code stringlengths 281 23.7M |
|---|
def main():
if (len(sys.argv) != 3):
print('Usage: python {} input_folder output_folder'.format(sys.argv[0]))
sys.exit((- 1))
input_folder = sys.argv[1]
output_folder = sys.argv[2]
if (not os.path.exists(output_folder)):
os.makedirs(output_folder)
latest_versions = []
for... |
class ArrayEntry(MainBox):
def __init__(self, index, param_type, parent=None):
MainBox.__init__(self, ('#%s' % utf8(index)), param_type, True, parent)
self.index = index
self.setObjectName(''.join(['[', utf8(index), ']']))
self.param_widget.setFrameShape(QFrame.Box)
self.para... |
.parametrize('cmd_args', [['generate', '--output-path', 'generated/', '--verbose'], ['download', 'generated/airflow_dags.yml', '--verbose']])
.usefixtures('_mock_dag')
def test_verbose(cmd_args):
result = runner.invoke(cli.app, cmd_args)
assert (result.exit_code == 0)
assert result.stdout.startswith('Runnin... |
def extractShayteatranslationsWordpressCom(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... |
class UseAttack(AskForCard):
card_usage = 'use'
def __init__(self, target):
from thb.cards.definition import AttackCard
AskForCard.__init__(self, target, target, AttackCard)
def process_card(self, card):
g = self.game
return g.process_action(UseCard(self.target, card))
de... |
def extract1EarthresearchCom(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 _set_stdout_logging(event_file):
class Logger(object):
def __init__(self, event_file, log_tag):
self.terminal = sys.stdout
self.event_file = event_file
self.tag = log_tag
self._buffer = []
def write(self, message):
self.terminal.write(m... |
class SmartNotebook(Gtk.Notebook):
def __init__(self, vertical: bool=False):
Gtk.Notebook.__init__(self)
self.set_scrollable(True)
self.connect('button-press-event', self.on_button_press)
self.connect('popup-menu', self.on_popup_menu)
self.connect('notify::tab-pos', self.__on... |
class TransformerEstimator(BaseEstimator):
def __init__(self, preprocessing, indexer, verbose=False, backend=None, n_jobs=(- 1), dtype=None):
super(TransformerEstimator, self).__init__()
self.preprocessing = preprocessing
self.indexer = indexer
self.verbose = verbose
self.bac... |
def gen_list_jtype(java_base_name):
return JType('List<{}>'.format(java_base_name)).op(read='ChannelUtils.readList(bb, $length, {}Ver$version.READER)'.format(java_base_name), write='ChannelUtils.writeList(bb, $name)', default='ImmutableList.<{}>of()'.format(java_base_name), funnel='FunnelUtils.putList($name, sink)'... |
def get_data_from_request(request: func.HttpRequest, capture_headers=False, capture_body=False):
result = {'method': request.method}
if ('Cookie' in request.headers):
cookie = SimpleCookie()
cookie.load(request.headers['Cookie'])
result['cookies'] = {k: v.value for (k, v) in cookie.items... |
def test_full_chat_pagination(channel, slave):
storage_id = (TelegramChatID(0), TelegramMessageID(1))
(legends, buttons) = channel.chat_binding.slave_chats_pagination(storage_id)
legend = '\n'.join(legends)
assert (slave.channel_emoji in legend)
assert (slave.channel_name in legend)
assert (min(... |
class ValveTestTransitOrderedTunnel(ValveTestBases.ValveTestTunnel):
TRANSIT_ID = 2
CONFIG = "\nacls:\n transit_acl:\n - rule:\n dl_type: 0x0800\n ip_proto: 1\n actions:\n output:\n - tunnel: {dp: s3, port: 1}\nvlans:\n vlan100:\n ... |
.asyncio
.workspace_host
class TestPostResetPassword():
.parametrize('data', [pytest.param({}, id='Missing password and token'), pytest.param({'password': 'newherminetincture'}, id='Missing token'), pytest.param({'token': 'TOKEN'}, id='Missing password'), pytest.param({'token': 'TOKEN', 'password': 'newherminetinct... |
class Message():
caller: Address
target: Union[(Bytes0, Address)]
current_target: Address
gas: Uint
value: U256
data: Bytes
code_address: Optional[Address]
code: Bytes
depth: Uint
should_transfer_value: bool
is_static: bool
accessed_addresses: Set[Address]
accessed_st... |
class OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingVolume(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, tex... |
def fill_header_params_from_parent(parent: BlockHeaderAPI, gas_limit: int, difficulty: int, timestamp: int, coinbase: Address=ZERO_ADDRESS, nonce: bytes=None, extra_data: bytes=None, transaction_root: bytes=None, state_root: bytes=None, mix_hash: bytes=None, receipt_root: bytes=None) -> Dict[(str, HeaderParams)]:
i... |
class TestDummyrunnerSettings(TestCase):
def setUp(self):
self.client = Mock()
self.client.cid = 1
self.client.counter = Mock(return_value=1)
self.client.gid = '-1'
self.client.name = ('Dummy_%s' % self.client.gid)
self.client.password = (Something,)
self.clie... |
class TestIntFlag(TestCase):
def setUp(self):
class Perm(IntFlag):
_order_ = 'R W X'
R = (1 << 2)
W = (1 << 1)
X = (1 << 0)
class Color(IntFlag):
BLACK = 0
RED = 1
GREEN = 2
BLUE = 4
PURPLE = ... |
class CustomBuildExtCommand(build_py):
def buildInkscapeExt(self):
os.system('{} {} {}'.format(sys.executable, os.path.join('scripts', 'boxes2inkscape'), 'inkex'))
def updatePOT(self):
os.system('{} {} {}'.format(sys.executable, os.path.join('scripts', 'boxes2pot'), 'po/boxes.py.pot'))
o... |
class OptionSeriesScatter3dLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text, ... |
.parametrize('dates', [[, ], ['', ''], 'all'])
def test_import_restart_namestyle(dates, reek_run):
gps = reek_run.get_restart_properties(names=['PRESSURE', 'SWAT'], dates=dates, namestyle=1)
assert (gps['PRESSURE--1999_12_01'].values.mean() == pytest.approx(334.52327, abs=0.001))
assert (gps['SWAT--1999_12_... |
class BaseJobRunner():
def __init__(self):
self.__log_dir = None
def run(self, name, working_dir, script, args):
raise NotImplementedError("Subclass must implement 'run'")
def terminate(self, job_id):
raise NotImplementedError("Subclass must implement 'terminate'")
def list(self)... |
class PublicIdRegistry(Generic[Item], Registry[(PublicId, Item)]):
__slots__ = ('_public_id_to_item',)
def __init__(self) -> None:
super().__init__()
self._public_id_to_item: Dict[(PublicId, Item)] = {}
def register(self, public_id: PublicId, item: Item, is_dynamically_added: bool=False) -> ... |
def get_bp_handler(intercept):
split_str = intercept.cls.split('.')
module_str = '.'.join(split_str[:(- 1)])
class_str = split_str[(- 1)]
module = importlib.import_module(module_str)
cls_obj = getattr(module, class_str)
if (cls_obj in initalized_classes):
bp_class = initalized_classes[cl... |
class XYZD65(RGBish, Space):
BASE = 'xyz-d65'
NAME = 'xyz-d65'
SERIALIZE = ('xyz-d65', 'xyz')
CHANNELS = (Channel('x', 0.0, 1.0), Channel('y', 0.0, 1.0), Channel('z', 0.0, 1.0))
WHITE = WHITES['2deg']['D65']
def is_achromatic(self, coords: Vector) -> bool:
for x in alg.vcross(coords, uti... |
def key_click_text_entry(control, interaction, delay, get_selection=(lambda control: control.GetSelection())):
if (not (control.IsEnabled() and control.IsEditable())):
raise Disabled('{!r} is disabled.'.format(control))
if (not control.HasFocus()):
control.SetFocus()
control.SetInsertion... |
def test_is_up_to_date():
origin = _DEFAULT_HTTPS_REPO_URL
source = _generate_source_tree_from_origin(origin)
with mock.patch('src.lib.source_tree.SourceTree.get_revs_behind_parent_branch', mock.MagicMock(return_value=0)) as magic_mock:
up_to_date = source.is_up_to_date()
magic_mock.assert_c... |
def extractBluedreamsblogonlineWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('romc', 'Rebirth of MC', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', '... |
def smallest_int_type_for_range(minimum, maximum):
signed = (minimum < 0)
abs_max = max(maximum, abs(minimum))
if signed:
if (abs_max < (1 << 7)):
return numpy.int8
elif (abs_max < (1 << 15)):
return numpy.int16
elif (abs_max < (1 << 31)):
return n... |
def test_task_set_command(task_definition):
task_definition.set_commands(webserver=u'run-webserver', application=u'run-application')
for container in task_definition.containers:
if (container[u'name'] == u'webserver'):
assert (container[u'command'] == [u'run-webserver'])
if (containe... |
def _create_plot_component():
xs = uniform(((- 2) * pi), (2 * pi), 600)
xs.sort()
ys = uniform(((- 1.5) * pi), (1.5 * pi), 300)
ys.sort()
(x, y) = meshgrid(xs, ys)
z = (tanh(((x * y) / 6)) * cosh(((exp((- (y ** 2))) * x) / 3)))
z = (x * y)
mask = ((abs((x - 5)) <= 1) & (abs((y - 2)) <= 2... |
class Loader(QtileLoader):
def __init__(self, *directories, masked=True, **kwargs):
self.img_class = (ImgMask if masked else Img)
QtileLoader.__init__(self, *directories, **kwargs)
def __call__(self, *names):
d = {}
seen = set()
set_names = set()
for n in names:
... |
def test_download_json(monkeypatch, mock_get_info, tmp_path):
sim = make_sim()
def mock_download(*args, **kwargs):
pass
def get_str(*args, **kwargs):
return sim.json().encode('utf-8')
monkeypatch.setattr(f'{task_core_path}.download_file', mock_download)
monkeypatch.setattr(f'{task_co... |
class Solution():
def integerBreak(self, n: int) -> int:
dp = [1 for _ in range((n + 1))]
for i in range(3, (n + 1)):
for j in range(1, i):
dp[i] = max(dp[i], (dp[j] * dp[(i - j)]), (j * dp[(i - j)]), (j * (i - j)))
print(dp)
return dp[(- 1)] |
class ServiceVersionDetailOrNull(ModelComposed):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = True
_property
def openapi_types():
lazy_i... |
def guanaco_generate_output(model, tokenizer, params, device, context_len=2048):
'Fork from:
print(params)
stop = params.get('stop', '###')
prompt = params['prompt']
query = prompt
print('Query Message: ', query)
input_ids = tokenizer(query, return_tensors='pt').input_ids
input_ids = in... |
def get_service_unit_type():
service_unit_type = get_random('Healthcare Service Unit Type', filters={'inpatient_occupancy': 1})
if (not service_unit_type):
service_unit_type = frappe.new_doc('Healthcare Service Unit Type')
service_unit_type.service_unit_type = '_Test Service Unit Type Ip Occupan... |
def synchronized(func):
(func)
def wrapper(self, *__args, **__kw):
try:
rlock = self._sync_lock
except AttributeError:
from threading import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
rlock.acquire()
try:
return f... |
class TestPutYamlDatasets():
def dataset_url(self, connection_config) -> str:
path = (V1_URL_PREFIX + YAML_DATASETS)
path_params = {'connection_key': connection_config.key}
return path.format(**path_params)
def test_patch_dataset_not_authenticated(self, example_yaml_dataset: str, dataset... |
def auto_install_ndk(build):
import sdkmanager
global config
if build.get('disable'):
return
ndk = build.get('ndk')
if (not ndk):
return
if isinstance(ndk, str):
sdkmanager.build_package_list(use_net=True)
_install_ndk(ndk)
elif isinstance(ndk, list):
... |
_os(*metadata.platforms)
def main():
powershell = 'C:\\Users\\Public\\posh.exe'
temp = 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\temp_persist.exe'
binary = 'C:\\Users\\Public\\winword.exe'
common.copy_file(EXE_FILE, powershell)
common.copy_file(powershell, binary)
comm... |
class TestAerospikeStore():
()
def aero(self):
with patch('faust.stores.aerospike.aerospike') as aero:
(yield aero)
.asyncio
async def test_get_aerospike_client_new(self, aero):
client_mock = MagicMock()
aero.client = MagicMock(return_value=client_mock)
client... |
class TestInvertTree(unittest.TestCase):
def test_invert_tree(self):
root = Node(5)
bst = InverseBst(root)
node2 = bst.insert(2)
node3 = bst.insert(3)
node1 = bst.insert(1)
node7 = bst.insert(7)
node6 = bst.insert(6)
node9 = bst.insert(9)
resul... |
def test_coverage_tx(json_path, plugintester):
plugintester.runpytest('-n 2')
with json_path.open() as fp:
build = json.load(fp)
assert (not len(build['tx']))
plugintester.runpytest('--numprocesses=2', '--coverage')
with json_path.open() as fp:
build = json.load(fp)
assert (len(b... |
.integration
class TestDefaultTaxonomyCrud():
.parametrize('endpoint', TAXONOMY_ENDPOINTS)
def test_api_cannot_delete_default(self, test_config: FidesConfig, endpoint: str) -> None:
resource = getattr(DEFAULT_TAXONOMY, endpoint)[0]
result = _api.delete(url=test_config.cli.server_url, resource_ty... |
def test_secondary_sort(setup_test_data, client):
resp = client.get((url + '?sort=fiscal_year&order=asc'))
assert (resp.status_code == status.HTTP_200_OK)
response = resp.json()
assert (len(response['results']) == 3)
expected_results = [{'fiscal_year': 2019, 'fiscal_period': 6, 'current_total_budget... |
def test_handle_graphql_invalid_values():
error = {'message': 'Invalid values provided for variables of operation "MessengerThreadlist": Value ""as"" cannot be used for variable "$limit": Expected an integer value, got "as".', 'severity': 'CRITICAL', 'code': 1675012, 'api_error_code': None, 'summary': "Your request... |
def fixture_to_computation(fixture, code, vm):
message = Message(to=fixture['exec']['address'], sender=fixture['exec']['caller'], value=fixture['exec']['value'], data=fixture['exec']['data'], code=code, gas=fixture['exec']['gas'])
transaction_context = BaseTransactionContext(origin=fixture['exec']['origin'], ga... |
class Batcher(MultiThreadTrajectoryBatcher):
def __init__(self, n_timesteps, n_slots, create_agent, agent_args, create_env, env_args, n_threads, seeds=None):
if (rlstructures.__deprecated_message__ == False):
print('[DEPRECATED]: The current version of rlstructures is based on rlstructures.rl_ba... |
class time(TestCase):
def assertFormatEqual(self, seconds, formatted):
self.assertEqual(util.format_timedelta(datetime.timedelta(seconds=seconds)), formatted)
def test_timedelta(self):
self.assertFormatEqual(0, '0:00')
self.assertFormatEqual(1, '0:01')
self.assertFormatEqual(59, ... |
class RedisPublishHandler(logging.Handler):
def __init__(self, rc, who, level=logging.NOTSET):
super(RedisPublishHandler, self).__init__(level)
self.rc = rc
self.who = who
def emit(self, record):
record = logging.makeLogRecord(record.__dict__)
record.who = self.who
... |
def extractDeadtoorightsBlogspotCom(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 ContentPublishingLimitResponse(AbstractObject):
def __init__(self, api=None):
super(ContentPublishingLimitResponse, self).__init__()
self._isContentPublishingLimitResponse = True
self._api = api
class Field(AbstractObject.Field):
config = 'config'
quota_usage = 'quo... |
def _lsstr(ls, prec=0):
if isinstance(ls, LS.Empty):
return ''
elif isinstance(ls, LS.Point):
coords = ','.join([str(a) for a in ls.coords])
typ = (f':{ls.type}' if ls.type else '')
return f'{{({ls.name},{coords}{typ})}}'
elif isinstance(ls, LS.WholeBuf):
coords = ','... |
def test_get_event_listener():
browser = pychrome.Browser()
tab = browser.new_tab()
def request_will_be_sent(**kwargs):
tab.stop()
tab.start()
tab.Network.requestWillBeSent = request_will_be_sent
tab.Network.enable()
try:
tab.Page.navigate(url='chrome://newtab/')
except p... |
class TestReindex(object):
async def test_reindex_passes_kwargs_to_scan_and_bulk(self, async_client, reindex_setup):
(await helpers.async_reindex(async_client, 'test_index', 'prod_index', scan_kwargs={'q': 'type:answers'}, bulk_kwargs={'refresh': True}))
assert (await async_client.indices.exists(ind... |
class TaskManagerTestCase(TestCase):
def test_nb_workers_positive(self):
obj = TaskManager()
obj.nb_workers
def test_stop_already_stopped(self):
obj = TaskManager()
with mock.patch.object(obj.logger, 'debug') as debug_mock:
obj.stop()
debug_mock.assert_cal... |
class TestDNSVanillaAggressivePacketCapture(LocalPacketCaptureTestCase):
HOSTNAMES = ['google.com', 'twitter.com', 'facebook.com', 'stackoverflow.com', 'yahoo.com', 'amazon.com']
NUM_PROCESSES = 10
def __init__(self, devices, parameters):
super().__init__(devices, parameters)
self.dns_server... |
class TestTachoMotorPositionValue(ptc.ParameterizedTestCase):
def test_position_large_negative(self):
self._param['motor'].position = (- 1000000)
self.assertEqual(self._param['motor'].position, (- 1000000))
def test_position_min_negative(self):
self._param['motor'].position = (- 1)
... |
def filterByVia(routes, viaSet, viaStartPos):
if (not routes):
return ()
matchedRoutes = []
partialRoutes = {}
maxMet = 0
for route in routes:
met = 0
for hop in route.route[viaStartPos:]:
if ((hop in viaSet) or (hop.system in viaSet)):
met += 1
... |
def test_readMetaInfo_unsupported_format_version(ufo_path, caplog):
metainfo = {'formatVersion': 10, 'formatVersionMinor': 15}
(ufo_path / 'metainfo.plist').write_bytes(plistlib.dumps(metainfo))
with pytest.raises(UnsupportedUFOFormat):
UFOReader(ufo_path)
with pytest.raises(UnsupportedUFOFormat... |
.django_db
def test_budget_function_list_sort_by_gross_outlay_amount(client, monkeypatch, agency_account_data, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
query_params = f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}&order=asc&sort=gross_outlay_amount'
resp = client.get(url.format(cod... |
def log_call(action, args: List[str]=[], *, dbt_config=None):
def _log_call(func):
(func)
def wrapper(*func_args, **func_kwargs):
sig = inspect.signature(func).bind(*func_args, **func_kwargs)
sig.apply_defaults()
log_args = dict(map((lambda arg: (arg, sig.argument... |
class OrganPipe(Boxes):
ui_group = 'Unstable'
def getFrequency(self, pitch, octave, base_freq=440):
steps = ((pitches.index(pitch) + ((octave - 4) * 12)) - 9)
return (base_freq * (2 ** (steps / 12.0)))
def getRadius(self, pitch, octave, intonation):
steps = ((pitches.index(pitch) + (... |
class OPAWDLState(DataClassJsonMixin):
plugin_name: str = field(metadata=config(field_name='PluginName'))
cmd_args_list: List[str] = field(metadata=config(field_name='CmdArgsList'))
timeout: Optional[int] = field(metadata=config(field_name='Timeout'), default=None)
next_: Optional[str] = field(metadata=... |
class OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 extractTheBanditsStrategyEngTlTumblrCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("the bandit's strategy", "the bandit's strategy", 'translated'), ('PRC', 'PRC', 'tran... |
class TestNestedDictField(FieldValues):
valid_inputs = [({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}})]
invalid_inputs = [({0: {'a': 1, 'b': None}, 1: {'c': None}}, {'0': {'b': ['This field may not be null.']}, '1': {'c': ['This field may not be null.']}}), ({0: 'not a dict'}... |
def test_recursive_update_all_values():
class SampleConfigModel(BaseModel):
test: str
timeout: float
values = {'test': 'hello'}
result = recursive_update_all_values(SampleConfigModel, values, ['sample'], value_storage={'SAMPLE_TIMEOUT': 3})
assert (result == {'test': 'hello', 'timeout': ... |
def drawedge(theta, r, w, N):
thetar = np.array(((theta * np.pi) / 180))
imCentre = (((np.array([N, N]).T - 1) / 2) + 1)
r = ((np.array([np.cos(thetar), np.sin(thetar)]) * (- 1)) * (r - imCentre))
w = np.maximum(1, w)
ramp = (np.arange(0, N) - ((N + 1) / 2))
hgrad = ((np.sin(thetar) * (- 1)) * n... |
def _build_error_message(code, exc_type, custom_message):
default_message = (exc_type.default_message if (exc_type and hasattr(exc_type, 'default_message')) else 'Error while calling Auth service')
ext = (' {0}'.format(custom_message) if custom_message else '')
return '{0} ({1}).{2}'.format(default_message,... |
(('slice_name', 'slice_'), slice_items)
def test_delitem_slice(slice_name, slice_, fx_asset):
with Image(filename=str(fx_asset.joinpath('apple.ico'))) as img:
instances = list(img.sequence)
del instances[slice_]
del img.sequence[slice_]
assert (list(img.sequence) == instances)
... |
class LoadExp(Exp):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.addr = (build_exp(**kwargs['addr']) if isinstance(kwargs['addr'], dict) else kwargs['addr'])
self.endian = kwargs['endian']
self.size = kwargs['size']
def __repr__(self):
retur... |
class AmbassadorEventWatcher(threading.Thread):
Actions = {'F-F-F': ('unhealthy', True), 'F-F-T': ('now-healthy', True), 'F-T-F': ('now-unhealthy', True), 'F-T-T': ('healthy', True), 'T-F-F': ('unhealthy', False), 'T-F-T': ('now-healthy', True), 'T-T-F': ('now-unhealthy', True), 'T-T-T': ('update', False)}
reCo... |
def get_exports(proj_dir):
exports = {}
if util.is_valid_project_dir(proj_dir):
dic = util.load_fips_yml(proj_dir)
if ('exports' in dic):
exports = dic['exports']
if (not ('header-dirs' in exports)):
exports['header-dirs'] = []
if (not ('conditional-header-dirs' in ex... |
class TestHubBlockingDetector(tests.LimitedTestCase):
TEST_TIMEOUT = 10
def test_block_detect(self):
def look_im_blocking():
import time
time.sleep(2)
from eventlet import debug
debug.hub_blocking_detection(True)
gt = eventlet.spawn(look_im_blocking)
... |
class NestedPureParallel(Computation):
def __init__(self, size, dtype):
Computation.__init__(self, [Parameter('output', Annotation(Type(dtype, shape=size), 'o')), Parameter('input', Annotation(Type(dtype, shape=size), 'i'))])
self._p = PureParallel([Parameter('output', Annotation(Type(dtype, shape=s... |
class ObligationsByAwardCategory(AgencyBase):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/agency/toptier_code/obligations_by_award_category.md'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.params_to_validate = ['fiscal_year']
_response()
def ... |
class OptionSeriesAreaDataAccessibility(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(flag, js... |
def add_fast_rcnn_outputs(model, blob_in, dim):
model.FC(blob_in, 'cls_score', dim, model.num_classes, weight_init=gauss_fill(0.01), bias_init=const_fill(0.0))
if (not model.train):
model.Softmax('cls_score', 'cls_prob', engine='CUDNN')
num_bbox_reg_classes = (2 if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG el... |
_router_advert.register_nd_option_type
class nd_option_mtu(nd_option):
_PACK_STR = '!BBHI'
_LEN = struct.calcsize(_PACK_STR)
_OPTION_LEN = (_LEN // 8)
def option_type(cls):
return ND_OPTION_MTU
def __init__(self, mtu=1500):
super(nd_option_mtu, self).__init__(self.option_type(), 0)
... |
def SetMass(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'mass']
optional_params = []
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('SetMass')
msg.write_float32(kwargs['mass'])
return msg |
def remove_exchanges(zone_key: ZoneKey):
def _is_zone_in_exchange(exchange_config_path: str) -> bool:
exchange_key = exchange_config_path.split('/')[(- 1)].split('.')[0]
return (zone_key in exchange_key.split(EXCHANGE_FILENAME_ZONE_SEPARATOR))
exchanges = [e for e in glob(str((ROOT_PATH / 'confi... |
def test_prefer_query_language(prompt_manager: PromptManager):
for language in ['en', 'zh']:
prompt_template = PromptTemplate(template='test', input_variables=[], template_scene='chat_normal')
prompt_manager.save(prompt_template, prompt_name='test_prompt', prompt_language=language)
result = prom... |
class OptionSeriesScatter3dSonificationDefaultinstrumentoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
def ecadd(computation: ComputationAPI, gas_cost: int=constants.GAS_ECADD) -> ComputationAPI:
computation.consume_gas(gas_cost, reason='ECADD Precompile')
try:
result = _ecadd(computation.msg.data_as_bytes)
except ValidationError:
raise VMError('Invalid ECADD parameters')
(result_x, resul... |
.parametrize('file_data', ['PROP\n 1 2 3 4 / \n', 'OTHERPROP\n 1 2 3 /\n 4 5 /\nPROP\n 1 2 3 4 / \n', 'OTHERPROP\n 1 2 3 /\n 4 5 /\n/ PROP Eclipse comment\nPROP\n 1 2 3 4 / \n', 'PROP\n 1 2 3 4 /', 'PROP\n -- a comment \n 1 2 3 4 /', '-- a comment \nPROP\n \n 1 2 3 4 /', 'PROP\n \n 1 2 \n -- a comment \n 3 4 /', 'NOECH... |
def extractErenstranslationHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Nii-san', 'Do You Think You Can Run After Reincarnating, Nii-san?', 'translated'), ('PRC', '... |
def test_nb_morphologizer_spaces(NLP):
doc = NLP('Some\nspaces are\tnecessary.')
assert (doc[0].pos != SPACE)
assert (doc[0].pos_ != 'SPACE')
assert (doc[1].pos == SPACE)
assert (doc[1].pos_ == 'SPACE')
assert (doc[1].tag_ == 'SPACE')
assert (doc[2].pos != SPACE)
assert (doc[3].pos != SP... |
def send_booking_receipt(booking, send_to=None):
location = booking.use.location
subject = ('[%s] Receipt for Booking %s - %s' % (location.email_subject_prefix, str(booking.use.arrive), str(booking.use.depart)))
if send_to:
recipient = [send_to]
else:
recipient = [booking.use.user.email]... |
def fifo36(tile_name, luts, lines, sites):
params = {}
params['tile'] = tile_name
params['Y0_IN_USE'] = True
params['Y1_IN_USE'] = True
params['FIFO_Y0_IN_USE'] = True
params['FIFO_Y1_IN_USE'] = True
data_width = random.choice((4, 9))
if (data_width == 4):
ALMOST_EMPTY_OFFSET = 8... |
def post_solve_bird_pig(arbiter, space, _):
surface = screen
(a, b) = arbiter.shapes
bird_body = a.body
pig_body = b.body
p = to_pygame(bird_body.position)
p2 = to_pygame(pig_body.position)
r = 30
pygame.draw.circle(surface, BLACK, p, r, 4)
pygame.draw.circle(surface, RED, p2, r, 4)
... |
class HexGridDraw():
def __init__(self, grid, color_func, file_name, rivers=True, numbers=False, show_coasts=False, borders=False, text_func=None):
self.image = Image.new('RGB', (int((HEX_RECT_WIDTH * (grid.hex_grid.size + 0.6))), int((HEX_RECT_WIDTH * grid.hex_grid.size))))
self.draw = ImageDraw.Dr... |
class PrescribInfo(models.Model):
class Meta():
verbose_name = 'Product Prescribing Information'
ampp = models.OneToOneField(db_column='appid', to='AMPP', on_delete=models.CASCADE, help_text='AMPP')
sched_2 = models.BooleanField(help_text='Schedule 2')
acbs = models.BooleanField(help_text='ACBS'... |
def AuthorizeMachineAndConnectDB(db_instance_name, project, username, database, logfile):
hostname = GetInstanceIP(db_instance_name, project)
password = utils.GetRandomPassword()
sh_utils.RunGCloudService(['users', 'set-password', username, '%', '--instance', db_instance_name, '--password', password], proje... |
def test_handles_multi_step_setup():
env = build_dummy_structured_env()
env = LogStatsWrapper.wrap(env)
env.reset()
for i in range(4):
env.step(env.action_space.sample())
assert (len(env.episode_event_log.step_event_logs) == 2)
env.write_epoch_stats()
assert (env.get_stats_value(Rewa... |
def test_phylip_parser():
SEQS2 = SeqGroup(ds.phylip_interleaved, format='iphylip')
with NamedTemporaryFile('wt') as f_iphylip:
f_iphylip.write(ds.phylip_interleaved)
f_iphylip.flush()
SEQS = SeqGroup(f_iphylip.name, format='iphylip')
assert (SEQS.write() == SEQS2.write())
with N... |
class SanaeFaithReturnCardAction(GenericAction):
card_usage = 'handover'
no_reveal = True
def apply_action(self) -> bool:
g = self.game
(src, tgt) = (self.source, self.target)
cards = user_choose_cards(self, src, ('cards', 'showncards', 'equips'))
c = (cards[0] if cards else ... |
class SmartSymbolsExtension(Extension):
def __init__(self, *args, **kwargs):
self.config = {'trademark': [True, 'Trademark'], 'copyright': [True, 'Copyright'], 'registered': [True, 'Registered'], 'plusminus': [True, 'Plus/Minus'], 'arrows': [True, 'Arrows'], 'notequal': [True, 'Not Equal'], 'fractions': [Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.