code stringlengths 281 23.7M |
|---|
def test_incomplete_graph(mocker: Any) -> None:
logger_module = (__name__.rsplit('.', 2)[0] + '.graph.logger')
mock_logger = mocker.patch(logger_module)
class MyMessage(Message):
int_field: int
class MyNode(Node):
A = Topic(MyMessage)
B = Topic(MyMessage)
(A)
(B)
... |
class ModelsFactory():
def __init__(self):
pass
def get_by_name(model_name, *args, **kwargs):
model = None
if (model_name == 'LVD_voxels_SMPL'):
from .LVD_voxels_SMPL import Model
model = Model(*args, **kwargs)
elif (model_name == 'IPNet_voxels_SMPL'):
... |
def upgrade():
try:
op.add_column('EntityTypes', sa.Column('accepts_references', sa.Boolean))
except (sa.exc.OperationalError, sa.exc.ProgrammingError):
pass
try:
op.add_column('Links', sa.Column('original_filename', sa.String(256)))
except (sa.exc.OperationalError, sa.exc.Progra... |
def test_hicConvertFormat_h5_to_ginteractions():
outfile = NamedTemporaryFile(suffix='.ginteractions', delete=False)
outfile.close()
args = '--matrices {} --outFileName {} --inputFormat h5 --outputFormat ginteractions '.format(original_matrix_h5, outfile.name).split()
compute(hicConvertFormat.main, args... |
class MrtPeer(stringify.StringifyMixin):
_HEADER_FMT = '!B4s'
HEADER_SIZE = struct.calcsize(_HEADER_FMT)
IP_ADDR_FAMILY_BIT = (1 << 0)
AS_NUMBER_SIZE_BIT = (1 << 1)
_TYPE = {'ascii': ['bgp_id', 'ip_addr']}
def __init__(self, bgp_id, ip_addr, as_num, type_=0):
self.type = type_
se... |
class BaseDiagnostics():
def __init__(self, samples: MonteCarloSamples):
self.samples = samples
self.statistics_dict = {}
self.plots_dict = {}
def _prepare_query_list(self, query_list: Optional[List[RVIdentifier]]=None) -> List[RVIdentifier]:
if (query_list is None):
... |
def run_file(file_path):
demo_name = os.path.basename(file_path)
screenshot_name = (demo_name.split('.')[0] + '.png')
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
globals = {'__name__': '__main__', '__file__': file_path}
with replace_configure_traits(screenshot_name),... |
class PocketTestCase(unittest.TestCase):
def test_main_initial(self):
pocket.WF._version.major = 'x'
CachedData['__workflow_update_status'] = {'available': True}
CachedData['pocket_tags'] = ['tag1']
sys.argv = ['pocket.py', '']
def send_feedback():
pass
po... |
def generate_feature(b, bin_dir, debug_dir, bap_dir):
try:
config = Config()
config.BINARY_NAME = b
config.BINARY_PATH = os.path.join(bin_dir, b)
config.DEBUG_INFO_PATH = os.path.join(debug_dir, b)
if (bap_dir != ''):
config.BAP_FILE_PATH = os.path.join(bap_dir, b... |
(HelpEntry)
class HelpEntryAdmin(admin.ModelAdmin):
inlines = [HelpTagInline]
list_display = ('id', 'db_key', 'db_help_category', 'db_lock_storage', 'db_date_created')
list_display_links = ('id', 'db_key')
search_fields = ['^db_key', 'db_entrytext']
ordering = ['db_help_category', 'db_key']
list... |
def fast_urandom16(urandom=[], locker=threading.RLock()):
try:
return urandom.pop()
except IndexError:
try:
locker.acquire()
ur = os.urandom((16 * 1024))
urandom += [ur[i:(i + 16)] for i in range(16, (1024 * 16), 16)]
return ur[0:16]
finall... |
def getHumans():
global humans
answer = DEFAULT
while (answer not in TYPES):
print("a: 'X' human, 'O' computer")
print("b: 'O' computer, 'X' human")
print("c: 'X' human, 'O' human")
print("d: 'X' computer, 'O' computer")
answer = input("Please choose ('X' begins): ").... |
def make_arg_parser():
parser = argparse.ArgumentParser(usage='python -m docxtpl [-h] [-o] [-q] {} {} {}'.format(TEMPLATE_ARG, JSON_ARG, OUTPUT_ARG), description='Make docx file from existing template docx and json data.')
parser.add_argument(TEMPLATE_ARG, type=str, help='The path to the template docx file.')
... |
def test_returning_a_pathlib_path(local_dummy_directory):
def t1() -> FlyteDirectory:
return pathlib.Path(local_dummy_directory)
def wf1() -> FlyteDirectory:
return t1()
wf_out = wf1()
assert isinstance(wf_out, FlyteDirectory)
os.listdir(wf_out)
assert wf_out._downloaded
with... |
class SectorItem(scrapy.Item):
id = scrapy.Field()
start_date = scrapy.Field()
name = scrapy.Field()
link = scrapy.Field()
type = scrapy.Field()
producer = scrapy.Field()
news_title = scrapy.Field()
news_link = scrapy.Field()
count = scrapy.Field()
leadings = scrapy.Field() |
def test_transaction_span_stack_trace_min_duration_overrides_old_config(elasticapm_client):
elasticapm_client.config.update(version='1', span_stack_trace_min_duration=20, span_frames_min_duration=1)
elasticapm_client.begin_transaction('test_type')
with elasticapm.capture_span('noframes', duration=0.01):
... |
class OptionSeriesVariablepieDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
class PrometheusPodsMetrics(PrometheusAPI):
def __init__(self):
super().__init__()
def podExists(self, pod, namespace='default'):
output = {'success': False, 'fail_reason': '', 'result': False}
try:
query = f'sum(container_last_seen{{image!="", container!="", container!="POD"... |
def test_add_variable():
import flxtest.foo
import flxtest.bar
store = {}
m = JSModule('flxtest.foo', store)
assert (not m.variables)
m.add_variable('Foo')
assert ('Foo' in m.variables)
assert (not store['flxtest.lib1'].deps)
with capture_log('info') as log:
store['flxtest.li... |
class TestPrepareRerunAccessGraphEvent():
def test_rerun_access_graph_event_no_previous_graph(self, privacy_request, env_a_b_c, resources):
end_nodes = [c_traversal_node().address]
analytics_event = prepare_rerun_graph_analytics_event(privacy_request, env_a_b_c, end_nodes, resources, ActionType.acce... |
def extractPhoebetranslationBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("dragon's raja", "dragon's raja", 'translated'), ('Thriller Paradise', 'Thriller Paradise... |
def test_task_failure(flask_celery):
apm_client = flask_celery.flask_apm_client.client
_celery.task()
def failing_task():
raise ValueError('foo')
t = failing_task.delay()
assert (t.status == 'FAILURE')
assert (len(apm_client.events[ERROR]) == 1)
error = apm_client.events[ERROR][0]
... |
class MyApp(App):
BINDINGS = [('t', 'change_theme()', 'Muda o tema!'), ('s', 'exit()', 'Sai da aplicacao!')]
def action_change_theme(self):
self.dark = (not self.dark)
def action_exit(self):
self.exit()
def compose(self):
self.label = Label('[b]Sera que clicou?[/]')
(yiel... |
class TestOFPQueuePropNone(unittest.TestCase):
property = {'buf': b'\x00\x00', 'val': ofproto.OFPQT_NONE}
len = {'buf': b'\x00\x08', 'val': ofproto.OFP_QUEUE_PROP_HEADER_SIZE}
zfill = (b'\x00' * 4)
c = OFPQueuePropNone()
def setUp(self):
pass
def tearDown(self):
pass
def test... |
def main(args=None):
import argparse
from pathlib import Path
from fontTools import configLogger
parser = argparse.ArgumentParser('fonttools voltLib.voltToFea', description=main.__doc__)
parser.add_argument('input', metavar='INPUT', type=Path, help='input font/VTP file to process')
parser.add_ar... |
def test_task_set_secrets(task_definition):
task_definition.set_secrets(((u'webserver', u'foo', u'baz'), (u'webserver', u'some-name', u'some-value')))
assert ({'name': 'dolor', 'valueFrom': 'sit'} in task_definition.containers[0]['secrets'])
assert ({'name': 'foo', 'valueFrom': 'baz'} in task_definition.con... |
class OptionChartJsSankeyParsing(Options):
def from_(self):
return self._config_get()
_.setter
def from_(self, val: str):
self._config(val, name='from')
def to(self):
return self._config_get()
def to(self, val: str):
self._config(val)
def flow(self):
retur... |
def ensure_bam_sorted(bam_fname, by_name=False, span=50, fasta=None):
if by_name:
def out_of_order(read, prev):
return (not ((prev is None) or (prev.qname <= read.qname)))
else:
def out_of_order(read, prev):
return (not ((prev is None) or (read.tid != prev.tid) or (prev.p... |
class OptionPlotoptionsTimelineLabel(Options):
def boxesToAvoid(self):
return self._config_get(None)
def boxesToAvoid(self, value: Any):
self._config(value, js_type=False)
def connectorAllowed(self):
return self._config_get(False)
def connectorAllowed(self, flag: bool):
s... |
def run_bot() -> None:
application = ApplicationBuilder().token(config.telegram_token).concurrent_updates(True).rate_limiter(AIORateLimiter(max_retries=5)).
user_filter = filters.ALL
if (len(config.allowed_telegram_usernames) > 0):
usernames = [x for x in config.allowed_telegram_usernames if isinsta... |
class GETTGT():
def __init__(self, target, password, domain, options):
self.__password = password
self.__user = target
self.__domain = domain
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = options.aesKey
self.__options = options
self.__kdcHost =... |
.parametrize('settype', ['PARAMETER', 'COMPUTATION'])
def test_values_multidim_values(tmpdir, merge_files_oneLR, settype):
path = os.path.join(str(tmpdir), 'values-multidim-values.dlis')
content = [*assemble_set(settype), 'data/chap4-7/eflr/ndattrs/objattr/1-2-3-4-5-6-7-8-9-10-11-12.dlis.part', 'data/chap4-7/ef... |
class HardTimeout(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running Hard_Timeout test ')
of_ports = config['port_map'].keys()
of_ports.sort()
self.assertTrue((len(of_ports) > 1), 'Not enough ports for test')
delete_all_flows(self.controller)
loggin... |
class TestBurnKeyCommands(EfuseTestCase):
.skipif((arg_chip != 'esp32'), reason='ESP32-only')
def test_burn_key_3_key_blocks(self):
self.espefuse_py('burn_key -h')
self.espefuse_py(f'burn_key BLOCK1 {IMAGES_DIR}/192bit', check_msg='A fatal error occurred: Incorrect key file size 24. Key file mus... |
class TestsAchromatic(util.ColorAsserts, unittest.TestCase):
def test_achromatic(self):
self.assertEqual(Color('hsl', [270, 0.5, 0]).is_achromatic(), True)
self.assertEqual(Color('hsl', [270, 0.5, 1]).is_achromatic(), True)
self.assertEqual(Color('hsl', [270, 0, 0.5]).is_achromatic(), True)
... |
def test_pca_bigwig_lieberman_histoneMark_track():
pca1 = NamedTemporaryFile(suffix='.bw', delete=False)
pca2 = NamedTemporaryFile(suffix='.bw', delete=False)
pca1.close()
pca2.close()
matrix = (ROOT + 'small_test_matrix.h5')
extra_track = (ROOT + 'bigwig_chrx_2e6_5e6.bw')
chromosomes = 'chr... |
def test_slice():
s = search.Search()
assert ({'from': 3, 'size': 7} == s[3:10].to_dict())
assert ({'from': 0, 'size': 5} == s[:5].to_dict())
assert ({'from': 3, 'size': 10} == s[3:].to_dict())
assert ({'from': 0, 'size': 0} == s[0:0].to_dict())
assert ({'from': 20, 'size': 0} == s[20:0].to_dict... |
.parametrize('abi,arguments,data,expected', (pytest.param(ABI_B, [0], None, '0xf0fdf', id='ABI_B, valid int args, no data'), pytest.param(ABI_B, [1], None, '0xf0fdf', id='ABI_B, valid int args, no data'), pytest.param(ABI_C, [1], None, '0xf0fdf', id='ABI_B, valid int args, no data'), pytest.param(ABI_C, [(b'a' + (b'\x0... |
class MemberList(MethodView):
form = UserSearchForm
def get(self):
page = request.args.get('page', 1, type=int)
sort_by = request.args.get('sort_by', 'reg_date')
order_by = request.args.get('order_by', 'asc')
if (order_by == 'asc'):
order_func = asc
else:
... |
.usefixtures('database_interfaces')
class TestRestFirmware(RestTestBase):
def test_rest_firmware_existing(self, backend_db):
test_firmware = create_test_firmware(device_class='test class', device_name='test device', vendor='test vendor')
backend_db.add_object(test_firmware)
response = self.t... |
def solve_tsp_simulated_annealing(distance_matrix: np.ndarray, x0: Optional[List[int]]=None, perturbation_scheme: str='two_opt', alpha: float=0.9, max_processing_time: Optional[float]=None, log_file: Optional[str]=None, verbose: bool=False) -> Tuple[(List, float)]:
(x, fx) = setup_initial_solution(distance_matrix, ... |
('ner.openai.fetch', input_path=('Path to jsonl data to annotate', 'positional', None, Path), output_path=('Path to save the output', 'positional', None, Path), labels=('Labels (comma delimited)', 'positional', None, (lambda s: s.split(','))), lang=('Language to use for tokenizer.', 'option', 'l', str), model=('GPT-3 m... |
def verify_file(filename, sample, formula):
try:
with open(filename, 'r') as f:
data = f.read()
except Exception as exc:
print_logs('Unable to open {0}: {1}'.format(filename, exc))
return False
basename = os.path.basename(filename)
ext = get_extension(filename)
de... |
def list_gtk_themes():
builtin_themes = [theme[:(- 1)] for theme in Gio.resources_enumerate_children('/org/gtk/libgtk/theme', Gio.ResourceFlags.NONE)]
theme_search_dirs = [(Path(data_dir) / 'themes') for data_dir in GLib.get_system_data_dirs()]
theme_search_dirs.append((Path(GLib.get_user_data_dir()) / 'the... |
def process_file(input_filename, output_filename, variables, die_on_missing_variable, remove_template):
if ((not input_filename) and (not remove_template)):
raise Fatal('--keep-template only makes sense if you specify an input file')
if die_on_missing_variable:
undefined = jinja2.StrictUndefined... |
class OptionSeriesPackedbubbleSonificationDefaultinstrumentoptionsMappingNoteduration(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... |
class BlueprintShortTest(TestCase):
def test_blueprint(self):
movie_night = pizza_short.m(quantity=10)()
self.assertEqual(len(movie_night), 10)
self.assertEqual(movie_night[0].chef.first_name, 'Chef 0')
self.assertEqual(movie_night[1].chef.first_name, 'Chef 1')
def test_blueprint... |
_op([BlockCursorA, CustomWindowExprA('block_cursor'), NameA, BoolA])
def stage_mem(proc, block_cursor, win_expr, new_buf_name, accum=False):
(buf_name, w_exprs) = win_expr
(ir, fwd) = scheduling.DoStageMem(block_cursor._impl, buf_name, w_exprs, new_buf_name, use_accum_zero=accum)
return Procedure(ir, _prove... |
def plotHistogram(figure, plot_context: 'PlotContext', case_to_data_map, _observation_data):
config = plot_context.plotConfig()
case_list = plot_context.cases()
if (not case_list):
dummy_case_name = 'default'
case_list = [dummy_case_name]
case_to_data_map = {dummy_case_name: pd.DataF... |
def by_time(t: float, after: bool=True) -> FilterFunc:
def func(events: List[Event]) -> List[Event]:
if (not (events == sorted(events, key=(lambda event: event.time)))):
raise ValueError('Event lists must be chronological')
new: List[Event] = []
for event in events:
i... |
def extractNekosandnekosBlogspotCom(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 strip_additional_properties(version: Version, api_contents: dict) -> dict:
stripped = {}
target_schema = get_schema_file(version, api_contents['type'])
for (field, field_schema) in target_schema['properties'].items():
if (field in api_contents):
stripped[field] = api_contents[field]
... |
def has_permissions(token_data: Dict[(str, Any)], client: ClientDetail, endpoint_scopes: SecurityScopes) -> bool:
has_direct_scope: bool = _has_direct_scopes(token_data=token_data, client=client, endpoint_scopes=endpoint_scopes)
has_role: bool = _has_scope_via_role(token_data=token_data, client=client, endpoint... |
class TotalNetSensor(BaseSensor):
name = 'totalnet'
desc = _('Total Network activity.')
def get_value(self, sensor_data):
return self._fetch_net()
def _fetch_net(self):
current = [0, 0]
for (_, iostat) in list(ps.net_io_counters(pernic=True).items()):
current[0] += io... |
.skip(reason='Table logging is now disabled')
.django_db()
def test_drf_tracking_logging(client):
endpoint_ping = client.get('/api/v1/awards/?page=1&limit=10')
assert (endpoint_ping.status_code == status.HTTP_200_OK)
assert (APIRequestLog.objects.count() == 1)
assert (APIRequestLog.objects.first().path ... |
class RDepPriority(Digraph.Node):
depends_on = ['RDepDependsOn', 'RDepNoDirectedCircles', 'RDepOneComponent', 'RDepSolvedBy', 'RDepMasterNodes']
def __init__(self, config):
Digraph.Node.__init__(self, 'RDepPriority')
self.config = config
def get_type_set():
return set([InputModuleTyp... |
_renderer(wrap_type=ScoreDistribution)
class ScoreDistributionRenderer(MetricRenderer):
def render_html(self, obj: ScoreDistribution) -> List[BaseWidgetInfo]:
metric_result = obj.get_result()
distr_fig = plot_4_distr(curr_1=HistogramData.from_distribution(metric_result.current_top_k_distr), curr_2=H... |
class SignalMethodTask(ITask):
task_id: str = None
workflow_instance: object = None
signal_name: str = None
signal_input: List = None
exception_thrown: BaseException = None
ret_value: object = None
def start(self):
logger.debug(f'[signal-task-{self.task_id}-{self.signal_name}] Create... |
class OptionPlotoptionsSeriesSonificationContexttracksMappingPlaydelay(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 Tuples():
def __init__(self, t1: Tuple[(float, float)], t2=(1, 2, 3), t3: Tuple[(float, ...)]=(0.1, 0.2, 0.3)):
self.t1 = t1
self.t2 = t2
self.t3 = t3
def __eq__(self, other):
return (isinstance(other, type(self)) and (self.t1 == other.t1) and (self.t2 == other.t2) and (sel... |
class FiniteElement(object):
def __init__(self, cell, degree, nodes, entity_nodes=None):
self.cell = cell
self.degree = degree
self.nodes = nodes
self.entity_nodes = entity_nodes
if entity_nodes:
self.nodes_per_entity = np.array([len(entity_nodes[d][0]) for d in r... |
def fetch_production_capacity(zone_key: ZoneKey, target_datetime: datetime, session: Session) -> (dict[(str, Any)] | None):
geo_limit = ZONE_KEY_TO_GEO_LIMIT[zone_key]
geo_ids = GEO_LIMIT_TO_GEO_IDS[geo_limit]
url = '
params = {'start_date': target_datetime.strftime('%Y-01-01T00:00'), 'end_date': target... |
_tag
def show_article_icon(article, state):
correspond = {'digg': ['digg_count', 'fa-thumbs-up'], 'look': ['look_count', 'fa-eye'], 'collects': ['collects_count', 'fa-star'], 'comment': ['comment_count', 'fa-comment']}
key = 'look'
if state:
word = re.search('[-](.*?)_.*?', state)
key = word... |
def split_on_groups(all_args):
groups = []
cmd = []
used_cmds = []
for item in all_args:
if (item in SUPPORTED_COMMANDS):
used_cmds.append(item)
if (cmd != []):
groups.append(cmd)
cmd = []
cmd.append(item)
if cmd:
groups.app... |
def _matrix_repr(M):
item = M[(0, 0)]
if (type(item) is flint.fmpz):
return f'fmpz_mat({M.nrows()}, {M.ncols()}, {M.entries()!r})'
elif (type(item) is flint.fmpq):
return f'fmpq_mat({M.nrows()}, {M.ncols()}, {M.entries()!r})'
elif (type(item) is flint.nmod):
return f'nmod_mat({M.... |
def test_convert_indirect_edge_to_unconditional(parser):
jmp_instr = MockFixedJump(42)
function = MockFunction([(block := MockBlock(0, [MockEdge(0, 42, BranchType.IndirectBranch)], instructions=[jmp_instr])), MockBlock(42, [])])
assert parser._can_convert_single_outedge_to_unconditional(block)
cfg = par... |
class NoHealthCheckTest(AmbassadorTest):
def init(self):
self.target = HealthCheckServer()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nname: {self.target.path.k8s}-health\n... |
.django_db
def test_tas_unparsable_too_short(client, monkeypatch, elasticsearch_award_index, subaward_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas_subaward(client, {'require': [['011', '011-0990', '3-4-2']]})
assert (resp.status_code == status.HTTP_422_UNPROCESSAB... |
class OptionSeriesTilemapStatesHover(Options):
def animation(self) -> 'OptionSeriesTilemapStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesTilemapStatesHoverAnimation)
def brightness(self):
return self._config_get(0.2)
def brightness(self, num: float):
sel... |
def extractBabelfishoutofwaterWordpressCom(item):
badtags = ['goodreads', 'readathon', 'Writing', 'Blog']
if any([(tmp in item['tags']) for tmp in badtags]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['titl... |
_member_required
def set_document_thumbnail(request, uuid, metadata_uuid=None):
uuid = UUID(uuid)
if metadata_uuid:
metadata_uuid = UUID(metadata_uuid)
try:
doc = Document.objects.all().get(uuid=uuid)
except Document.DoesNotExist:
raise Http404('Document with this uuid does not e... |
class ValveTestMultipleOrderedTunnel(ValveTestBases.ValveTestTunnel):
TUNNEL_ID = 2
CONFIG = "\nacls:\n tunnel_acl:\n - rule:\n dl_type: 0x0800\n ip_proto: 1\n actions:\n output:\n - tunnel: {dp: s2, port: 1}\nvlans:\n vlan100:\n ... |
class Const(Field):
errors = {'only_null': 'Must be null.', 'const': "Must be the value '{const}'."}
def __init__(self, const: typing.Any, **kwargs: typing.Any):
assert ('allow_null' not in kwargs)
super().__init__(**kwargs)
self.const = const
def validate(self, value: typing.Any) ->... |
def update_address_links(address, method):
if ('Healthcare' not in frappe.get_active_domains()):
return
patient_links = list(filter((lambda link: (link.get('link_doctype') == 'Patient')), address.links))
for link in patient_links:
customer = frappe.db.get_value('Patient', link.get('link_name... |
class Migration(migrations.Migration):
dependencies = [('extra_settings', '0001_initial')]
operations = [migrations.AddField(model_name='setting', name='value_duration', field=models.DurationField(blank=True, null=True, verbose_name='Value')), migrations.AlterField(model_name='setting', name='value_type', field... |
class OptionSeriesPyramidDataDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
def add_background(youtube_uri, filename, citation, position):
regex = re.compile('(?:\\/|%3D|v=|vi=)([0-9A-z\\-_]{11})(?:[%#?&]|$)').search(youtube_uri)
if (not regex):
flash('YouTube URI is invalid!', 'error')
return
youtube_uri = f'
if ((position == '') or (position == 'center')):
... |
('/emailable-report/export', strict_slashes=False)
('/allure-docker-service/emailable-report/export', strict_slashes=False)
_required
def emailable_report_export_endpoint():
try:
project_id = resolve_project(request.args.get('project_id'))
if (is_existent_project(project_id) is False):
b... |
class CmdTelescope(Cmd):
keywords = ['telescope', 'tel']
description = 'Display a specified region in the memory and follow pointers to valid addresses.'
parser = argparse.ArgumentParser(prog=keywords[0], description=description, epilog=('Aliases: ' + ', '.join(keywords)))
parser.add_argument('--length'... |
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lojadelivros.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environmen... |
def test_that_segment_defaults_are_applied(tmpdir):
with tmpdir.as_cwd():
with open('config.ert', 'w', encoding='utf-8') as fh:
fh.writelines(dedent('\n NUM_REALIZATIONS 2\n\n ECLBASE ECLIPSE_CASE\n REFCASE ECLIPSE_CASE\n ... |
def extractTwomorefreethoughtsCom(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 extractGracegracy118BlogspotCom(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... |
class OptionSeriesHeatmapSonificationTracksMappingRate(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 HttpDialogues(BaseHttpDialogues):
def __init__(self, self_address: Address, **kwargs: Any) -> None:
def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role:
return HttpDialogue.Role.CLIENT
BaseHttpDialogues.__init__(self, self_address=self_addr... |
class RetryExceptionWrapperInterceptor(grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor):
def __init__(self, max_retries: int=3):
self._max_retries = 3
def _raise_if_exc(request: typing.Any, e: Union[(grpc.Call, grpc.Future)]):
if isinstance(e, grpc.RpcError):
if (... |
def update_tile_conn(tileconn, key_history, wirename1, wire1, wirename2, wire2, tiles):
tile1 = tiles[wire1['tile']]
tile2 = tiles[wire2['tile']]
if ((wire1['type'], wire1['shortname'], tile1['grid_x'], tile1['grid_y']) > (wire2['type'], wire2['shortname'], tile2['grid_x'], tile2['grid_y'])):
(wire1... |
def mark_as_notified_on_before(sha256, notification_date):
if (not is_notified_on_before(sha256)):
try:
database_connection.execute('INSERT INTO seen_sha256_hashes (sha256, notification_date) values (?, ?)', [str(sha256), int(notification_date)])
except Exception as e:
print(... |
def migrate(config_file, current_version, target_version, out=print, i=input):
logger = logging.getLogger(__name__)
if (current_version == target_version):
logger.info('Config file is already at version [%s]. Skipping migration.', target_version)
return
if (current_version < Config.EARLIEST_... |
class DNSClientProtocolTCP(DNSClientProtocol):
def __init__(self, dnsq, fut, clientip, logger=None):
super().__init__(dnsq, fut, clientip, logger=logger)
self.buffer = bytes()
def connection_made(self, transport):
self.send_helper(transport)
msg = self.dnsq.to_wire()
tcpm... |
def update_marks_from_args(nodes, marks, tree, args):
if args.mark:
if (args.mark_leaves or args.mark_internals):
exit('ERROR: incompatible marking options')
for group in args.mark:
marks.append([])
nodes.append([])
group = group.replace(',,,', ';;;')
... |
def make_othervar_node(name, blk):
binary = blk.binary
if (name in binary.othervar_nodes):
othervar_node = binary.othervar_nodes[name]
else:
othervar_node = OtherVarNode(binary=binary, name=name)
binary.othervar_nodes[name] = othervar_node
return othervar_node |
class OpenAIEmbeddingGenerator(object):
def __init__(self, env_file_path: str):
load_dotenv(dotenv_path=env_file_path)
self.OPENAI_API_KEY = os.getenv('OPENAI_API_KEY', '')
if (not self.OPENAI_API_KEY):
raise MissingEnvironmentVariableError('OPENAI_API_KEY')
self.OPENAI_G... |
class fileParser():
def __init__(self, topFile, coorFile=''):
coorPostfix = os.path.splitext(coorFile)[(- 1)]
if ((coorPostfix == '.rst7') or (coorPostfix == '.rst') or (coorPostfix == '.inpcrd')):
coorType = 'inpcrd'
if (coorFile == ''):
self.uObject = MDAnalysis.Uni... |
def test_decimal_precision_is_greater_than_scale():
'
schema = {'type': 'record', 'name': 'test_scale_is_an_int', 'fields': [{'name': 'field', 'type': {'logicalType': 'decimal', 'precision': 5, 'scale': 10, 'type': 'bytes'}}]}
with pytest.raises(SchemaParseException, match='decimal scale must be less than o... |
class Station(object):
__slots__ = ('ID', 'system', 'dbname', 'lsFromStar', 'market', 'blackMarket', 'shipyard', 'maxPadSize', 'outfitting', 'rearm', 'refuel', 'repair', 'planetary', 'fleet', 'odyssey', 'itemCount', 'dataAge')
def __init__(self, ID, system, dbname, lsFromStar, market, blackMarket, shipyard, max... |
.WebInterfaceUnitTestConfig(intercom_mock_class=IntercomMock, database_mock_class=DbMock)
class TestAppShowAnalysis():
def test_app_show_analysis_get_valid_fw(self, test_client):
result = test_client.get(f'/analysis/{TEST_FW.uid}').data
assert ((b'<strong>UID:</strong> ' + make_bytes(TEST_FW.uid)) i... |
.sphinx(buildername='html', srcdir=os.path.join(SOURCE_DIR, 'include_from_rst'), freshenv=True)
def test_include_from_rst(app, status, warning, get_sphinx_app_doctree):
app.build()
assert ('build succeeded' in status.getvalue())
warnings = warning.getvalue().strip()
assert (warnings == '')
get_sphin... |
def test_generate_gpu_scene_with_references_before_generating_gpu_of_references_first(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
gen = RepresentationGenerator(version=data['building1_yapi_look_dev_main_v001'])
with pytest.raises(RuntimeError) as cm:
... |
class KeyBindingEditor(Editor):
has_focus = Bool(False)
key = Event()
clear = Event()
def init(self, parent):
self.control = KeyBindingCtrl(self, parent, size=wx.Size(160, 19))
def update_editor(self):
self.control.Refresh()
def _key_changed(self, event):
binding = self.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.