code stringlengths 281 23.7M |
|---|
def delexicalize_one_sent(sent):
def normalize(text):
def insertSpace(token, text):
sidx = 0
while True:
sidx = text.find(token, sidx)
if (sidx == (- 1)):
break
if (((sidx + 1) < len(text)) and re.match('[0-9]', text... |
def _bump_regex(version: str) -> str:
match = re.match('(.*?)(\\d+)$', version)
if (match is None):
raise ValueError(f'{version} does not end with a number to bump, please correct or use a custom version scheme')
else:
(prefix, tail) = match.groups()
return f'{prefix}{(int(tail) + 1)... |
def main():
set_starting_dir_abs_path('C:\\Development\\qf-lib')
stats_factory = InitialRiskStatsFactory(max_accepted_dd=0.3, target_return=0.1)
initial_risks_list = [0.001, 0.005, 0.01, 0.02, 0.05]
scenarios_generator = ScenariosGenerator()
scenarios_df_list = []
nr_of_param_sets = len(initial_... |
.parametrize(('has_artifacts', 'rb_damage_mode'), [(False, DreadRavenBeakDamageMode.CONSISTENT_LOW), (True, DreadRavenBeakDamageMode.CONSISTENT_LOW), (False, DreadRavenBeakDamageMode.CONSISTENT_HIGH), (False, DreadRavenBeakDamageMode.UNMODIFIED)])
def test_dread_format_params(has_artifacts: bool, rb_damage_mode: DreadR... |
def generate_body(pkg, remediation, vulns, *, api_key):
changelog = fetch_changelog(pkg, remediation['version'], remediation['recommended_version'], api_key=api_key, from_spec=remediation.get('requirement', {}).get('specifier', None))
p = (Path(__file__).parent / 'templates')
env = jinja2.Environment(loader... |
class MaterializeResult(dict):
def of(delta: Delta, task_index: int, pyarrow_write_result: PyArrowWriteResult, referenced_pyarrow_write_result: Optional[PyArrowWriteResult]=None, peak_memory_usage_bytes: Optional[np.double]=None, telemetry_time_in_seconds: Optional[np.double]=None, task_completed_at: Optional[np.do... |
(name='connector')
def remote_connector():
executor_mock = MagicMock(CSExecutor)
executor_mock.server_info = MagicMock(CSServerInfo)
executor_mock.server_info.uuid = INVALID_UUID
executor_mock.server_info.platform = 'Freeware'
connector = CSRemoteConnector(executor_mock)
return connector |
class PurePursuitExpert():
def __init__(self, env, ref_velocity=REF_VELOCITY, position_threshold=POSITION_THRESHOLD, following_distance=FOLLOWING_DISTANCE, max_iterations=1000):
self.env = env.unwrapped
self.following_distance = following_distance
self.max_iterations = max_iterations
... |
def test_normalize_height(view):
item1 = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item1)
item1.setSelected(True)
item2 = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item2)
item2.setSelected(True)
item2.setScale(3)
view.scene.cancel_crop_mode = MagicMock()
with patch.obje... |
def test_exit_unsuccessful(qtbot, proc, message_mock, py_proc, caplog):
with caplog.at_level(logging.ERROR):
with qtbot.wait_signal(proc.finished, timeout=10000):
proc.start(*py_proc('import sys; sys.exit(1)'))
msg = message_mock.getmsg(usertypes.MessageLevel.error)
expected = 'Testproce... |
def generate(batch, size):
ptrain = 'data/train'
pval = 'data/validation'
datagen1 = ImageDataGenerator(rescale=(1.0 / 255), shear_range=0.2, zoom_range=0.2, rotation_range=90, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True)
datagen2 = ImageDataGenerator(rescale=(1.0 / 255))
tra... |
def test_file_dependency_pep_508_local_file_localhost(mocker: MockerFixture) -> None:
path = (DIST_PATH / 'demo-0.2.0.tar.gz')
requirement = f'demo file://localhost{path.as_posix()}'
expected = f'demo {path.as_uri()}'
_test_file_dependency_pep_508(mocker, 'demo', path, requirement, expected) |
def save_path_formatter(args):
args_dict = vars(args)
data_folder_name = args_dict['dataset']
folder_string = [data_folder_name]
key_map = OrderedDict()
key_map['model'] = ''
key_map['aux_loss'] = 'aux'
key_map['epochs'] = 'ep'
key_map['lr'] = ''
key_map['batch_size'] = 'bs'
key_... |
class NormalizeItems(QtGui.QUndoCommand):
def __init__(self, items, scale_factors):
super().__init__('Normalize items')
self.items = items
self.scale_factors = scale_factors
def redo(self):
self.old_scale_factors = []
for (item, factor) in zip(self.items, self.scale_facto... |
def main():
parser = build_parser()
args = parser.parse_args()
truth = load_file_flex_format(args.truth)
truth.X = utils.ensure_arr(truth.X)
logging.info(f'Loaded truth {args.truth}: {truth.shape}')
preds = load_file_flex_format(args.preds)
preds.X = utils.ensure_arr(preds.X)
logging.inf... |
class ShuffleNet_Auxiliary(nn.Module):
def __init__(self, cfg, num_classes=100):
super(ShuffleNet_Auxiliary, self).__init__()
self.backbone = ShuffleNet(cfg, num_classes=num_classes)
self.auxiliary_classifier = Auxiliary_Classifier(cfg, num_classes=(num_classes * 4))
def forward(self, x,... |
def _create_resources_rc(pdfium_build):
input_path = ((PatchDir / 'win') / 'resources.rc')
output_path = (PDFiumDir / 'resources.rc')
content = input_path.read_text()
content = content.replace('$VERSION_CSV', str(pdfium_build))
content = content.replace('$VERSION', str(pdfium_build))
output_path... |
class ATON():
def __init__(self, nbrs_num=30, rand_num=30, alpha1=0.8, alpha2=0.2, n_epoch=10, batch_size=64, lr=0.1, n_linear=64, margin=2.0, verbose=True, gpu=True):
self.verbose = verbose
self.x = None
self.y = None
self.ano_idx = None
self.dim = None
self.normal_n... |
def test_set_band_descriptions(tmpdir):
tmptiff = str(tmpdir.join('test.tif'))
with rasterio.open(tmptiff, 'w', count=3, height=256, width=256, **default_gtiff_profile) as dst:
assert (dst.descriptions == (None, None, None))
dst.descriptions = ['this is a test band', 'this is another test band',... |
def dump(outpath: str, norb: int, nelec: int, hijs: np.ndarray, hijkls: np.ndarray, einact: float, ms2: int=0, orbsym: Optional[List[str]]=None, isym: int=1) -> None:
(hij, hij_b) = hijs
(hijkl, hijkl_ba, hijkl_bb) = hijkls
assert (all(((h is None) for h in [hij_b, hijkl_ba, hijkl_bb])) or all(((h is not No... |
def _create_version():
import os
from subprocess import check_output, CalledProcessError, STDOUT
version = 'Unknown'
root = os.path.dirname(os.path.abspath(__file__))
try:
with open(os.path.join(root, 'VERSION.txt'), 'r') as f:
version = f.read().strip()
except IOError as err... |
class OpenChatPopup(QWidget, Ui_OpenChatPopup):
def __init__(self, parent):
super(OpenChatPopup, self).__init__()
self.setupUi(self)
self.parent = parent
QApplication.instance().installEventFilter(self)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
se... |
def plot(pitched_data: PitchedData, output_path: str, transcribed_data: list[TranscribedData]=None, midi_notes: list[str]=None, title: str=None) -> None:
step_size = pitched_data.times[1]
pitched_data = get_pitched_data_with_high_confidence(pitched_data)
if (len(pitched_data.frequencies) < 2):
print... |
class DlibDetector(FaceDetector):
def __init__(self, device, path_to_detector=None, verbose=False):
super().__init__(device, verbose)
print('Warning: this detector is deprecated. Please use a different one, i.e.: S3FD.')
base_path = os.path.join(appdata_dir('face_alignment'), 'data')
... |
def print_and_count_results(test_result: TestResult) -> TestCounts:
counts = TestCounts()
for test_suite in test_result.suites:
if (test_suite.status == TestStatus.SUCCESS):
print_suite_divider((green('[PASSED] ') + test_suite.name))
elif (test_suite.status == TestStatus.SKIPPED):
... |
class DNSName(GeneralName):
def __init__(self, value: str) -> None:
if isinstance(value, str):
try:
value.encode('ascii')
except UnicodeEncodeError:
raise ValueError('DNSName values should be passed as an A-label string. This means unicode characters s... |
def _single_tensor_adagrad(params: List[Tensor], grads: List[Tensor], state_sums: List[Tensor], state_steps: List[Tensor], *, lr: float, weight_decay: float, lr_decay: float, eps: float, maximize: bool) -> None:
for (param, grad, state_sum, step_t) in zip(params, grads, state_sums, state_steps):
if grad.is_... |
def main():
if six.PY2:
stdin = sys.stdin
else:
stdin = sys.stdin.buffer
info = pickle.load(stdin)
data = pickle.load(stdin)
assert isinstance(info, tmva._AdditionalInformationPredict)
assert isinstance(data, pandas.DataFrame)
predictions = tmva_process(info, data)
with o... |
class MultilingualLayerNorm(torch.nn.Module):
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, n_languages=1):
super().__init__()
self.n_languages = n_languages
self.fused = False
if isinstance(normalized_shape, numbers.Integral):
normalized_shape ... |
def ffmpeg_seek_file(file, timestamp):
flags = 0
max_ts = (file.context.contents.duration * AV_TIME_BASE)
result = avformat.avformat_seek_file(file.context, (- 1), 0, timestamp, timestamp, flags)
if (result < 0):
buf = create_string_buffer(128)
avutil.av_strerror(result, buf, 128)
... |
def main():
coverage_report = (ROOT / 'coverage.xml')
root = etree.fromstring(coverage_report.read_text())
raw_package_data = defaultdict((lambda : {'hits': 0, 'misses': 0}))
for package in root.find('packages'):
for module in package.find('classes'):
filename = module.attrib['filena... |
.parametrize('namespace, expected', [('', []), ('unknown', []), ('knownuser', [{'last_updated': 0, 'name': 'somerepo', 'url': ' 'private': True, 'full_name': 'knownuser/somerepo', 'has_admin_permissions': True, 'description': 'some somerepo repo'}]), ('someorg', [{'last_updated': 0, 'name': 'somerepo', 'url': ' 'privat... |
class Generator(object):
def __init__(self, window, path: str, fonts_list: list[Font], formats: list[str], ranges: dict[(str, str)], base64: bool, font_display: (str | None)):
self.window = window
self.stop = False
self.path = path
self.list = fonts_list
self.formats = format... |
class Effect6425(BaseEffect):
type = ('projected', 'active')
def handler(fit, container, context, projectionRange, **kwargs):
if ('projected' not in context):
return
if fit.ship.getModifiedItemAttr('disallowOffensiveModifiers'):
return
appliedBoost = (container.ge... |
def eventlogtime(log='Security', max=100, num=1000, id_list=None, sid=None, string_opt_list=None, startrecord=None, xpath=None, target=None, summary=False, logons=False):
record_list = []
color_list = []
eventcmd = ops.cmd.getDszCommand('eventlogfilter')
eventcmd.log = log
eventcmd.max = max
eve... |
def add_user_as_admin(user_obj, org_obj):
try:
admin_role = TeamRole.get(name='admin')
admin_team = Team.select().where((Team.role == admin_role), (Team.organization == org_obj)).get()
team.add_user_to_team(user_obj, admin_team)
except team.UserAlreadyInTeam:
pass |
class RTC_CR(IntEnum):
COE = (1 << 23)
OSEL = (3 << 21)
POL = (1 << 20)
COSEL = (1 << 19)
BKP = (1 << 18)
SUB1H = (1 << 17)
ADD1H = (1 << 16)
TSIE = (1 << 15)
WUTIE = (1 << 14)
ALRBIE = (1 << 13)
ALRAIE = (1 << 12)
TSE = (1 << 11)
WUTE = (1 << 10)
ALRBE = (1 << 9)... |
def test_fileformattoml_pass_with_path_substitutions(fs):
in_path = './tests/testfiles/testsubst.toml'
fs.create_file(in_path, contents='key1 = "{k1}value !$% *"\n["key2_{k2}"]\nabc = "{k3} def {k4}"\ndef = [\n "l1",\n "l2 {k5}",\n "l3",\n]\nk21 = "value"\n', encoding='utf-8')
context = Context({'k1': 'v... |
def draw_slash(x, y, dx, dy, name=None, style=None):
global orientation
if style:
style_str = ('[%s]' % style)
else:
style_str = ''
if (orientation == 'vertical'):
print(('\\draw%s (%f, %f) -- (%f, %f);' % (style_str, (x - (0.5 * dx)), (y - (0.5 * dy)), (x + (0.5 * dx)), (y + (0.... |
def test_token_network_deposit_race(token_network_proxy, private_keys, token_proxy, web3, contract_manager):
assert (token_network_proxy.settlement_timeout_min() == TEST_SETTLE_TIMEOUT_MIN)
assert (token_network_proxy.settlement_timeout_max() == TEST_SETTLE_TIMEOUT_MAX)
token_network_address = to_canonical_... |
class PollOption(TelegramObject):
__slots__ = ('voter_count', 'text')
def __init__(self, text: str, voter_count: int, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.text: str = text
self.voter_count: int = voter_count
self._id_attrs = (self.... |
def get_int_opt(options, optname, default=None):
string = options.get(optname, default)
try:
return int(string)
except TypeError:
raise OptionError(('Invalid type %r for option %s; you must give an integer value' % (string, optname)))
except ValueError:
raise OptionError(('Invali... |
def test_upload_collection():
records = generate_sparse_fixtures(UPLOAD_NUM_VECTORS)
local_client = init_local()
init_client(local_client, records, sparse_vectors_config=sparse_vectors_config)
remote_client = init_remote()
init_client(remote_client, records, sparse_vectors_config=sparse_vectors_conf... |
def main(argv=None):
op = argparse.ArgumentParser()
op.add_argument('-f', '--from', dest='f')
op.add_argument('-t', '--to', dest='t')
op.add_argument('-l', '--listversions', dest='listversions', action='store_true', default=False, help=_('list the available versions of kickstart syntax'))
opts = op.... |
class Sticker(Object):
def __init__(self, *, client: 'pyrogram.Client'=None, file_id: str, file_unique_id: str, width: int, height: int, is_animated: bool, is_video: bool, file_name: str=None, mime_type: str=None, file_size: int=None, date: datetime=None, emoji: str=None, set_name: str=None, thumbs: List['types.Thu... |
def make_shuffled_prompt(prompt_path: str, seed: int, example_sep: str):
with open(prompt_path, 'r') as f:
prompt = f.read()
random.seed(seed)
prompt_parts = prompt.split(example_sep)
prompt_parts = [p for p in prompt_parts if p.strip()]
print(prompt_parts)
print(f'Found {len(prompt_part... |
def vector_to_amplitudes(cc_or_eom, vec, kshift=0):
expected_vs = vector_size(cc_or_eom, kshift)
if (expected_vs != len(vec)):
raise ValueError('The size of the vector passed {:d} should be exactly {:d}'.format(len(vec), expected_vs))
itr = iter_12(cc_or_eom, kshift)
nocc = cc_or_eom.nocc
nm... |
def smiles2expandfeature(smiles):
if (not is_valid(smiles)):
return None
mol = smiles2mol(smiles)
if (mol is None):
return None
idx_lst = []
clique_lst = [list(x) for x in Chem.GetSymmSSSR(mol)]
for clique in clique_lst:
clique_smiles = Chem.MolFragmentToSmiles(mol, cliqu... |
def main():
global model
if (args.data_test == ['video']):
from videotester import VideoTester
model = model.Model(args, checkpoint)
t = VideoTester(args, model, checkpoint)
t.test()
elif checkpoint.ok:
loader = data.Data(args)
_model = model.Model(args, check... |
def _eval_on_global_object(extend_property):
result = _eval_script_returning_object(extend_property)
if (result == 'undefined'):
return None
if (isinstance(result, dict) and ('isObject' in result) and (result['isObject'] is True)):
kwargs = dict(pymiere_id=result['pymiereId'])
return... |
class Solution(object):
def majorityElement(self, nums):
ls = len(nums)
res = []
check_value = []
for i in range(ls):
if (nums[i] in check_value):
continue
count = 1
for j in range((i + 1), ls):
if (nums[i] == nums[j... |
def get_resnet_v1_d(input_x, scope='resnet50_v1d', bottleneck_nums=[3, 4, 6, 3], base_channels=[64, 128, 256, 512], freeze=[True, False, False, False, False], is_training=True, freeze_norm=False, num_cls=1000, dropout=False):
(net, fet_dict) = get_resnet_v1_d_base(input_x=input_x, scope=scope, bottleneck_nums=bottl... |
class GeneralSchema(Schema):
class Meta():
unknown = RAISE
key = fields.Str(required=True, description='A unique key used to retrieve in registry. For example, given `Lamb` for optimizers, it will check `OptimRegistry` and find the optimizer `apex.optim.FusedLAMB`.')
params = fields.Dict(required=Tr... |
class MoreQuietAction(argparse.Action):
def __init__(self, option_strings: Sequence[str], dest: str, default: object=None, required: bool=False, help: Optional[str]=None) -> None:
super().__init__(option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help)
def __cal... |
def test_track_trackables_typing1():
root = MyRootTrackable()
t1 = MyTrackable()
t2 = MyTrackable2()
t1.foo = t2.foo = 42
root.sub1 = t1
with root.track_usage('format'):
root.sub1.foo
with root.track_usage('!resources'):
root.sub1
root.sub1 = t2
assert (root.pop_chang... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
.parametrize('enable_rest_api', [True])
def test_payload_with_address_invalid_length(api_server_test_instance: APIServer):
invalid_address = '0x61c808d82a3acdadc13c777b59310b'
channel_data_obj = {'partner_address': invalid_a... |
class SimAM(torch.nn.Module):
def __init__(self, channels=None, e_lambda=0.0001):
super(SimAM, self).__init__()
self.activaton = nn.Sigmoid()
self.e_lambda = e_lambda
def __repr__(self):
s = (self.__class__.__name__ + '(')
s += ('lambda=%f)' % self.e_lambda)
retur... |
def make_raiden_service_mock(token_network_registry_address: TokenNetworkRegistryAddress, token_network_address: TokenNetworkAddress, channel_identifier: ChannelID, partner: Address):
raiden_service = MockRaidenService()
chain_state = MockChainState()
wal = Mock()
wal.get_current_state.return_value = ch... |
class SoapClient(object):
def __init__(self, location=None, action=None, namespace=None, cert=None, exceptions=True, proxy=None, ns=None, soap_ns=None, wsdl=None, wsdl_basedir='', cache=False, cacert=None, sessions=False, soap_server=None, timeout=TIMEOUT, trace=False, username=None, password=None, key_file=None, ... |
class Application():
def __init__(self) -> None:
self.__verbosity = (int(os.environ.get('HATCH_VERBOSE', '0')) - int(os.environ.get('HATCH_QUIET', '0')))
def verbosity(self) -> int:
return self.__verbosity
def display(message: str='', **kwargs: Any) -> None:
_display(message)
def... |
def test_extras_require(tmp_path):
project_dir = (tmp_path / 'project')
project_with_a_test.generate(project_dir)
actual_wheels = utils.cibuildwheel_run(project_dir, add_env={'CIBW_TEST_EXTRAS': 'test', 'CIBW_TEST_COMMAND': 'false || pytest {project}/test', 'CIBW_TEST_COMMAND_WINDOWS': 'COLOR 00 || pytest {... |
def get_qr_template(request):
error = 'L'
if ('errorCorrectionLevel' in request.POST):
error = request.POST['errorCorrectionLevel']
urlPrefix = 'HTTPS://MY-QR.ART/R'
if ('customUrlPrefix' in request.POST):
urlPrefix = request.POST['customUrlPrefix'].upper()
template = qrmap.get_qr_ma... |
('/v1/organization/<orgname>/applications/<client_id>/resetclientsecret')
_param('orgname', 'The name of the organization')
_param('client_id', 'The OAuth client ID')
_only
class OrganizationApplicationResetClientSecret(ApiResource):
('resetOrganizationApplicationClientSecret')
def post(self, orgname, client_id... |
def get_minimum_file(file_lst: list) -> str:
if (not file_lst):
return ''
if (len(file_lst) == 1):
return file_lst[0]
res = file_lst[0]
size = os.path.getsize(res)
for f in file_lst[1:]:
_size = os.path.getsize(f)
if (_size < size):
res = f
siz... |
class TestMapDataPipe(expecttest.TestCase):
def test_unzipper_mapdatapipe(self) -> None:
source_dp = SequenceWrapper([(i, (i + 10), (i + 20)) for i in range(10)])
dp1: MapDataPipe
dp2: MapDataPipe
dp3: MapDataPipe
(dp1, dp2, dp3) = UnZipper(source_dp, sequence_length=3)
... |
.parametrize('hamiltonian, time, initial_state, exact_state, order, n_steps, algorithm, result_fidelity', [(diag_coul_hamiltonian, long_time, diag_coul_initial_state, diag_coul_exact_state, 0, 5, None, 0.99), (diag_coul_hamiltonian, long_time, diag_coul_initial_state, diag_coul_exact_state, 0, 12, None, 0.999), (diag_c... |
class RunConfig(_ConfigCommon):
def __init__(self, port: int, host: str, authenticate: t.List[str], password_file: t.Optional[str], disable_fallback: bool, fallback_url: str, health_endpoint: str, server_method: str, overwrite: bool, welcome_msg: str, cache_control: t.Optional[int], log_req_frmt: str, log_res_frmt:... |
def _back_forward(info, go_forward):
history = info.cur_tab.history
current_idx = history.current_idx()
model = completionmodel.CompletionModel(column_widths=(5, 36, 50, 9))
if go_forward:
start = (current_idx + 1)
items = history.forward_items()
else:
start = 0
items... |
(derivate=True, coderize=True)
_loss
def balanced_l1_loss(pred, target, beta=1.0, alpha=0.5, gamma=1.5, reduction='mean'):
assert (beta > 0)
assert ((pred.size() == target.size()) and (target.numel() > 0))
diff = torch.abs((pred - target))
b = ((np.e ** (gamma / alpha)) - 1)
loss = torch.where((diff... |
class YouTubeMetadata():
def __init__(self, metadata: List):
self._raw_metadata: List = metadata
self._metadata = [{}]
for el in metadata:
if (('title' in el) and ('simpleText' in el['title'])):
metadata_title = el['title']['simpleText']
else:
... |
def backup_file(directory, filename):
logger = logging.getLogger(__name__)
logger.trace("Backing up: '%s'", filename)
origfile = os.path.join(directory, filename)
backupfile = (origfile + '.bk')
if os.path.exists(backupfile):
logger.trace("Removing existing file: '%s'", backup_file)
... |
class RETACREDProcessor(Processor):
def __init__(self, args, tokenizer):
super().__init__(args, tokenizer)
self.LABEL_TO_ID = {'no_relation': 0, 'org:founded_by': 1, 'per:identity': 2, 'org:alternate_names': 3, 'per:children': 4, 'per:origin': 5, 'per:countries_of_residence': 6, 'per:employee_of': 7... |
class SlippageModel(with_metaclass(FinancialModelMeta)):
allowed_asset_types = (Equity, Future)
def __init__(self):
self._volume_for_bar = 0
def volume_for_bar(self):
return self._volume_for_bar
def process_order(self, data, order):
raise NotImplementedError('process_order')
... |
.parametrize('p', [1, 2, 3])
def test_compile_to_syc(p):
problem = nx.complete_graph(n=5)
problem = random_plus_minus_1_weights(problem)
qubits = cirq.LineQubit.range(5)
c1 = cirq.Circuit(cirq.H.on_each(qubits), [[ProblemUnitary(problem, gamma=np.random.random()).on(*qubits), DriverUnitary(5, beta=np.ra... |
def main(data_dir, client, bc, config):
benchmark(read_tables, data_dir, bc, dask_profile=config['dask_profile'])
query_distinct = '\n SELECT DISTINCT i_category_id, ws_order_number\n FROM web_sales ws, item i\n WHERE ws.ws_item_sk = i.i_item_sk\n AND i.i_category_id IS NOT NULL\n ... |
def make_optimizer(args, my_model):
trainable = filter((lambda x: x.requires_grad), my_model.parameters())
if (args.type == 'SGD'):
optimizer_function = optim.SGD
kwargs = {'momentum': args.SGD.momentum}
elif (args.type == 'ADAM'):
optimizer_function = optim.Adam
kwargs = {'b... |
def epsilon_greedy(var_Q_circuit, var_Q_bias, epsilon, n_actions, s, train=False):
if (train or (np.random.rand() < ((epsilon / n_actions) + (1 - epsilon)))):
action = torch.argmax(variational_classifier(var_Q_circuit=var_Q_circuit, var_Q_bias=var_Q_bias, angles=decimalToBinaryFixLength(4, s)))
else:
... |
class LakeShore224(Instrument):
input_0 = Instrument.ChannelCreator(LakeShoreTemperatureChannel, 0)
input_A = Instrument.ChannelCreator(LakeShoreTemperatureChannel, 'A')
input_B = Instrument.ChannelCreator(LakeShoreTemperatureChannel, 'B')
input_C1 = Instrument.ChannelCreator(LakeShoreTemperatureChannel... |
class EllipseROI(ROI):
def __init__(self, pos, size, **args):
self.path = None
ROI.__init__(self, pos, size, **args)
self.sigRegionChanged.connect(self._clearPath)
self._addHandles()
def _addHandles(self):
self.addRotateHandle([1.0, 0.5], [0.5, 0.5])
self.addScale... |
def datetime_attributes(draw: DrawFn, total: bool=True, not_required: bool=False) -> Tuple[(datetime, SearchStrategy, SearchStrategy)]:
success_strat = datetimes(min_value=datetime(1970, 1, 1), max_value=datetime(2038, 1, 1)).map((lambda dt: dt.replace(microsecond=0)))
type = datetime
strat = (success_strat... |
def main():
arg = args()
if (not os.path.exists(arg.exp_name)):
os.makedirs(arg.exp_name)
assert (arg.exp_name.split('/')[0] == 'o'), "'o' is the directory of experiment, --exp_name o/..."
output_dir = arg.exp_name
save_scripts_in_exp_dir(output_dir)
logger = logging_set(output_dir)
... |
def anyOf(validator, anyOf, instance, schema):
all_errors = []
for (index, subschema) in enumerate(anyOf):
errs = list(validator.descend(instance, subschema, schema_path=index))
if (not errs):
break
all_errors.extend(errs)
else:
(yield ValidationError(f'{instance!... |
def select_train_data(data, select_num=(- 1)):
new_train = {'text': [], 'label': []}
if (select_num == (- 1)):
return data
else:
new_train['text'] = data['train']['text'][:select_num]
new_train['label'] = data['train']['label'][:select_num]
data['train'] = new_train
retur... |
_lr_scheduler('polynomial_decay', dataclass=PolynomialDecayLRScheduleConfig)
class PolynomialDecayLRSchedule(FairseqLRScheduler):
def __init__(self, cfg: PolynomialDecayLRScheduleConfig, optimizer):
super().__init__(cfg, optimizer)
assert (cfg.total_num_update > 0)
self.lr = cfg.lr[0]
... |
class World(object):
def __init__(self):
self.agents = []
self.landmarks = []
self.dim_c = 2
self.dim_p = 2
self.dim_color = 3
self.length = 960
self.width = 355
self.height = 600
self.net_height = (155 / 2)
self.gravitational_acceratio... |
def train_fun_weak(epoch, model, loss_fn, optimizer, dataloader, dataloader_neg, batch_tnf, use_cuda=True, log_interval=50, triplet=False, tps_grid_regularity_loss=0):
tgrl = TpsGridRegularityLoss(use_cuda=use_cuda)
model.train()
train_loss = 0
if (dataloader_neg is not None):
dataloader_neg_ite... |
class ScaledDotProductAttention(nn.Module):
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
def forward(self, q, k, v, mask=None):
attn = torch.matmul(q, k.transpose(2, 3))
attn =... |
.parametrize('del_s_fact,flag', [(1, GeodIntermediateFlag.NPTS_ROUND), ((4.5 / 5), GeodIntermediateFlag.NPTS_TRUNC), ((5.5 / 5), GeodIntermediateFlag.NPTS_CEIL)])
def test_geodesic_inv_intermediate__del_s__numpy(del_s_fact, flag):
geod = Geod(ellps='clrk66')
point_count = 5
lons = numpy.empty(point_count)
... |
class TheanetsRegressor(TheanetsBase, Regressor):
__doc__ = ('Implements a regression model from the Theanets library. \n' + remove_first_line(TheanetsBase.__doc__))
_model_type = 'regression'
def partial_fit(self, X, y, sample_weight=None, keep_trainer=True, **trainer):
allow_multiple_targets = (Fa... |
def reestimate_bn_stats(sim: QuantizationSimModel, start_op_names: List[str], output_op_names: List[str], dataset: tf.compat.v1.data.Dataset, num_batches: int=DEFAULT_NUM_BATCHES) -> Handle:
(mean_checkpoints, variance_checkpoints, momentum_checkpoints, is_training_checkpoints) = _get_tf_vars_and_orig_values(sim)
... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
.parametrize('enable_rest_api', [True])
def test_shutdown(api_server_test_instance: APIServer):
url = '
response = grequests.post(url).send().response
assert_response_with_code(response, HTTPStatus.OK)
finished = gev... |
def add_namespace(struct: Structure, opts: ScaffoldOpts) -> ActionParams:
if (not opts.get('namespace')):
msg = 'Using the `Namespace` extension with an empty namespace string/None. '
msg += 'You can try a valid string with the `--namespace` option in `putup` '
msg += '(PyScaffold CLI) the a... |
def first_stage():
ql = Qiling(['rootfs/8086/petya/petya.DOS_MBR'], 'rootfs/8086', console=False, verbose=QL_VERBOSE.DEBUG)
ql.add_fs_mapper(128, QlDisk('rootfs/8086/petya/out_1M.raw', 128))
ql.hook_code(stop, begin=petya_2nd_stage_start, end=petya_2nd_stage_start)
ql.run()
return ql |
class Pred():
def __init__(self, id, conf, left, top, right, bottom):
self.id = id
self.conf = conf
self.left = left
self.top = top
self.right = right
self.bottom = bottom
def calc_pred_intersection(self, pred):
if (not (self.id == pred.id)):
r... |
def test_add_with_git_constraint_with_extras(tester: CommandTester, repo: TestRepository) -> None:
repo.add_package(Package('pendulum', '2.0.5'))
repo.add_package(Package('tomlkit', '0.7.0'))
tester.execute('git+
expected = '\nUpdating dependencies\nResolving dependencies...\n\nPackage operations: 3 ins... |
class DebugResolveCommand(InitCommand):
name = 'debug resolve'
description = 'Debugs dependency resolution.'
arguments = [argument('package', 'The packages to resolve.', optional=True, multiple=True)]
options = [option('extras', 'E', 'Extras to activate for the dependency.', flag=False, multiple=True), ... |
def test_pipelined_close() -> None:
c = Connection(SERVER)
c.receive_data(b'GET /1 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n12345GET /2 HTTP/1.1\r\nHost: a.com\r\nContent-Length: 5\r\n\r\n67890')
c.receive_data(b'')
assert (get_all_events(c) == [Request(method='GET', target='/1', headers=[('h... |
class GetMoreInfoWorker(QThread):
infos = pyqtSignal(object)
share_url = pyqtSignal(object)
dl_link = pyqtSignal(object)
msg = pyqtSignal(str, int)
def __init__(self, parent=None):
super(GetMoreInfoWorker, self).__init__(parent)
self._disk = None
self._infos = None
se... |
def get_source_file(filename: str, include_no_ext: bool=False) -> str:
filename = os.path.abspath(_path_from_filename(filename))
(base, orig_ext) = os.path.splitext(filename)
if ((orig_ext == '.pyi') and os.path.exists(f'{base}{orig_ext}')):
return f'{base}{orig_ext}'
for ext in PY_SOURCE_EXTS:
... |
class TestReadmeSample(QiskitAquaTestCase):
def setUp(self):
super().setUp()
try:
from qiskit import Aer
except Exception as ex:
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
def test_readme_sample(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.