code stringlengths 281 23.7M |
|---|
class DefaultGuest(DefaultAccount):
def create(cls, **kwargs):
return cls.authenticate(**kwargs)
def authenticate(cls, **kwargs):
errors = []
account = None
username = None
ip = kwargs.get('ip', '').strip()
if (not settings.GUEST_ENABLED):
errors.appen... |
class OptionPlotoptionsParetoSonificationDefaultinstrumentoptionsActivewhen(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... |
.django_db
def test_date_range(award_data_fixture, elasticsearch_award_index):
elasticsearch_award_index.update_index()
should = {'bool': {'should': [{'range': {'action_date': {'gte': '2010-10-01'}}}, {'range': {'date_signed': {'lte': '2011-09-30'}}}], 'minimum_should_match': 2}}
query = create_query(should... |
def get_geoms(images=KWARGS['images']):
initial = 'xyz_files/hcn.xyz'
ts_guess = 'xyz_files/hcn_iso_ts.xyz'
final = 'xyz_files/nhc.xyz'
xyz_fns = (initial, ts_guess, final)
atoms_coords = [parse_xyz_file(fn) for fn in xyz_fns]
geoms = [Geometry(atoms, coords.flatten()) for (atoms, coords) in ato... |
.django_db
class BaseConversationTagsTestCase(object):
(autouse=True)
def setup(self):
self.loadstatement = '{% load forum_conversation_tags %}'
self.request_factory = RequestFactory()
self.g1 = GroupFactory.create()
self.u1 = UserFactory.create()
self.u2 = UserFactory.cr... |
def extractUnderworldersBlogspotCom(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_ty... |
def test_task_set_system_controlsts_exclusively(task_definition):
assert (len(task_definition.containers[0]['systemControls']) == 1)
assert ('net.core.somaxconn' == task_definition.containers[0]['systemControls'][0]['namespace'])
task_definition.set_system_controls(((u'webserver', u'net.ipv4.ip_forward', u'... |
class ObjectClassFinancialSpendingViewSet(CachedDetailViewSet):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/financial_spending/major_object_class.md'
serializer_class = ObjectClassFinancialSpendingSerializer
def get_queryset(self):
json_request = self.request.query_params
fisc... |
def metrics_store(cfg, read_only=True, track=None, challenge=None, car=None, meta_info=None):
cls = metrics_store_class(cfg)
store = cls(cfg=cfg, meta_info=meta_info)
logging.getLogger(__name__).info('Creating %s', str(store))
race_id = cfg.opts('system', 'race.id')
race_timestamp = cfg.opts('system... |
class FullTextProcessorConfig(NamedTuple):
extract_front: bool = True
extract_authors: bool = True
extract_affiliations: bool = True
extract_body_sections: bool = True
extract_acknowledgements: bool = True
extract_back_sections: bool = True
extract_references: bool = True
extract_citatio... |
class Tokenizer(object):
_pyopmap = {'(': tokenize.LPAR, ')': tokenize.RPAR, '[': tokenize.LSQB, ']': tokenize.RSQB, ':': tokenize.COLON, ',': tokenize.COMMA, ';': tokenize.SEMI, '+': tokenize.PLUS, '+=': tokenize.PLUSEQUAL, '-': tokenize.MINUS, '-=': tokenize.MINEQUAL, '*': tokenize.STAR, '**': tokenize.DOUBLESTAR... |
def test_cube_attr_mean_two_surfaces_multiattr(tmpdir, load_cube_rsgy1, generate_plot):
xs1 = xtgeo.surface_from_file(RTOP1)
xs2 = xtgeo.surface_from_file(RBAS1)
kube = load_cube_rsgy1
xss = xs1.copy()
xss.slice_cube_window(kube, other=xs2, other_position='below', attribute='rms', sampling='trilinea... |
class aggregate_stats_reply(stats_reply):
version = 5
type = 19
stats_type = 2
def __init__(self, xid=None, flags=None, packet_count=None, byte_count=None, flow_count=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
... |
.skipif((sys.platform in {'win32', 'linux'}), reason='macOS specific test')
def test_macos_open_privacy_settings_logs_exception(monkeypatch, caplog):
def mocked_run(*_, **__):
raise ValueError("Mocked exception on 'open' call")
monkeypatch.setattr(subprocess, 'run', mocked_run)
with caplog.at_level(... |
def upload_csv(resource_name, data, gcs_upload_path):
try:
with csv_writer.write_csv(resource_name, data, True) as csv_file:
LOGGER.info('CSV filename: %s', csv_file.name)
storage_client = StorageClient({})
storage_client.put_text_file(csv_file.name, gcs_upload_path)
... |
def create_class_type(rid, type_desc):
if (type_desc == 'implementable'):
return ClassTypeImplementable()
if (type_desc == 'detailable'):
return ClassTypeDetailable()
if (type_desc == 'selected'):
return ClassTypeSelected()
raise RMTException(95, ("%s:class type invalid '%s'" % (... |
('ecs_deploy.cli.get_client')
def test_deploy(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME))
assert (result.exit_code == 0)
assert (not result.exception)
assert (u'Deploying based on task defini... |
.parametrize('threshold', [0.3, 0.5, 0.8])
.parametrize('y_true, y_pred', [(binary_raw_inputs.target, binary_raw_inputs.preds), (binary_prob_inputs.target, binary_prob_inputs.preds)])
def test_accuracy(y_true, y_pred, threshold):
sk_preds = (y_pred.view((- 1)).numpy() >= threshold).astype(np.uint8)
sk_target = ... |
def test_matcher_regex_shape(en_vocab):
matcher = Matcher(en_vocab)
pattern = [{'SHAPE': {'REGEX': '^[^x]+$'}}]
matcher.add('NON_ALPHA', [pattern])
doc = Doc(en_vocab, words=['99', 'problems', '!'])
matches = matcher(doc)
assert (len(matches) == 2)
doc = Doc(en_vocab, words=['bye'])
matc... |
class Association(Base):
__tablename__ = 'association'
cve_id = Column(String(), ForeignKey('cves.cve_id'), primary_key=True)
cpe_id = Column(String(), ForeignKey('cpes.cpe_id'), primary_key=True)
version_start_including = Column(String())
version_start_excluding = Column(String())
version_end_i... |
class TestDemoDocs():
def setup_class(cls):
md_path = os.path.join(ROOT_DIR, 'docs', 'generic-skills-step-by-step.md')
code_blocks = extract_code_blocks(filepath=md_path, filter_='python')
cls.generic_seller = code_blocks[0:11]
cls.generic_buyer = code_blocks[11:len(code_blocks)]
... |
_register_parser
_set_msg_type(ofproto.OFPT_ERROR)
class OFPErrorMsg(MsgBase):
def __init__(self, datapath, type_=None, code=None, data=None, **kwargs):
super(OFPErrorMsg, self).__init__(datapath)
self.type = type_
self.code = code
if isinstance(data, six.string_types):
d... |
class Net(nn.Module):
def __init__(self, num_classes=576, reid=False):
super(Net, self).__init__()
self.conv = nn.Sequential(nn.Conv2d(3, 64, 3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, padding=1))
self.layer1 = make_layers(64, 64, 2, False)
... |
def _check_preliminaries() -> None:
try:
import aea
except ModuleNotFoundError:
enforce(False, "'aea' package not installed.")
enforce((shutil.which('black') is not None), 'black command line tool not found.')
enforce((shutil.which('isort') is not None), 'isort command line tool not foun... |
class ToptierAgencyPublishedDABSView(models.Model):
toptier_code = models.TextField()
name = models.TextField()
abbreviation = models.TextField()
toptier_agency = models.OneToOneField('references.ToptierAgency', on_delete=models.DO_NOTHING, primary_key=True, related_name='%(class)s')
agency = models... |
class OptionPlotoptionsPyramid3dEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._... |
class TestPythonProperty(unittest.TestCase):
def test_read_only_property(self):
model = Model()
self.assertEqual(model.read_only, 1729)
with self.assertRaises(AttributeError):
model.read_only = 2034
with self.assertRaises(AttributeError):
del model.read_only
... |
class ThreeColumns(Layout):
def __init__(self, workspace_name: str, params: List[Any]):
super().__init__(LayoutName.THREE_COLUMNS, workspace_name)
try:
self.two_columns_main_ratio = (float(params[0]) if (len(params) > 0) else 0.5)
self.three_columns_main_ratio = (float(params... |
def upgrade():
op.create_table('fidesopsuserpermissions', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), ... |
class ExperimentalFlagsManager(LocaleMixin):
DEFAULT_VALUES = {'chats_per_page': 10, 'multiple_slave_chats': True, 'network_error_prompt_interval': 100, 'prevent_message_removal': True, 'auto_locale': True, 'retry_on_error': False, 'send_image_as_file': False, 'message_muted_on_slave': 'normal', 'your_message_on_sl... |
class DefaultScale(AbstractScale):
def __init__(self, formatter=None):
if (formatter is None):
formatter = BasicFormatter()
self.formatter = formatter
def ticks(self, start, end, desired_ticks=8):
if ((start == end) or isnan(start) or isnan(end)):
return [start]
... |
class BenjiStoreTestCase(BenjiTestCaseBase):
def generate_version(self, testpath):
size = ((512 * kB) + 123)
image_filename = os.path.join(testpath, 'image')
self.image = ((self.random_bytes((size - (2 * 128123))) + (b'\x00' * 128123)) + self.random_bytes(128123))
with open(image_fil... |
class TernaryOp(Node):
__slots__ = ('cond', 'iftrue', 'iffalse', 'coord', '__weakref__')
def __init__(self, cond, iftrue, iffalse, coord=None):
self.cond = cond
self.iftrue = iftrue
self.iffalse = iffalse
self.coord = coord
def children(self):
nodelist = []
if... |
def get_brew_arch(wf):
find_brew = brew_installed()
result = wf.settings.get('HOMEBREW_OPTS', None)
if (result is not None):
brew_arch = result['current_brew']
else:
brew_arch = ('ARM' if (find_brew['ARM'] and (not find_brew['INTEL'])) else 'INTEL')
return brew_arch |
class OptionPlotoptionsFunnelSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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(... |
def set_develop_mode(on=True, intensive_logging=False, skip_wait_methods=False):
from .. import io
if on:
defaults._mode_settings = [defaults.initialize_delay, defaults.window_mode, defaults.fast_quit, io.defaults.outputfile_time_stamp, defaults.auto_create_subject_id]
if intensive_logging:
... |
def expect(invocation, out, program=None, test='equals'):
if (program is None):
program = make_program()
program.run('fab {}'.format(invocation), exit=False)
output = sys.stdout.getvalue()
if (test == 'equals'):
assert (output == out)
elif (test == 'contains'):
assert (out in... |
def plugin_init(config, ingest_ref, callback):
global shutdown_in_progress, the_rpc
_LOGGER.info('plugin_init called')
_config = config
_config['ingest_ref'] = ingest_ref
_config['callback'] = callback
the_rpc = iprpc.IPCModuleClient('np_server', _module_dir)
_config['readings_buffer'] = lis... |
_cache(maxsize=1)
def get_yt_id(url, ignore_playlist=False):
query = urlparse(url)
if (query.hostname == 'youtu.be'):
return query.path[1:]
if (query.hostname in {'www.youtube.com', 'youtube.com', 'music.youtube.com'}):
if (not ignore_playlist):
with suppress(KeyError):
... |
class Command(DanubeCloudCommand):
help = 'Display Danube Cloud version.'
options = (CommandOption('-f', '--full', action='store_true', dest='full', default=False, help='Display full version string (including edition).'),)
def handle(self, full=False, **options):
from core.version import __version__... |
class ContextVarsContext(BaseContext):
elasticapm_transaction_var = contextvars.ContextVar('elasticapm_transaction_var')
elasticapm_spans_var = contextvars.ContextVar('elasticapm_spans_var', default=())
def get_transaction(self, clear: bool=False) -> 'elasticapm.traces.Transaction':
try:
... |
def preprocess_observation(observation: np.ndarray, key: jnp.ndarray) -> jnp.ndarray:
observation = observation.astype(jnp.float32)
observation = jnp.floor((observation / 8))
observation = (observation / 32)
observation = (observation + (jax.random.uniform(key, observation.shape) / 32))
observation ... |
class OptionPlotoptionsTimelineStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsTimelineStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsTimelineStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, fl... |
('/calls/view/<int:call_no>', methods=['GET'])
def calls_view(call_no):
sql = "SELECT\n a.CallLogID,\n CASE\n WHEN b.PhoneNo is not null then b.Name\n WHEN c.PhoneNo is not null then c.Name\n ELSE a.Name\n END Name,\n a.Number Number,\n a.Date,\n ... |
def get_layouts(layouts=None):
layouts_from_module = get_layouts_from_getters()
default_layouts = layouts_from_module.pop('default_layouts')
all_layouts = {}
for (idx, layout) in enumerate((default_layouts + (layouts or []))):
layout.module = 'default'
all_layouts[(layout.name or idx)] =... |
class TraitEnum(TraitHandler):
def __init__(self, *values):
if ((len(values) == 1) and (type(values[0]) in SequenceTypes)):
values = values[0]
self.values = tuple(values)
self.fast_validate = (ValidateTrait.enum, self.values)
def validate(self, object, name, value):
i... |
def _attr_to_optparse_option(at: Field, default: Any) -> Tuple[(dict, str)]:
if (at.name == 'url_schemes'):
return ({'metavar': '<comma-delimited>|<yaml-dict>', 'validator': _validate_url_schemes}, ','.join(default))
if (at.type is int):
return ({'metavar': '<int>', 'validator': _validate_int}, ... |
_cache()
def _load_config(env_code=None) -> Type[DefaultConfig]:
if (not env_code):
env_code = os.environ.get(ENV_CODE_VAR, _FALLBACK_ENV_CODE)
runtime_env = next((env for env in ENVS if (env['code'] == env_code)), None)
if (not runtime_env):
raise KeyError(f'Runtime environment with code={e... |
class Cmd(object):
CMD = NotImplemented
OK = 0
ERR_HOST_CHECK = 3
ERR_UNKNOWN = 99
msg = None
_time_started = 0
def __init__(self, host=None, verbose=False, **kwargs):
self.host = host
self.verbose = verbose
self.__dict__.update(kwargs)
self._time_started = ge... |
def parse(definition, parcel: ParcelParser, parent: Field) -> None:
names = definition.keys()
if ('__parcelType' in names):
parse_parcel_type(definition, parcel, parent)
elif ('__type' in names):
parse_generic_type(definition, parcel, parent)
elif ('__repeated' in names):
parse_r... |
(scope='function')
def strava(stravawidget):
class StravaConfig(libqtile.confreader.Config):
auto_fullscreen = True
keys = []
mouse = []
groups = [libqtile.config.Group('a')]
layouts = [libqtile.layout.Max()]
floating_layout = libqtile.resources.default_config.floatin... |
class BasicEdge(GraphEdgeInterface):
def __init__(self, source: GraphNodeInterface, sink: GraphNodeInterface):
self._source: GraphNodeInterface = source
self._sink: GraphNodeInterface = sink
def source(self) -> GraphNodeInterface:
return self._source
def sink(self) -> GraphNodeInterf... |
class News(commands.Cog):
__version__ = '0.0.3'
__author__ = 'flare#0001'
def format_help_for_context(self, ctx):
pre_processed = super().format_help_for_context(ctx)
return f'''{pre_processed}
Cog Version: {self.__version__}
Author: {self.__author__}'''
def __init__(self, bot):
... |
def test_example_tensor():
def t1(array: torch.Tensor) -> torch.Tensor:
return torch.flatten(array)
task_spec = get_serializable(OrderedDict(), serialization_settings, t1)
assert (task_spec.template.interface.outputs['o0'].type.blob.format is PyTorchTensorTransformer.PYTORCH_FORMAT) |
def start_north(start_north_omf_as_a_service, fledge_url, num_assets, pi_host, pi_port, pi_admin, pi_passwd, clear_pi_system_through_pi_web_api, pi_db):
global north_schedule_id
af_hierarchy_level_list = AF_HIERARCHY_LEVEL.split('/')
dp_list = ['']
asset_dict = {}
no_of_services = 6
num_assets_p... |
def events(request, **kwargs):
from .eventrequest import EventRequest
from .eventstream import EventPermissionError, get_events
from .utils import sse_error_response
try:
event_request = EventRequest(request, view_kwargs=kwargs)
event_response = get_events(event_request)
response... |
.django_db
def test_spending_over_time_new_awards_only_filter(client, monkeypatch, elasticsearch_transaction_index, populate_models):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
group = 'month'
test_payload = {'group': group, 'subawards': False, 'filters': {'time_period': [{'date_... |
class PZEM():
VOLT = 0
AMP = 1
WATT = 3
WHR = 5
FREQ = 7
PWRF = 8
def __init__(self, port, slaveaddress, timeout=0.1):
self.busy = False
self.initialized = False
self.port = port
self.timeout = timeout
self.address = slaveaddress
self.connect()... |
def export_speakers_csv(speakers):
headers = ['Speaker Name', 'Speaker Email', 'Speaker Session(s)', 'Speaker Mobile', 'Speaker Bio', 'Speaker Organisation', 'Speaker Position', 'Speaker Experience', 'Speaker Sponsorship Required', 'Speaker City', 'Speaker Country', 'Speaker Website', 'Speaker Twitter', 'Speaker Fa... |
(scope='function')
def redshift_connection_config(db: Session) -> Generator:
connection_config = ConnectionConfig.create(db=db, data={'name': str(uuid4()), 'key': 'my_redshift_config', 'connection_type': ConnectionType.redshift, 'access': AccessLevel.write})
host = (integration_config.get('redshift', {}).get('h... |
def find_omorfi(large_coverage=False) -> str:
dirs = ['/usr/local/share/omorfi/', '/usr/share/omorfi/']
if os.getenv('HOME'):
dirs += [(os.getenv('HOME') + '/.local/omorfi/')]
if os.getcwd():
cwd = os.getcwd()
dirs += [(cwd + '/src/generated/'), (cwd + '/generated/'), (cwd + '/')]
... |
class CheckGradientAction(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if is_color(value):
setattr(namespace, self.dest.upper(), value)
return
if REGEXP_PARAM_STRING.match(value):
(is_valid, reason) = is_rgbgradient(value)
... |
def convert_partial_iso_format_to_full_iso_format(partial_iso_format_time: str) -> str:
try:
date = datetime.fromisoformat(partial_iso_format_time)
time_zone_name = date.strftime('%Z')
time_zone = (tz.gettz(time_zone_name) if time_zone_name else tz.UTC)
date_with_timezone = date.repl... |
def check_template(slug: str, tests_path: Path, tmpfile: Path):
try:
check_ok = True
if (not tmpfile.is_file()):
logger.debug(f'{slug}: tmp file {tmpfile} not found')
check_ok = False
if (not tests_path.is_file()):
logger.debug(f'{slug}: tests file {tests_... |
def main() -> None:
parser = argparse.ArgumentParser(prog='GPTtrace', description='Use ChatGPT to write eBPF programs (bpftrace, etc.)')
parser.add_argument('-c', '--cmd', help='Use the bcc tool to complete the trace task', nargs=2, metavar=('CMD_NAME', 'QUERY'))
parser.add_argument('-v', '--verbose', help=... |
def lazy_import():
from fastly.model.backend_response import BackendResponse
from fastly.model.cache_setting_response import CacheSettingResponse
from fastly.model.condition_response import ConditionResponse
from fastly.model.director import Director
from fastly.model.domain_response import DomainRe... |
class DownBlock(nn.Module):
def __init__(self, opt, scale, n_feat=None, in_channels=None, out_channels=None):
super(DownBlock, self).__init__()
negval = opt.negval
if (n_feat is None):
n_feat = opt.n_feats
if (in_channels is None):
in_channels = opt.n_colors
... |
class ShutdownSignalHandler():
def __init__(self):
self.shutdown_count: int = 0
signal.signal(signal.SIGINT, self._on_signal_received)
signal.signal(signal.SIGTERM, self._on_signal_received)
def is_shutting_down(self):
return (self.shutdown_count > 0)
def _on_signal_received(... |
class AccessManualWebhooks(FidesSchema):
fields: ManualWebhookFieldsList
class Config():
orm_mode = True
('fields')
def check_for_duplicates(cls, value: List[ManualWebhookField]) -> List[ManualWebhookField]:
unique_pii_fields: Set[str] = {field.pii_field for field in value}
if (l... |
class TestTransactionManager():
()
def consumer(self):
return Mock(name='consumer', spec=Consumer)
()
def producer(self):
return Mock(name='producer', spec=Producer, create_topic=AsyncMock(), stop_transaction=AsyncMock(), maybe_begin_transaction=AsyncMock(), commit_transactions=AsyncMock... |
class THBEventDispatcher(EventDispatcher):
game: 'THBattle'
def populate_handlers(self) -> List[EventHandler]:
from thb.actions import COMMON_EVENT_HANDLERS
g = self.game
ehclasses = (list(COMMON_EVENT_HANDLERS) + list(g.game_ehs))
for c in getattr(g, 'players', ()):
... |
def lincomb(numbers, factors, adder=(lambda x, y: (x + y)), zero=0):
maxbitlen = max(((len(bin(f)) - 2) for f in factors))
subsets = [{i for i in range(len(numbers)) if (factors[i] & (1 << j))} for j in range((maxbitlen + 1))]
subset_sums = multisubset2(numbers, subsets, adder=adder, zero=zero)
o = zero... |
class Components():
def __init__(self, page: primitives.PageModel):
self.page = page
if (self.page.ext_packages is None):
self.page.ext_packages = {}
self.page.icons.add('bootstrap-icons', PkgImports.BOOTSTRAP)
self.page.imports.pkgs.bootstrap.version = '5.1.0'
se... |
def test_defaults_legacy():
html = '\n<input type="text" name="foo" value="bar" />\n<input type="text" name="foo" value="biz" />\n<input type="text" name="foo" value="bash" />\n'
expected_html = '\n<input type="text" name="foo" value="bang" />\n<input type="text" name="foo" value="bang" />\n<input type="text" n... |
def main():
global_clock_sources = ClockSources()
cmt_clock_sources = ClockSources()
cmt_fast_clock_sources = ClockSources(4)
bufr_clock_sources = ClockSources()
bufio_clock_sources = ClockSources()
site_to_cmt = dict(read_site_to_cmt())
clock_region_limit = dict()
clock_region_serdes_lo... |
def test_strict_bytes_type_checking_turns_on_and_off(w3):
assert w3.strict_bytes_type_checking
assert (not w3.is_encodable('bytes2', b'\x01'))
w3.strict_bytes_type_checking = False
assert (not w3.strict_bytes_type_checking)
assert w3.is_encodable('bytes2', b'\x01')
w3.strict_bytes_type_checking ... |
class OptionPlotoptionsFunnel3dDatalabels(Options):
def align(self):
return self._config_get('right')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag... |
class CheckMeasureDefinitionsTests(TestCase):
def setUpTestData(cls):
create_import_log()
set_up_bq()
upload_presentations()
def test_check_definition(self):
upload_dummy_prescribing(['0703021Q0AAAAAA', '0703021Q0BBAAAA'])
with patched_global_matrixstore_from_data_factory... |
def knapsack_top_down_alt(items, total_weight):
if ((items is None) or (total_weight is None)):
raise TypeError('input_items or total_weight cannot be None')
if ((not items) or (not total_weight)):
return 0
memo = {}
result = _knapsack_top_down_alt(items, total_weight, memo, index=0)
... |
def hsluv_to_luv(hsluv: Vector) -> Vector:
(h, s, l) = hsluv
c = 0.0
if (l > (100 - 1e-07)):
l = 100.0
elif (l < 1e-08):
l = 0.0
else:
_hx_max = max_chroma_for_lh(l, h)
c = ((_hx_max / 100.0) * s)
(a, b) = alg.polar_to_rect(c, h)
return [l, a, b] |
def get_archlinux_aur_helper():
command = None
for helper in ['paru', 'pacaur', 'yay', 'yaourt', 'aura']:
if which(helper):
command = helper
break
if command:
return command
else:
print("Please install one of AUR's helper, such as 'pacaur', 'yay', 'yaourt'... |
def upgrade():
op.add_column('session', sa.Column('submission_date', sa.DateTime(), nullable=True))
op.drop_column('session', 'date_of_submission')
op.add_column('session_version', sa.Column('submission_date', sa.DateTime(), autoincrement=False, nullable=True))
op.drop_column('session_version', 'date_of... |
def test_detect_invalid_initial_magic(tmpdir: Path):
filepath = (tmpdir / 'invalid_magic.mcap')
with open(filepath, 'w') as f:
f.write('some bytes longer than the initial magic bytes')
with open(filepath, 'rb') as f:
with pytest.raises(InvalidMagic):
SeekingReader(f)
with ope... |
def get_next_page(html, url):
if is_project(url):
page = int(parse_qs(urlparse(url).query)['page'][0])
total_page = math.ceil((json.loads(html)['total_count'] / EP_PER_PAGE))
return (update_qs(url, {'page': (page + 1)}) if (page < total_page) else None)
if is_user_home(url):
user... |
class Solution():
def search(self, nums: List[int], target: int) -> bool:
(l, r) = (0, (len(nums) - 1))
while (l <= r):
mid = (l + ((r - l) // 2))
if (nums[mid] == target):
return True
while ((l < mid) and (nums[l] == nums[mid])):
l... |
def generate_fixture_tests(metafunc: Any, base_fixture_path: str, filter_fn: Callable[(..., Any)]=identity, preprocess_fn: Callable[(..., Any)]=identity) -> None:
if ('fixture_data' in metafunc.fixturenames):
all_fixtures = find_fixtures(base_fixture_path)
if (not all_fixtures):
raise As... |
def upgrade():
op.create_table('settings', sa.Column('id', sa.Integer(), nullable=False), sa.Column('aws_key', sa.String(), nullable=True), sa.Column('aws_secret', sa.String(), nullable=True), sa.Column('aws_bucket_name', sa.String(), nullable=True), sa.Column('google_client_id', sa.String(), nullable=True), sa.Col... |
.django_db
def test_signals__encoding_failed(monkeypatch, mocker, local_video: models.Video) -> None:
encoding_format = tasks.settings.VIDEO_ENCODING_FORMATS['FFmpeg'][0]
monkeypatch.setattr(tasks.settings, 'VIDEO_ENCODING_FORMATS', {'FFmpeg': [encoding_format]})
mocker.patch.object(tasks, '_encode', side_e... |
.feature('unit')
.story('payload_builder')
class TestPayloadBuilderCreate():
def test_insert_payload(self):
res = PayloadBuilder().INSERT(key='x').payload()
assert (_payload('data/payload_insert1.json') == json.loads(res))
def test_insert_into_payload(self):
res = PayloadBuilder().INSERT... |
def extractItsladygreyWordpressCom(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_typ... |
('/mod_board/<board:board>/log')
('/mod_board/<board:board>/log/<int(max=14):page>')
def mod_board_log(board: BoardModel, page=0):
per_page = 100
pages = 15
moderator = request_moderator()
logs = moderator_service.user_get_logs(moderator, board, page, per_page)
def get_log_type(typeid):
try:... |
def upgrade():
op.add_column('video_stream_moderators', sa.Column('email', sa.String(), nullable=False))
op.create_unique_constraint('uq_user_email_video_stream_moderator', 'video_stream_moderators', ['email', 'video_stream_id'])
op.drop_constraint('user_video_stream_id', 'video_stream_moderators', type_='u... |
def main():
parser = argparse.ArgumentParser(description='Convert FPGA configuration description ("FPGA assembly") into binary frame equivalent')
util.db_root_arg(parser)
util.part_arg(parser)
parser.add_argument('--sparse', action='store_true', help="Don't zero fill all frames")
parser.add_argument... |
class Highlights(MixHtmlState.HtmlStates, Html.Html):
name = 'Highlights'
tag = 'div'
requirements = ('bootstrap',)
_option_cls = OptText.OptionsHighlights
def __init__(self, page: primitives.PageModel, text, title, icon, type, color, width, height, html_code, helper, options, profile):
supe... |
class Immutable():
__slots__: tuple[(Any, ...)] = ()
def __init__(self, **kwargs: Any) -> None:
for (k, v) in kwargs.items():
super(Immutable, self).__setattr__(k, v)
def __setattr__(self, name: str, value: Any) -> None:
raise AttributeError('Class is immutable!') |
def moyle_processor(df) -> list:
datapoints = []
for (index, row) in df.iterrows():
snapshot = {}
snapshot['datetime'] = add_default_tz(parser.parse(row['TimeStamp'], dayfirst=True))
snapshot['netFlow'] = row['Total_Moyle_Load_MW']
snapshot['source'] = 'soni.ltd.uk'
snaps... |
def main():
global_config = config['Global']
post_process_class = build_post_process(config['PostProcess'], global_config)
model = build_model(config['Architecture'])
load_model(config, model)
transforms = []
for op in config['Eval']['dataset']['transforms']:
op_name = list(op)[0]
... |
def test_offset_limit(response_with_body):
config = OffsetPaginationConfiguration(incremental_param='page', increment_by=1, limit=10)
request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/conversations', query_params={'page': 10})
paginator = OffsetPaginationStrategy(config)
... |
class TestMerging(object):
def commit_to_branches(self, to_branches, opts, version):
(srpm_path, package_desc) = get_srpm(version)
name = package_desc['package_name']
import_result = import_package(opts, 'bob/blah', to_branches, srpm_path, name)
return import_result['branch_commits']... |
def test():
print('Basic tests\n')
for alpha in (0.4, 0.38, 0.36, 0.34, 0.32, 0.3, 0.28):
race_results = [race(alpha, (1 - alpha), 1000) for j in range(100)]
probs = []
for i in range(1, 9):
probs.append((len([x for x in race_results if (x >= i)]) / 100))
print(('Prob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.