code stringlengths 281 23.7M |
|---|
def test_override_providers_context_manager():
p1 = providers.Provider()
p2 = providers.Provider()
container = Container()
with container.override_providers(p11=p1, p12=p2) as context_container:
assert (container is context_container)
assert (container.p11.last_overriding is p1)
... |
def create_all_search_playlist(groups, exaile):
tagname = get_tagname()
name = ('%s: %s' % (tagname.title(), ' and '.join(groups)))
search_string = ' '.join([('%s~"\\b%s\\b"' % (tagname, re.escape(group.replace(' ', '_')))) for group in groups])
_create_search_playlist(name, search_string, exaile) |
def test_create_key(db: Session):
with pytest.raises(KeyValidationError) as exc:
StorageConfig.create(db, data={'type': StorageType.s3.value, 'details': {'bucket': 'some-bucket'}})
assert (str(exc.value) == 'StorageConfig requires a name.')
sc = StorageConfig.create(db, data={'name': 'test dest', 't... |
class CircleCI(IntervalModule):
settings = ('format', ('circleci_token', 'circleci access token'), ('repo_slug', 'repository identifier eg. "enkore/i3pystatus"'), ('time_format', 'passed directly to .strftime() for `last_build_started`'), ('repo_status_map', 'map representing how to display status'), ('duration_for... |
def _get_pred_labels_from_prob(dataframe: pd.DataFrame, prediction_column: list) -> List[str]:
array_prediction = dataframe[prediction_column].to_numpy()
prediction_ids = np.argmax(array_prediction, axis=(- 1))
prediction_labels = [prediction_column[x] for x in prediction_ids]
return prediction_labels |
def resistor_label(colors):
if (len(colors) == 1):
return f'0 ohms'
elif (len(colors) == 4):
value = ((10 * COLORS.index(colors[0])) + COLORS.index(colors[1]))
value *= (10 ** COLORS.index(colors[2]))
(value, unit) = color_code(value)
value = (int(value) if value.is_integ... |
def test_check_typed_prims_invalid_bend():
geom_kwargs = {'coord_type': 'redund'}
h2o_zmat = 'O\n H 1 0.96\n H 1 0.96 2 104.5\n '
geom = geom_from_zmat_str(h2o_zmat, **geom_kwargs)
typed_prims = geom.internal.typed_prims
bend = typed_prims[2]
assert (bend[0] == PrimTypes.BEND)
h2o_l... |
class OptionPlotoptionsFunnel3dSonificationContexttracksMappingPan(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 list_router_factory(fides_model: FidesModelType, model_type: str) -> APIRouter:
router = APIRouter(prefix=f'{API_PREFIX}/{model_type}', tags=[fides_model.__name__])
(path='/', dependencies=[Security(verify_oauth_client_prod, scopes=[f'{CLI_SCOPE_PREFIX_MAPPING[model_type]}:{READ}'])], response_model=List[fi... |
class AirflowPipelineProcessorResponse(RuntimePipelineProcessorResponse):
_type = RuntimeProcessorType.APACHE_AIRFLOW
_name = 'airflow'
def __init__(self, git_url, run_url, object_storage_url, object_storage_path):
super().__init__(run_url, object_storage_url, object_storage_path)
self.git_u... |
def extractNorthstarnovelsCom(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_raises_if_username_in_blacklist():
requirements = UsernameRequirements(min=1, max=100, blacklist=set(['no']))
validator = UsernameValidator(requirements)
registration = UserRegistrationInfo(username='no', password='no', email='', group=4, language='no')
with pytest.raises(ValidationError) as ex... |
def zeroshot_cfg_string():
return '\n [nlp]\n lang = "en"\n pipeline = ["llm"]\n batch_size = 128\n\n [components]\n\n [components.llm]\n factory = "llm"\n\n [components.llm.task]\n _tasks = "spacy.TextCat.v1"\n labels = "Recipe"\n exclusive_classes = true\n\n [components.llm.tas... |
class TestXGMIIPHY(unittest.TestCase):
def test_xgmii_rx(self):
csv_file = ((Path(__file__).parent / 'assets') / 'xgmii_bus_capture.csv')
xgmii_injector = XGMII64bCSVReader(csv_file.resolve(), complete_trailing_transaction=True)
xgmii_collector = XGMIICollector(min_interframegap=5, tolerate_... |
class PDTable():
def __init__(self, chart, aspList=const.MAJOR_ASPECTS):
pd = PrimaryDirections(chart)
self.table = pd.getList(aspList)
def view(self, arcmin, arcmax):
res = []
for direction in self.table:
if (arcmin < direction[0] < arcmax):
res.appen... |
def test_outcome_by_span_exception(elasticapm_client):
elasticapm_client.begin_transaction('test')
try:
with elasticapm.capture_span('fail', 'test_type'):
assert False
except AssertionError:
pass
with elasticapm.capture_span('success', 'test_type'):
pass
elasticap... |
def start_controller(folder: Path, command: str, tasks_per_node: int=1, cuda_devices: str='', timeout_min: float=5.0, signal_delay_s: int=30, stderr_to_stdout: bool=False, setup: tp.Sequence[str]=()) -> "subprocess.Popen['bytes']":
env = dict(os.environ)
env.update(SUBMITIT_LOCAL_NTASKS=str(tasks_per_node), SUB... |
class PoseUtils():
def __init__(self):
pass
def bullet_pos_to_unity_pos(self, pos: list):
return [(- pos[1]), pos[2], pos[0]]
def unity_pos_to_bullet_pos(self, pos: list):
return [pos[2], (- pos[0]), pos[1]]
def bullet_qua_to_unity_qua(self, qua: list):
return [(- qua[1])... |
def get_right_audio_support_and_sampling_rate(audio_format: str, sampling_rate: int):
if (sampling_rate and ((sampling_rate < 8000) or (sampling_rate > 192000))):
raise ProviderException('Sampling rate must lie in the range of 8 kHz to 192 kHz')
if (not audio_format):
audio_format = 'mp3'
ri... |
class OptionPlotoptionsTimelineSonificationTracksMappingGapbetweennotes(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 TraditionalPokerScoreDetector(ScoreDetector):
def __init__(self, lowest_rank):
self._lowest_rank = lowest_rank
def get_score(self, cards):
cards = Cards(cards, self._lowest_rank)
score_functions = [(TraditionalPokerScore.STRAIGHT_FLUSH, cards.straight_flush), (TraditionalPokerScore... |
class PdnsRecursorCfg(DummyPdnsCfg, models.Model):
pg_notify_payload = 'recursor_cfg_modified'
log_object_name = 'PowerDNS recursor config'
key = models.CharField(_('Key'), primary_key=True, max_length=32, null=False, unique=True, db_index=True, help_text='PowerDNS Recursor configuration parameter keys')
... |
def _validate_end_states(end_states: List[str]) -> Tuple[(bool, str)]:
if (not isinstance(end_states, list)):
return (False, "Invalid type for roles. Expected list. Found '{}'.".format(type(end_states)))
for end_state in end_states:
if (not _is_valid_regex(END_STATE_REGEX_PATTERN, end_state)):
... |
def clear_tutorial(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
save_stats['tutorial_cleared']['Value'] = 1
if (save_stats['story_chapters']['Chapter Progress'][0] == 0):
save_stats['story_chapters']['Chapter Progress'][0] = 1
save_stats['story_chapters']['Times Cleared'][0][0] = 1
print('... |
def setup_to_fail():
with open('/usr/local/bin/dmesg', 'w') as f:
f.writelines({'/bin/dmesg | grep -v "Execute Disable"'})
os.chmod('/usr/local/bin/dmesg', 755)
print(shellexec('echo $PATH'))
print(shellexec('which dmesg'))
(yield None)
os.remove('/usr/local/bin/dmesg') |
class Matrix(GraphCanvas.Canvas):
name = 'Skin Matrix'
_option_cls = OptSkins.OptionsSkin
_js__builder__ = '\n var ctx = htmlObj.getContext("2d"); htmlObj.height = window.innerHeight; htmlObj.width = window.innerWidth;\n var matrix = "#$%^&*()*&^%+-/~{[|`]}";\n matrix = matrix.split(""); var ... |
class DiscountCodeSchemaEvent(DiscountCodeSchemaPublic):
class Meta():
type_ = 'discount-code'
self_view = 'v1.discount_code_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
_schema(pass_original=True)
def validate_quantity(self, data, original_data):
if ... |
class ExecutionTimeout():
def __init__(self, seconds=0, error_message='Execution took longer than the allotted time'):
self.seconds = seconds
self.error_message = error_message
def _timeout_handler(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
... |
class GetFileRequest(DatClass):
file_id: str
drive_id: str = None
url_expire_sec: int = field(default=14400, repr=False)
fields: GetFileFields = field(default='*', repr=False)
image_thumbnail_process: str = field(default='image/resize,w_160/format,jpeg', repr=False)
image_url_process: str = fiel... |
class BaseModelTransformer(type_engine.TypeTransformer[pydantic.BaseModel]):
_TYPE_INFO = types.LiteralType(simple=types.SimpleType.STRUCT)
def __init__(self):
super().__init__(name='basemodel-transform', t=pydantic.BaseModel)
def get_literal_type(self, t: Type[pydantic.BaseModel]) -> types.LiteralT... |
class TestLogicConditionZ3():
def test_init_basic(self):
new_member = LogicCondition(Bool('x1'))
assert ((str(new_member) == 'x1') and isinstance(new_member, LogicCondition))
def test_init(self):
new_member = LogicCondition(Or(z3_symbol[1], And(z3_symbol[2], z3_symbol[3])))
asser... |
class EntrySetType(Enum):
IN: str = 'in'
INTRA: str = 'intra'
MIXED: str = 'mixed'
OUT: str = 'out'
def has_value(cls, value: str) -> bool:
return (value in _entry_set_type_values)
def get_entry_set_type_from_string(cls, entry_set_type: str) -> Optional['EntrySetType']:
if (not i... |
.django_db
def test_double_eclipsing_filters2(client, monkeypatch, elasticsearch_award_index, award_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas(client, {'require': [_fa_path(BASIC_TAS)], 'exclude': [_agency_path(BASIC_TAS), _tas_path(BASIC_TAS)]})
assert (resp.js... |
class HoldemPokerScore(Score):
NO_PAIR = 0
PAIR = 1
TWO_PAIR = 2
TRIPS = 3
STRAIGHT = 4
FLUSH = 5
FULL_HOUSE = 6
QUADS = 7
STRAIGHT_FLUSH = 8
def strength(self):
strength = self.category
for offset in range(5):
strength <<= 4
try:
... |
def test_config_from_str_invalid_section():
config_str = '[a]\nb = null\n\n[a.b]\nc = 1'
with pytest.raises(ConfigValidationError):
Config().from_str(config_str)
config_str = '[a]\nb = null\n\n[a.b.c]\nd = 1'
with pytest.raises(ConfigValidationError):
Config().from_str(config_str) |
class Example(flx.Widget):
persons = flx.TupleProp((), doc=' People to show cards for')
first_name = flx.StringProp('', settable=True)
last_name = flx.StringProp('', settable=True)
def add_person(self, name, info):
ppl = list(self.persons)
ppl.append((name, info))
self._mutate_pe... |
class OptionPlotoptionsLineSonificationTracksMappingRate(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._c... |
class StridedReshapeCatTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(StridedReshapeCatTestCase, self).__init__(*args, **kwargs)
self.test_count = 1
def _test_strided_reshape_cat(self, num_cat_ops=1, dtype='float16'):
target = detect_target()
if (int(targ... |
def downgrade():
op.drop_column('events_version', 'pay_onsite')
op.drop_column('events_version', 'pay_by_stripe')
op.drop_column('events_version', 'pay_by_paypal')
op.drop_column('events_version', 'pay_by_cheque')
op.drop_column('events_version', 'pay_by_bank')
op.drop_column('events', 'pay_onsi... |
class OptionSeriesPieStatesInactive(Options):
def animation(self) -> 'OptionSeriesPieStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesPieStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._confi... |
class VmSerializer(VmBaseSerializer):
hostname = s.Field()
uuid = s.CharField(read_only=True)
alias = s.Field()
node = s.SlugRelatedField(slug_field='hostname', read_only=True, required=False)
owner = s.SlugRelatedField(slug_field='username', read_only=True)
status = s.DisplayChoiceField(choices... |
class UnitRenderer(DefaultRenderer):
def DrawForeground(self, grid, attr, dc, rect, row, col, isSelected):
dc.SetBackgroundMode(wx.TRANSPARENT)
text = grid.model.GetValue(row, col)
dc.SetFont(self.font)
dc.DrawText(text, (rect.x + 1), (rect.y + 1))
def DrawBackground(self, grid, ... |
def generate_histogram_plotly(df, col, num_bins, plot_path):
import plotly.graph_objs as go
import plotly
import codecs
trace = go.Histogram(x=df[col], nbinsx=int(num_bins))
data = [trace]
layout = {'title': (col.capitalize() + ' Histogram')}
fig = go.Figure(data=data, layout=layout)
plo... |
def test_chat_id_str_conversion():
channel_id = '__channel_id__'
chat_id = '__chat_id__'
group_id = '__group_id__'
assert ((channel_id, chat_id, None) == chat_id_str_to_id(chat_id_to_str(channel_id=channel_id, chat_uid=chat_id))), 'Converting channel-chat ID without group ID'
assert ((channel_id, ch... |
(private_key_bytes=private_key_st, message_hash=message_hash_st)
def test_signatures_with_high_s(key_api, private_key_bytes, message_hash):
private_key = key_api.PrivateKey(private_key_bytes)
low_s_signature = private_key.sign_msg_hash(message_hash)
assert (coerce_low_s(low_s_signature.s) == low_s_signature... |
class PhiFunctionLifter():
def __init__(self, cfg: ControlFlowGraph, interference_graph: InterferenceGraph, phi_functions: DefaultDict[(BasicBlock, List[Phi])]):
self._cfg = cfg
self.interference_graph = interference_graph
self._phi_functions_of: DefaultDict[(BasicBlock, List[Phi])] = phi_fu... |
class NotebookImportExtractor(ImportExtractor):
def extract_imports(self) -> dict[(str, list[Location])]:
notebook = self._read_ipynb_file(self.file)
if (not notebook):
return {}
cells = self._keep_code_cells(notebook)
import_statements = [self._extract_import_statements_... |
class FrameHeader():
def read_header(cls, fp: IOWrapper) -> FrameHeader:
size = fp.read_short('header.size')
payload_type = fp.read_byte('header.payload_type')
reserved1 = fp.read_byte('header.reserved1')
frame_id = fp.read_long('header.id')
reserved2 = fp.read_bytes(8, 'head... |
class Project(_ProjectBase):
def __init__(self, name: str, project_path: Path) -> None:
self._path: Path = project_path
self._envvars = _load_project_envvars(project_path)
self._structure = expand_posix_vars(_load_project_structure_config(project_path), self._envvars)
self._build_pat... |
def add_tile_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument('-c', '--coordinates', metavar='<latitude>,<longitude>', help='coordinates of any location inside the tile')
parser.add_argument('-t', '--tile', metavar='<zoom level>/<x>/<y>', help='tile specification')
parser.add_argument... |
def test_affine_index_range7():
def bar(N: size):
assert (N >= 1)
assert (N <= 5)
for i in seq(0, 6):
for j in seq(0, (((- 3) + ((i + 2) * 5)) - N)):
pass
e = bar.find('for j in _:_').hi()._impl._node
i_sym = bar.find('for i in _:_')._impl._node.iter
N... |
class VelhopStation(BikeShareStation):
def __init__(self, data):
super(VelhopStation, self).__init__()
self.name = data['na']
self.latitude = float(data['coordonnees']['lat'])
self.longitude = float(data['coordonnees']['lon'])
self.bikes = int(data['av'])
self.free = ... |
class SettingsSelect(InteractiveEntityBase, SelectEntity):
def device_class(self) -> str:
return f'{DOMAIN}__settings'
def translation_key(self) -> str:
return 'settings'
def name_ext(self) -> (str | None):
if ((self._key in self._appliance.settings) and self._appliance.settings[self... |
def extractDawninfinityBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Dawn Infinity', 'Dawn Infinity', 'oel'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname,... |
class ForLoopNodeSerializer(LoopNodeSerializer):
def serialize(self, node: ForLoopNode) -> Dict:
data = super().serialize(node)
data.update({'declaration': self._pseudo.serialize(node.declaration), 'modification': self._pseudo.serialize(node.modification)})
return data
def deserialize(se... |
def _twilio_sms_dispatcher(messaging_config: MessagingConfig, message: str, to: Optional[str]) -> None:
if (not to):
logger.error('Message failed to send. No phone identity supplied.')
raise MessageDispatchException('No phone identity supplied.')
if (messaging_config.secrets is None):
lo... |
class Tracer(BaseComponent, ABC):
name = ComponentType.TRACER.value
def __init__(self, system_app: (SystemApp | None)=None):
super().__init__(system_app)
self.system_app = system_app
def init_app(self, system_app: SystemApp):
self.system_app = system_app
def append_span(self, spa... |
def diag_quadrupole3d_04(ax, da, A, bx, db, B, R):
result = numpy.zeros((3, 1, 15), dtype=float)
x0 = (0.5 / (ax + bx))
x1 = ((ax + bx) ** (- 1.0))
x2 = ((- x1) * ((ax * A[0]) + (bx * B[0])))
x3 = ((- x2) - B[0])
x4 = ((ax * bx) * x1)
x5 = numpy.exp(((- x4) * ((A[0] - B[0]) ** 2)))
x6 = ... |
def test_poll_option_from_graphql_alternate_format():
data = {'id': '', 'text': 'abc', 'viewer_has_voted': True, 'voters': {'count': 2, 'edges': [{'node': {'id': '1234'}}, {'node': {'id': '2345'}}]}}
assert (PollOption(text='abc', vote=True, voters=['1234', '2345'], votes_count=2, id='') == PollOption._from_gra... |
def test_search_result_serialization():
msg = OefSearchMessage(performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=('agent_1', 'agent_2', 'agent_3'), agents_info=OefSearchMessage.AgentsInfo({'key_1': {'key_1': b'value_1', 'key_2': b'value_2'}, 'key_2': {'key_3': b'value_3', 'key_4': b'value_4'}}))
... |
(scope='function')
def integration_mongodb_config(db) -> ConnectionConfig:
connection_config = ConnectionConfig(key='mongo_example', connection_type=ConnectionType.mongodb, access=AccessLevel.write, secrets=integration_secrets['mongo_example'], name='mongo_example')
connection_config.save(db)
(yield connect... |
def _start():
global patch, name, path, monitor
global delay, input_scale, input_offset, filename, fileformat, f, recording, filenumber, lock, trigger, item, thread
delay = patch.getfloat('general', 'delay')
input_scale = patch.getfloat('input', 'scale', default=None)
input_offset = patch.getfloat('... |
def is_aaaa_request(dnspkt: bytes):
(xid, flags, questions, answer_rrs, authority_rrs, add_rrs) = struct.unpack(HEADER_FMT, dnspkt[0:12])
if ((flags & 32768) != 0):
return False
if (questions != 1):
return False
is_aaaa = False
dns_fmt_ok = False
dnspkt = dnspkt[12:]
while 1:... |
def extractEasyDesignBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('-Yuri War-', "Yuri War of the Demon King's Daughter the Brave Hero Who Incarnates as the Ts Wants to ... |
(wx_available, 'Wx is not available')
class CompositeGridModelTestCase(unittest.TestCase):
def setUp(self):
self.model_1 = SimpleGridModel(data=[[1, 2], [3, 4]], rows=[GridRow(label='foo'), GridRow(label='bar')], columns=[GridColumn(label='cfoo'), GridColumn(label='cbar')])
self.model_2 = SimpleGrid... |
def calculate_correlation_matrix(X, Y=None):
if (Y is None):
Y = X
n_samples = np.shape(X)[0]
covariance = ((1 / n_samples) * (X - X.mean(0)).T.dot((Y - Y.mean(0))))
std_dev_X = np.expand_dims(calculate_std_dev(X), 1)
std_dev_y = np.expand_dims(calculate_std_dev(Y), 1)
correlation_matrix... |
class PreferencesTest(QuickbooksTestCase):
def setUp(self):
super(PreferencesTest, self).setUp()
self.account_number = datetime.now().strftime('%d%H%M')
self.name = 'Test Account {0}'.format(self.account_number)
def test_get(self):
preferences = Preferences.get(qb=self.qb_client)... |
def evolve_handler_ids(save_stats: dict[(str, Any)], val: int, string: str, ids: list[int], forced: bool) -> dict[(str, Any)]:
ids = helper.check_cat_ids(ids, save_stats)
evolves = save_stats['unlocked_forms']
if (not forced):
form_data = get_evolve_data(helper.check_data_is_jp(save_stats))
... |
def agency_data(helpers):
ta1 = baker.make('references.ToptierAgency', toptier_code='001', abbreviation='ABBR', name='NAME', mission='TO BOLDLY GO', about_agency_data='ABOUT', website='HTTP', justification='BECAUSE', icon_filename='HAI.jpg')
ta2 = baker.make('references.ToptierAgency', toptier_code='002', _fill... |
class FinancialLineItem(BaseModel):
tax: Optional[float] = Field(default=None, description='Tax amount for the line item.')
amount_line: Optional[float] = Field(default=None, description='Total amount for the line item.')
description: Optional[StrictStr] = Field(default=None, description='Description of the... |
def unified_yaml_load(configuration_file: Path) -> Dict:
package_type = configuration_file.parent.parent.name
with configuration_file.open(encoding='utf-8') as fp:
if (package_type != 'agents'):
return yaml.safe_load(fp)
data = yaml.safe_load_all(fp)
return list(data)[0] |
def test_copy_traineddata_files_briefcase(tmp_path, monkeypatch):
monkeypatch.setattr(system_info, 'is_briefcase_package', (lambda : True))
with resources.as_file(resources.files('normcap.resources')) as file_path:
resource_path = Path(file_path)
((resource_path / 'tessdata') / 'placeholder_1.traine... |
def extractShirokumamachinetranslationWordpressCom(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 (tagna... |
def forward(model: TransformerListener, docs, is_train):
if is_train:
if (model._batch_id is None):
outputs = []
for doc in docs:
if (doc._.trf_data is None):
raise ValueError(Errors.E203.format(name='transformer'))
else:
... |
def get_workflow_stub_fn(wm: WorkflowMethod):
def workflow_stub_fn(self, *args):
assert (self._workflow_client is not None)
return exec_workflow_sync(self._workflow_client, wm, args, workflow_options=self._workflow_options, stub_instance=self)
workflow_stub_fn._workflow_method = wm
return wo... |
def setup_sudoers(user):
from bench.config.lets_encrypt import get_certbot_path
if (not os.path.exists('/etc/sudoers.d')):
os.makedirs('/etc/sudoers.d')
set_permissions = (not os.path.exists('/etc/sudoers'))
with open('/etc/sudoers', 'a') as f:
f.write('\n#includedir /etc/sud... |
class Dialogues(BaseDialogues):
END_STATES = frozenset({Dialogue.EndState.SUCCESSFUL, Dialogue.EndState.FAILED})
def __init__(self, self_address: Address, message_class=DefaultMessage, dialogue_class=Dialogue, keep_terminal_state_dialogues=None) -> None:
def role_from_first_message(message: Message, rec... |
def pwn():
io_list_all = (libc_base + libc.symbols['_IO_list_all'])
system_addr = (libc_base + libc.symbols['system'])
vtable_addr = (heap_addr + 1480)
log.info(('_IO_list_all address: 0x%x' % io_list_all))
log.info(('system address: 0x%x' % system_addr))
log.info(('vtable address: 0x%x' % vtabl... |
def start():
global gameStarted, hunger, fun, health, alive, day, money
if (gameStarted == False):
gameStarted = True
hunger = 100
fun = 100
health = 100
day = 0
money = 0
sick = False
alive = True
startLabel.config(text='')
update(... |
def make_transfer_trace(block_number: int, transaction_hash: str, trace_address: List[int], from_address: str, to_address: str, token_address: str, amount: int):
return DecodedCallTrace(transaction_hash=transaction_hash, transaction_position=0, block_number=block_number, type=TraceType.call, trace_address=trace_add... |
def _AddVersionKeys(plist, version=None):
if version:
match = re.match('\\d+\\.\\d+\\.(\\d+\\.\\d+)$', version)
if (not match):
print(('Invalid version string specified: "%s"' % version), file=sys.stderr)
return False
full_version = match.group(0)
bundle_versi... |
('/dbphotos/<subject>/<pictype>/<page>')
def dbphotos(subject, pictype='S', page=0):
pictypes = {'R': '', 'S': '', 'W': ''}
del pictypes[pictype]
menus = []
for key in pictypes:
menus.append({'label': comm.colorize_label(pictypes[key], None, color='32FF94'), 'path': plugin.url_for('dbphotos', su... |
class TestOFReader(unittest.TestCase):
def test_simple(self):
reader = OFReader('abcdefg')
self.assertEquals(reader.read('2s')[0], 'ab')
self.assertEquals(reader.read('2s')[0], 'cd')
self.assertEquals(reader.read('3s')[0], 'efg')
with self.assertRaisesRegexp(loxi.ProtocolErro... |
class LedgerDialogues(LedgerApiDialogues):
def __init__(self, self_address: Address) -> None:
def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role:
return LedgerApiDialogue.Role.LEDGER
LedgerApiDialogues.__init__(self, self_address=self_address, r... |
class SliderInterface():
def __init__(self, qslider):
self.qslider = qslider
def value(self) -> int:
return self.qslider.value()
def value(self, value: int):
self.qslider.setValue(value)
def max(self) -> int:
return self.qslider.maximum()
def max(self, value: int):
... |
class TestXmlTreeWriter():
def test_should_create_separate_elements_depending_on_path(self):
xml_writer = XmlTreeWriter(E('root'), element_maker=E)
xml_writer.require_path(['parent', 'child1'])
xml_writer.append_text(TEXT_1)
xml_writer.require_path(['parent', 'child2'])
xml_w... |
def get_help_topic(help_entry):
help_topic = getattr(help_entry, 'key', None)
if (not help_topic):
help_topic = getattr(help_entry, 'db_key', 'unknown_topic')
if (not hasattr(help_entry, 'web_help_key')):
setattr(help_entry, 'web_help_key', slugify(help_topic))
return help_topic.lower() |
class HDFSBlobManager(BlobManager):
def __init__(self, config: Dict[(str, Any)]):
super().__init__(config)
if (not self.root_dir):
raise AIFlowConfigException('`root_directory` option of blob manager config is not configured.')
hdfs_url = config.get('hdfs_url', None)
if (... |
class Serve(BaseServe):
name = SERVE_APP_NAME
def __init__(self, system_app: SystemApp, api_prefix: Optional[str]=f'/api/v1/serve/{APP_NAME}', api_tags: Optional[List[str]]=None, db_url_or_db: Union[(str, URL, DatabaseManager)]=None, try_create_tables: Optional[bool]=False):
if (api_tags is None):
... |
class EnhancedIconView(Gtk.IconView):
__gtype_name__ = 'EnhancedIconView'
__gsignals__ = {'item-clicked': (GObject.SIGNAL_RUN_LAST, None, (object, object))}
object_column = GObject.property(type=int, default=(- 1))
def __init__(self, *args, **kwargs):
super(EnhancedIconView, self).__init__(*args... |
class TableConfig(OptionsWithTemplates):
('datatables-autoFill', 'datatables-autoFill')
def autoFill(self):
from epyk.core.html.tables.exts import DtAutoFill
return self._config_sub_data('autoFill', DtAutoFill.AutoFill)
def autoWidth(self):
return self._config_get()
def autoWidth... |
def _write_lookup_aciic_b(gen, t, srcs):
i1 = gen.emit_binop('*', [ConstIntArg(2), srcs[2]], Int)
i2 = gen.emit_binop('+', [ConstIntArg(1), i1], Int)
d1 = gen.emit_func_n(4, 'write_float_array_2D', [srcs[0], srcs[1], i1, srcs[3].re], Float)
d2 = gen.emit_func_n(4, 'write_float_array_2D', [srcs[0], srcs[... |
class EmailMessagesPrefs(QuickbooksBaseObject):
class_dict = {'InvoiceMessage': EmailMessageType, 'EstimateMessage': EmailMessageType, 'SalesReceiptMessage': EmailMessageType, 'StatementMessage': EmailMessageType}
def __init__(self):
super().__init__()
self.InvoiceMessage = None
self.Est... |
def register_dataset_split(dataset_name, split_dict):
_DATASET_TYPE_LOAD_FUNC_MAP = {'COCODataset': _register_extended_coco, 'COCOText': _register_coco_text, 'COCOTextDataset': _register_coco_text, 'LVISDataset': _register_extended_lvis}
factory = split_dict.get('DS_TYPE', 'COCODataset')
_DATASET_TYPE_LOAD_... |
def str2type(str_type):
str_type = str_type.strip()
if (' or ' in str_type):
subtypes = str_type.split(' or ')
return Union[tuple((str2type(subtype) for subtype in subtypes))]
try:
return eval(str_type)
except (TypeError, SyntaxError, NameError):
pass
if ('[' not in s... |
class OptionSeriesScatter3dStatesHoverHalo(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, ... |
class OptionSeriesHeatmapDataEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
de... |
def test_result_lengths_within_slots():
s = 'some random text that will be split by different slot lengths'
for i in range(10):
slots = [i, (i * 3), (i * 5), (i * 10)]
result = ad_from_string(s, slots=slots)
for (string, slot) in zip(result, slots):
assert (len(string) <= slo... |
('orca')
def test_orca_stable():
init_logging()
geom = geom_loader('lib:ozone.xyz')
orca_kwargs = {'keywords': 'UHF def2-SVP', 'pal': 1, 'mult': 1, 'charge': 0}
calc = ORCA(**orca_kwargs)
geom.set_calculator(calc)
unstable_energy = calc.get_energy(geom.atoms, geom.coords)['energy']
assert (u... |
def test_align_convert_align_mafft_fasta_to_phylip_relaxed(o_dir, e_dir, request):
program = 'bin/align/phyluce_align_convert_one_align_to_another'
output = os.path.join(o_dir, 'mafft-fasta-to-phylip-relaxed')
cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.