code stringlengths 281 23.7M |
|---|
def demo(use_files=False, dir_name=None, config_filename='', title='Traits UI Demos', css_filename='default.css'):
if (dir_name is None):
dir_name = dirname(abspath(sys.argv[0]))
(path, name) = split(dir_name)
if ((len(config_filename) > 0) and (not isabs(config_filename))):
config_filename ... |
class EmmetInsertAttribute(sublime_plugin.TextCommand):
def run(self, edit, attribute=None, **kw):
if (not attribute):
return
prefix = ''
if self.view.sel():
sel = self.view.sel()[0]
if (not self.view.substr(sublime.Region((sel.begin() - 1), sel.begin())).... |
class SwapBrackets(BracketRemove):
def run(self, edit, name, remove_content=False, remove_indent=False, remove_block=False):
offset = self.left.toregion().size()
selection = [sublime.Region(self.left.begin, (self.right.begin - offset))]
left = self.left.move(self.left.end, self.left.end)
... |
class Resolver():
ball_ball: BallBallCollisionStrategy
ball_linear_cushion: BallLCushionCollisionStrategy
ball_circular_cushion: BallCCushionCollisionStrategy
ball_pocket: BallPocketStrategy
stick_ball: StickBallCollisionStrategy
transition: BallTransitionStrategy
def resolve(self, shot: Sys... |
class Circle(Html.Html):
name = 'Progress Circle'
def __init__(self, value: float, page: primitives.PageModel, width: tuple, height: tuple, html_code: Optional[str], options: Optional[dict], profile: Optional[Union[(dict, bool)]]):
page.properties.css.add_text("\ --pgPercentage {\n syntax: '<number>';\... |
class TestSequenceFunctions_FlatTree(unittest.TestCase):
def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args, **kwargs)
def setUp(self):
self.tree = hamDb.BkHammingTree()
for x in range(4):
with self.tree.writer_context():
... |
def bulk_run_local_args__init__(self, device_to_commands=None, timeout=bulk_run_local_args.thrift_spec[3][4], open_timeout=bulk_run_local_args.thrift_spec[4][4], client_ip=bulk_run_local_args.thrift_spec[10][4], client_port=bulk_run_local_args.thrift_spec[11][4], uuid=bulk_run_local_args.thrift_spec[12][4]):
self.d... |
class RunLevelParams(PyFlyteParams):
project: str = make_click_option_field(project_option)
domain: str = make_click_option_field(domain_option)
destination_dir: str = make_click_option_field(click.Option(param_decls=['--destination-dir', 'destination_dir'], required=False, type=str, default='/root', show_d... |
def _wrap_type_validation(template: object, callable_mock: _CallableMock, callable_templates: List[Callable]) -> Callable:
def callable_mock_with_type_validation(*args: Any, **kwargs: Any) -> Any:
for callable_template in callable_templates:
if _validate_callable_signature(False, callable_templa... |
def filter_endpoint_control_fctems_data(json):
option_list = ['admin_password', 'admin_username', 'call_timeout', 'capabilities', 'certificate', 'cloud_server_type', 'dirty_reason', 'ems_id', 'fortinetone_cloud_authentication', ' 'interface', 'interface_select_method', 'name', 'out_of_sync_threshold', 'preserve_ssl... |
class FrappeClient(object):
def __init__(self, url=None, username=None, password=None, api_key=None, api_secret=None, verify=True):
self.headers = dict(Accept='application/json')
self.session = requests.Session()
self.can_download = []
self.verify = verify
self.url = url
... |
def main(argv):
fuzzers_dir = os.path.abspath(os.path.dirname(__file__))
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('fuzzer', help='fuzzer to run')
parser.add_argument('--retries', type=int, default=0, help='Retry a failed fuzzer n times.')
args = parser.parse_args()
... |
(np.conjugate, np.conj)
def conjugate(x, out=None, out_like=None, sizing='optimal', method='raw', **kwargs):
def _conjugate_raw(x, n_frac, **kwargs):
precision_cast = ((lambda m: np.array(m, dtype=object)) if (n_frac >= _n_word_max) else (lambda m: m))
val_real = np.vectorize((lambda v: v.real))(x.v... |
def decoder_factory_from_dict(feature_map: Mapping[(str, FEATURE_DESCRIPTOR)], dtype_map: Mapping[(str, Any)]) -> DECODER_TYPE:
def _decoder(sample: TF_TENSOR):
return {key: tf.cast(tensor, dtype=dtype_map[key]) for (key, tensor) in tf.io.parse_single_example(sample, feature_map).items()}
return _decode... |
class AgentComponentRegistry(Registry[(ComponentId, Component)]):
__slots__ = ('_components_by_type', '_registered_keys')
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._components_by_type: Dict[(ComponentType, Dict[(PublicId, Component)])] = {}
self._register... |
class OptionSeriesScatter3dDataAccessibility(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._config(fla... |
class CustomFormDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
event = None
if view_kwargs.get('event_id'):
event = safe_query_kwargs(Event, view_kwargs, 'event_id')
elif view_kwargs.get('event_identifier'):
event = safe_query_kwargs(Event, view_kwa... |
def main() -> None:
setup_version = get_setup_version(setup_file_path)
pypi_version = get_pypi_version(package)
if (version_parse(setup_version) > version_parse(pypi_version)):
print(f'setup.py {setup_version} is higher than Pypi version {pypi_version}')
print('higher')
elif (version_par... |
class AudioInterface():
def audio__speech_to_text_async__launch_job(self, file: str, language: str, speakers: int, profanity_filter: bool, vocabulary: Optional[List[str]], audio_attributes: tuple, model: str=None, file_url: str='', provider_params: dict=dict()) -> AsyncLaunchJobResponseType:
raise NotImplem... |
def test_set_fill_pattern_url():
with Image(width=50, height=50, background='white') as img:
was = img.signature
with Drawing() as ctx:
ctx.push_pattern('green_circle', 0, 0, 10, 10)
ctx.fill_color = 'green'
ctx.stroke_color = 'black'
ctx.circle(origin... |
class OptionPlotoptionsPolygonSonificationTracksMappingNoteduration(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):
... |
_project_chroots_ns.route('/')
class ProjectChroot(Resource):
_to_parameters
_project_chroots_ns.doc(params=project_chroot_get_params)
_project_chroots_ns.marshal_with(project_chroot_model)
def get(self, ownername, projectname, chrootname):
copr = get_copr(ownername, projectname)
chroot ... |
class TutorialMirror(DefaultObject):
def return_appearance(self, looker, **kwargs):
if isinstance(looker, self.__class__):
return 'The image of yourself stretches into infinity.'
return f'''{self.key} shows your reflection:
{looker.db.desc}'''
def msg(self, text=None, from_obj=None, ... |
_member_required
def remove_document_storage(request, uuid, metadata_uuid=None):
uuid = UUID(uuid)
if (metadata_uuid is not None):
metadata_uuid = UUID(metadata_uuid)
doc = get_object_or_404(Document, uuid=uuid)
if (metadata_uuid is not None):
has = get_object_or_404(DocumentHasBinaryMet... |
class Ui_OpenNewick():
def setupUi(self, OpenNewick):
OpenNewick.setObjectName('OpenNewick')
OpenNewick.resize(569, 353)
self.comboBox = QtGui.QComboBox(OpenNewick)
self.comboBox.setGeometry(QtCore.QRect(460, 300, 81, 23))
self.comboBox.setObjectName('comboBox')
self.... |
def test_forum_get_topics(topic, user):
forum = topic.forum
with current_app.test_request_context():
login_user(user)
topics = Forum.get_topics(forum_id=forum.id, user=current_user)
assert (topics.items == [(topic, topic.last_post, None)])
logout_user()
topics = Forum.get... |
class ESDevRunner(ESMasterRunner):
n_eval_rollouts: int
(ESMasterRunner)
def create_distributed_rollouts(self, env: Union[(StructuredEnv, StructuredEnvSpacesMixin)], shared_noise: SharedNoiseTable, agent_instance_seed: int) -> ESDistributedRollouts:
return ESDummyDistributedRollouts(env=env, shared_... |
('subprocess.run')
def test_command_authenticator(mock_subprocess: MagicMock):
with pytest.raises(AuthenticationError):
authn = CommandAuthenticator(None)
authn = CommandAuthenticator(['echo'])
authn.refresh_credentials()
assert authn._creds
mock_subprocess.assert_called()
mock_subproces... |
class lift(_coconut_base_callable):
__slots__ = ('func',)
def __new__(cls, func, *func_args, **func_kwargs):
self = _coconut.super(lift, cls).__new__(cls)
self.func = func
if (func_args or func_kwargs):
self = self(*func_args, **func_kwargs)
return self
def __redu... |
('foremast.securitygroup.create_securitygroup.get_security_group_id')
('foremast.securitygroup.create_securitygroup.get_properties')
('foremast.securitygroup.create_securitygroup.get_details')
def test_missing_configuration(get_details, get_properties, get_sec_id):
get_properties.return_value = {}
security_grou... |
class FirstSwitch():
def __init__(self, gr):
self.gr = gr
def __call__(self, *args, **kw):
gr = self.gr
del gr.switch
(run, gr.run) = (gr.run, None)
t = stackless.tasklet(run)
gr.t = t
tasklet_to_greenlet[t] = gr
t.setup(*args, **kw)
t.run(... |
def get_command_search(text):
parts = text.split(None, 1)
if (parts[0] not in ['/r', '/e', '/t']):
abort(400, ('invalid command %r' % parts[0]))
if (len(parts) != 2):
abort(400, ('missing argument to command %r' % parts[0]))
(command, arg) = parts
if (command == '/r'):
return... |
class BookmarkListForm(forms.Form):
org_bookmarks = forms.MultipleChoiceField(label='Alerts about organisations', widget=forms.CheckboxSelectMultiple())
search_bookmarks = forms.MultipleChoiceField(label='Alerts about searches', widget=forms.CheckboxSelectMultiple())
ncso_concessions_bookmarks = forms.Multi... |
class ReflectionServiceStub(object):
def __init__(self, channel):
self.ListAllInterfaces = channel.unary_unary('/cosmos.base.reflection.v1beta1.ReflectionService/ListAllInterfaces', request_serializer=cosmos_dot_base_dot_reflection_dot_v1beta1_dot_reflection__pb2.ListAllInterfacesRequest.SerializeToString, ... |
class EventTap(object):
def __init__(self):
self._taps = {}
def tap(self, *cores):
for core in cores:
for k in dir(core.events):
if k.startswith('__'):
continue
hub = getattr(core.events, k)
if (not isinstance(hub, E... |
def extractSparemysiteWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
titlemap = [('IWBKD Chapter', 'I was Born as the Kings Daughter', 'translated')]
for (titlecomponent,... |
class Events(enum.Enum):
TIMER_START = 0
TIMER_UPDATE = 1
TIMER_STOP = 2
TIMER_END = 3
SESSION_READY = 4
SESSION_START = 5
SESSION_INTERRUPT = 6
SESSION_CHANGE = 7
SESSION_END = 8
SESSION_RESET = 9
WINDOW_SHOW = 10
WINDOW_HIDE = 11
CONFIG_CHANGE = 12 |
class ResumeDialog(xbmcgui.WindowXMLDialog):
resumePlay = (- 1)
resumeTimeStamp = ''
action_exitkeys_id = None
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
log.debug('ResumeDialog INITIALISED')
def onInit(self):
self.action_exit... |
def check_file(filename, *, expected=None):
(kind, st) = _get_file_kind(filename)
if (not kind):
return None
kinds = kind.split()
if callable(expected):
if (not expected(filename, kinds)):
return None
elif (expected and (expected is not True)):
if isinstance(expec... |
def memoize(f):
global total_memoized_functions
total_memoized_functions += 1
cache: Dict[(Any, Any)] = {}
(f)
def wrapper(*args):
if count_calls:
global total_memoized_calls
total_memoized_calls += 1
function_calls.add_item(f)
key = MemoizationKey... |
def generate_thumbnail():
import tempfile
import glob
from anima.dcc import mayaEnv
m_env = mayaEnv.Maya()
v = m_env.get_current_version()
if (not v):
return
if ('' in v.take_name):
return
task = v.task
project = task.project
imf = project.image_format
width =... |
class OptionSeriesPackedbubbleSonificationTracksMappingHighpassResonance(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_retrieve_from_
with RetrieveFileFromUri(URL).get_file_object() as f:
c = f.read()
assert (type(c) is bytes)
assert (len(c) > 0)
with RetrieveFileFromUri(URL).get_file_object(True) as f:
c = f.read()
assert (type(c) is str)
assert (len(c) > 0) |
class TestMrtlib(unittest.TestCase):
def test_reader(self):
files = ['rib..0000_pick.bz2', 'updates..0000.bz2']
for f in files:
counter = 0
input_file = os.path.join(MRT_DATA_DIR, f)
for record in mrtlib.Reader(bz2.BZ2File(input_file, 'rb')):
ok_((... |
class TestColumnIntegerToIndex(unittest.TestCase):
def test_column_integer_to_index(self):
self.assertEqual(column_integer_to_index(0), 'A')
self.assertEqual(column_integer_to_index(1), 'B')
self.assertEqual(column_integer_to_index(25), 'Z')
self.assertEqual(column_integer_to_index(2... |
class BaseLandingArea(BaseDataLakeArea, abc.ABC):
schemas = LandingSchemas
def _github_repositories_base(self):
return 'github/repository'
def save_push_events_commits(self, push_event_commits, date: datetime):
raise NotImplementedError()
def get_hour_push_events_commits(self, date: date... |
def check_strava_connection():
if (not strava_connected()):
return html.A(className='col-lg-12', children=[dbc.Button('Connect Strava', id='connect-strava-button', color='primary', className='mb-2', size='sm')], href=connect_strava_link(get_strava_client()))
else:
return html.H4('Strava Connecte... |
def deno_parser(subparser):
subparser.set_defaults(func=deno)
subparser.add_argument('-n', '--name', required=True, help='The name of the page to be transpiled (without the extension)')
subparser.add_argument('-p', '--path', help='The path where the new environment will be created: -p /foo/bar') |
def test_no_summary_not_seeking(tmpdir: Path):
filepath = (tmpdir / 'no_summary.mcap')
write_no_summary_mcap(filepath)
with open(filepath, 'rb') as f:
assert (len(list(NonSeekingReader(f).iter_messages())) == 200)
with open(filepath, 'rb') as f:
assert (len(list(NonSeekingReader(f).iter_... |
def test_alternative_hashing_algorithms(data_dir_mirror):
fname = str((data_dir_mirror / 'tiny-data.txt'))
check_tiny_data(fname)
with open(fname, 'rb') as fin:
data = fin.read()
for alg in ('sha512', 'md5'):
hasher = hashlib.new(alg)
hasher.update(data)
registry = {'tiny... |
class OptionSeriesStreamgraphSonificationContexttracksMappingGapbetweennotes(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... |
def bootstrap_registries(enable_cache: bool=True, catch_exception: bool=True):
global _IS_BOOTSTRAPPED
if _IS_BOOTSTRAPPED:
logger.warning('Registries are already bootstrapped, skipped!')
return
if _INSIDE_BOOTSTRAP:
_log(1, 'calling bootstrap_registries() inside bootstrap process, s... |
class PornEmbyCheckin(AnswerBotCheckin):
name = 'Pornemby'
bot_username = 'PronembyTGBot2_bot'
bot_success_pat = '.*?(\\d+)$'
async def start(self):
if (not self.client.me.username):
self.log.warning(f': .')
return None
return (await super().start())
async def... |
def calc_dataset_item(cache: Tuple[(Tuple[(int, ...)], ...)], i: int) -> Tuple[(int, ...)]:
n = len(cache)
r = (HASH_BYTES // WORD_BYTES)
mix = keccak_512(int_to_le_bytes((le_uint32_sequence_to_uint(cache[(i % n)]) ^ i), HASH_BYTES))
mix_integers = le_bytes_to_uint32_sequence(mix)
for j in range(DAT... |
class OptionSeriesFunnel3dStatesHoverHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(num, j... |
class Cubelet():
def __init__(self, cube, coords, coords_names=None):
self._coords_names = coords_names
self.owner = cube
assert all((isinstance(_, int) for _ in coords)), coords
self.coords = coords
self.flatten_values = cube.flatten_values
def __repr__(self):
re... |
def build_database(sql_files):
print('\n* Building the database...')
db_conn = sqlite3.connect(':memory:')
cur = db_conn.cursor()
for sql_file in sql_files:
if ('migratedTables' in sql_file):
print((' * Skipping %s...' % sql_file))
continue
print((' * Running %s... |
class OptionSeriesVariwideTooltipDatetimelabelformats(Options):
def day(self):
return self._config_get('%A, %e %b %Y')
def day(self, text: str):
self._config(text, js_type=False)
def hour(self):
return self._config_get('%A, %e %b, %H:%M')
def hour(self, text: str):
self._... |
def extractExecutionergirlWordpressCom(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... |
class LocalFileDAGLoader(DAGLoader):
def __init__(self, dag_dirs: List[str]) -> None:
self._dag_dirs = dag_dirs
def load_dags(self) -> List[DAG]:
dags = []
for filepath in self._dag_dirs:
if (not os.path.exists(filepath)):
continue
if os.path.isdir... |
class AgentDialogue(TacDialogue):
def __init__(self, dialogue_label: DialogueLabel, self_address: Address, role: BaseDialogue.Role, message_class: Type[TacMessage]) -> None:
TacDialogue.__init__(self, dialogue_label=dialogue_label, self_address=self_address, role=role, message_class=message_class) |
def prompt_credentials():
credentials = config.get('koapy.backend.kiwoom_open_api_plus.credentials')
default_user_id = credentials['user_id']
default_user_password = credentials['user_password']
default_server = ('simulation' if credentials['is_simulation'] else 'real')
default_cert_password = crede... |
class MapboxVectorTileSerializer(Serializer):
mimetype: ClassVar[str] = 'application/vnd.mapbox-vector-tile'
def loads(self, data: bytes) -> bytes:
return data
def dumps(self, data: bytes) -> bytes:
if isinstance(data, bytes):
return data
raise SerializationError(f'Cannot... |
def run():
print('\nmodule top();\n ')
params = {}
sites = list(gen_brams())
fuzz_iter = iter(util.gen_fuzz_states((len(sites) * 5)))
for (tile_name, bram_sites, int_tiles) in sites:
(b0_diadi3, b1_wraddr10, b1_wraddr9, b1_wraddr13, b1_diadi7) = itertools.islice(fuzz_iter, 5)
para... |
class OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingTremoloDepth(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, te... |
_member_required
def import_documents(request):
if (request.method == 'POST'):
print(request.POST)
form = ImportDocumentsForm(request.POST, request.FILES)
print(form)
files = request.FILES.getlist('files')
print(files)
if form.is_valid():
print('got ', len... |
class CriteoDataModule(pl.LightningDataModule):
def __init__(self, num_days: int=1, num_days_test: int=0, num_embeddings: Optional[int]=100000, num_embeddings_per_feature: Optional[List[int]]=None, batch_size: int=32, train_percent: float=0.8, num_workers: int=0, read_chunk_size: int=100000, dataset_name: str='crit... |
class DividerNotchesEdge(edges.BaseEdge):
description = 'Edge with multiple notches for easier access to dividers'
def __init__(self, boxes, sx) -> None:
super().__init__(boxes, None)
self.sx = sx
def __call__(self, _, **kw):
first = True
for width in self.sx:
if ... |
(scope='function')
def tooltip_manager(request, bar_position, manager_nospawn):
widget = TooltipWidget('Testint', **{**{'tooltip_delay': 0.5}, **getattr(request, 'param', dict())})
class TooltipConfig(libqtile.confreader.Config):
auto_fullscreen = True
keys = []
mouse = []
groups... |
def compute_metrics(pred: Tensor, gt: Tensor, mask: Optional[Tensor]=None, extra=False) -> Dict[(str, float)]:
metrics = {'psnr': compute_psnr(pred, gt, mask)}
if ((mask is not None) or (not extra)):
return metrics
metrics['ssim'] = compute_ssim(pred, gt)
if (lpips_net is not None):
metr... |
class Sentiment(GeneratedFeature):
column_name: str
def __init__(self, column_name: str, display_name: Optional[str]=None):
self.column_name = column_name
self.display_name = display_name
super().__init__()
def generate_feature(self, data: pd.DataFrame, data_definition: DataDefinitio... |
class Event(TraitType):
default_value_type = DefaultValue.constant
def __init__(self, trait=None, **metadata):
metadata['type'] = 'event'
metadata['transient'] = True
super().__init__(**metadata)
self.trait = None
if (trait is not None):
self.trait = trait_fro... |
class TypeDoc():
type: object
doc: object
def print_text(self, indent=0):
color_kw = color_theme['keyword']
color_class = color_theme['name_class']
params = [str(p) for p in self.type.elems]
params = ', '.join(params)
if params:
params = f'\[{params}]'
... |
def test_loop_to_sequence_rule_1():
ast = AbstractSyntaxForest(condition_handler=condition_handler1(LogicCondition.generate_new_context()))
root = ast.factory.create_endless_loop_node()
body = ast.factory.create_seq_node()
children = [ast.factory.create_code_node(stmts=[assignment_c_plus_5.copy()]), ast... |
class Slice():
def __init__(self, source_class, offset, number_of_lines):
self.source_class = source_class
self.source = None
self.offset = offset
self.number_of_lines = number_of_lines
self.current_line = 0
self.bulk_size = None
self.logger = logging.getLogge... |
def pytest_collection_modifyitems(items, config):
flaky_tests = []
non_flaky_tests = []
for item in items:
if (any(((_ in item.fixturenames) for _ in ('async_unlocked_account', 'async_unlocked_account_dual_type', 'unlocked_account', 'unlocked_account_dual_type'))) and ('offchain_lookup' not in item.... |
class OptionPlotoptionsTreemapLevelsColorvariation(Options):
def key(self):
return self._config_get(None)
def key(self, value: Any):
self._config(value, js_type=False)
def to(self):
return self._config_get(None)
def to(self, num: float):
self._config(num, js_type=False) |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/launchctl'
common.create_macos_masquerade(masquerade)
common.log('Launching fake launchctl command to mimic env variable hijacking')
common.execute([masquerade, 'setenv'], timeout=10, kill=True)
common.remove_file(masquerade) |
class OptionSeriesAreasplinerangeTooltip(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) -> 'OptionSeriesAreasplinerangeTooltipDate... |
def gen_sites():
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
for tile_name in sorted(grid.tiles()):
loc = grid.loc_of_tilename(tile_name)
gridinfo = grid.gridinfo_at_loc(loc)
sites = {}
for (site_name, site_type) in gridinfo.sites.items():
... |
class RequestBuildOperator(MapOperator[(RequestInput, ModelRequest)], ABC):
def __init__(self, model: Optional[str]=None, **kwargs):
self._model = model
super().__init__(**kwargs)
async def map(self, input_value: RequestInput) -> ModelRequest:
req_dict = {}
if isinstance(input_va... |
.django_db
def test_spending_over_time_subawards_success(client):
resp = client.post('/api/v2/search/spending_over_time', content_type='application/json', data=json.dumps({'group': 'quarter', 'filters': non_legacy_filters(), 'subawards': True}))
assert (resp.status_code == status.HTTP_200_OK) |
.integration
class TestThermometerSkillFetchaiLedger(AEATestCaseManyFlaky):
.flaky(reruns=MAX_FLAKY_RERUNS_INTEGRATION)
def test_thermometer(self):
thermometer_aea_name = 'my_thermometer'
thermometer_client_aea_name = 'my_thermometer_client'
self.create_agents(thermometer_aea_name, therm... |
(private_key_bytes=private_key_st)
(max_examples=MAX_EXAMPLES)
def test_public_key_generation_is_equal(private_key_bytes, native_key_api, coincurve_key_api):
native_public_key = native_key_api.PrivateKey(private_key_bytes).public_key
coincurve_public_key = coincurve_key_api.PrivateKey(private_key_bytes).public_... |
def nextCmd(snmpDispatcher, authData, transportTarget, *varBinds, **options):
def cbFun(*args, **kwargs):
response[:] = (args + (kwargs.get('nextVarBinds', ()),))
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls ... |
def closest(color: Color, colors: Sequence[ColorInput], method: (str | None)=None, **kwargs: Any) -> Color:
if (method is None):
method = color.DELTA_E
algorithm = color.DE_MAP.get(method)
if (not algorithm):
raise ValueError("'{}' is not currently a supported distancing algorithm.".format(m... |
class JsHtmlTabulator(JsHtml.JsHtml):
def val(self):
return JsObjects.JsObjects.get(('{%s: {value: %s, timestamp: Date.now(), offset: new Date().getTimezoneOffset()}}' % (self.htmlCode, self.content.toStr())))
def content(self):
return JsHtml.ContentFormatters(self.page, ('%s.getData()' % self.c... |
def get_templates_dir():
res_dir = None
try:
res_dir = resource_filename(Requirement.parse('ambassador'), 'templates')
except:
pass
maybe_dirs = [res_dir, os.path.join(os.path.dirname(__file__), '..', 'templates')]
for d in maybe_dirs:
if (d and os.path.isdir(d)):
... |
class Test(unittest.TestCase):
def testCreate(self):
f = fourway.T('hello', 'fourway')
self.assertTrue(f)
def testAddToWindow(self):
w = Gtk.Window()
f = fourway.T('wibble', 'fourway')
w.set_child(f)
w.present()
def testMouseButton1(self):
f = fourway.... |
def test_regression_performance_metrics() -> None:
test_dataset = pd.DataFrame({'category_feature': ['1', '2', '3'], 'numerical_feature': [3, 2, 1], 'target': [1, 2, 3], 'prediction': [1, np.NAN, 1]})
data_mapping = ColumnMapping()
report = Report(metrics=[RegressionPerformanceMetrics()])
report.run(cur... |
class TransactionTruncator(object):
def __init__(self):
self.log = logging.getLogger('Main.DbVersioning.TransactionTruncator')
self.qlog = logging.getLogger('Main.DbVersioning.TransactionTruncator.Query')
def truncate_transaction_table(self):
with db.session_context() as sess:
... |
def test_path_dir_created():
with spacy.util.make_tempdir() as tmpdir:
config = copy.deepcopy(_DEFAULT_CFG)
assert (not (tmpdir / 'new_dir').exists())
config['cache']['path'] = str((tmpdir / 'new_dir'))
spacy.blank('en').add_pipe('llm', config=config)
assert (tmpdir / 'new_di... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Topic', fields=[('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.CharField(max_length=200)), ('date_added', models.DateTimeF... |
class OptionSeriesColumnrangeStatesInactive(Options):
def animation(self) -> 'OptionSeriesColumnrangeStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesColumnrangeStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
def get_bins(bin_size, chrom_size, region=None):
bin_intvals = []
start = 0
if region:
(chrom_size, start, _, _) = getUserRegion(chrom_size, region)
for (chrom, size) in chrom_size:
for interval in range(start, size, bin_size):
bin_intvals.append((chrom, interval, min(size, (... |
def project_settings_with_dotenv(testproject, env_file):
project_config = copy.deepcopy(BASE_PROJECT_CONFIG)
project_config['dotenv'] = str(env_file)
project_config['networks']['development']['default_balance'] = '${DEFAULT_BALANCE}'
if ('console' not in project_config):
project_config['console'... |
class TestVTKDataSource(TestContour):
def make_data(self):
script = self.script
from mayavi.sources.vtk_data_source import VTKDataSource
from tvtk.api import tvtk
s = self.new_scene()
r = tvtk.StructuredPointsReader()
r.file_name = get_example_data('heart.vtk')
... |
class ChainOfStates():
logger = logging.getLogger('cos')
valid_coord_types = ('cart', 'cartesian', 'dlc')
def __init__(self, images, fix_first=True, fix_last=True, align_fixed=True, climb=False, climb_rms=0.005, climb_lanczos=False, climb_lanczos_rms=0.005, climb_fixed=True, energy_min_mix=False, scheduler=... |
class FedAvgWithLRSyncAggregator(SyncAggregatorWithOptimizer):
def __init__(self, *, global_model: IFLModel, channel: Optional[IdentityChannel]=None, **kwargs) -> None:
init_self_cfg(self, component_class=__class__, config_class=FedAvgWithLRSyncAggregatorConfig, **kwargs)
super().__init__(global_mod... |
class OptionSeriesDependencywheelSonificationTracksMappingFrequency(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):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.