content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' Created on Sep 9, 2013 @author: akittredge '''
""" Created on Sep 9, 2013 @author: akittredge """
# import pyperclip class User: ''' the user class ''' user_list = [] def __init__(self, first_name, last_name, number, email, password): self.first_name = first_name self.last_name = last_name self.phone_number = number self.email = email self.password = password def save_user(self): ''' this saves the user into the user_list ''' User.user_list.append(self) def delete_user(self): ''' this deletes the user saved from the user_list ''' User.user_list.remove(self) @classmethod def find_by_first_name(cls, first_name): ''' finds the first name and displays it ''' for user in cls.user_list: if user.first_name == first_name: return user @classmethod def user_exist(cls, first_name): ''' confirms whether the user does exist or not ''' for user in cls.user_list: if user.first_name == first_name: return True else: return False @classmethod def display_users(cls): ''' display the contact list by returning it ''' return cls.user_list # @classmethod # def copy_email(cls, first_name): # user_found = User.find_by_first_name(first_name) # pyperclip.copy(user_found.email)
class User: """ the user class """ user_list = [] def __init__(self, first_name, last_name, number, email, password): self.first_name = first_name self.last_name = last_name self.phone_number = number self.email = email self.password = password def save_user(self): """ this saves the user into the user_list """ User.user_list.append(self) def delete_user(self): """ this deletes the user saved from the user_list """ User.user_list.remove(self) @classmethod def find_by_first_name(cls, first_name): """ finds the first name and displays it """ for user in cls.user_list: if user.first_name == first_name: return user @classmethod def user_exist(cls, first_name): """ confirms whether the user does exist or not """ for user in cls.user_list: if user.first_name == first_name: return True else: return False @classmethod def display_users(cls): """ display the contact list by returning it """ return cls.user_list
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") PROTOBUF_VERSION = "3.6.1.3" SHA = "9510dd2afc29e7245e9e884336f848c8a6600a14ae726adb6befdb4f786f0be2" def generate_protobuf(): http_archive( name = "com_google_protobuf", urls = ["https://github.com/protocolbuffers/protobuf/archive/v%s.zip" % PROTOBUF_VERSION], sha256 = SHA, strip_prefix = "protobuf-" + PROTOBUF_VERSION, )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') protobuf_version = '3.6.1.3' sha = '9510dd2afc29e7245e9e884336f848c8a6600a14ae726adb6befdb4f786f0be2' def generate_protobuf(): http_archive(name='com_google_protobuf', urls=['https://github.com/protocolbuffers/protobuf/archive/v%s.zip' % PROTOBUF_VERSION], sha256=SHA, strip_prefix='protobuf-' + PROTOBUF_VERSION)
# # @lc app=leetcode id=69 lang=python3 # # [69] Sqrt(x) # # @lc code=start class Solution: def mySqrt(self, x: int) -> int: v = 1 result = 0 while True: if v * v > x: result = v - 1 break v = v + 1 return result # @lc code=end
class Solution: def my_sqrt(self, x: int) -> int: v = 1 result = 0 while True: if v * v > x: result = v - 1 break v = v + 1 return result
def morris_pratt_string_matching(t, w, m, n): B = prefix_suffix(w) i = 0 while i <= n - m + 1: j = 0 while j < m and t[i + j + 1] == w[j + 1]: j = j + 1 if j == m: return True i, j = i + j - B[j], max(0, B[j]) return False
def morris_pratt_string_matching(t, w, m, n): b = prefix_suffix(w) i = 0 while i <= n - m + 1: j = 0 while j < m and t[i + j + 1] == w[j + 1]: j = j + 1 if j == m: return True (i, j) = (i + j - B[j], max(0, B[j])) return False
teste = list() teste.append('Pedro') teste.append(15) galera = list() galera.append(teste[:]) teste[0] = 'Ronaldo' teste[1] = '22' galera.append(teste[:]) print(galera)
teste = list() teste.append('Pedro') teste.append(15) galera = list() galera.append(teste[:]) teste[0] = 'Ronaldo' teste[1] = '22' galera.append(teste[:]) print(galera)
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py', '../_base_/swa.py' ] num_stages = 6 num_proposals = 512 model = dict( type='SparseRCNN', pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22k.pth', backbone=dict( type='SwinTransformer', embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., ape=False, drop_path_rate=0.3, patch_norm=True, out_indices=(0, 1, 2, 3), use_checkpoint=True, ), neck=dict( type='PAFPNX', in_channels=[128, 256, 512, 1024], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=4, relu_before_extra_convs=True, pafpn_conv_cfg=dict(type='DCNv2'), norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)), rpn_head=dict( type='EmbeddingRPNHead', num_proposals=num_proposals, proposal_feature_channel=256), roi_head=dict( type='SparseRoIHead', num_stages=num_stages, stage_loss_weights=[1] * num_stages, proposal_feature_channel=256, bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='DIIHead', num_classes=34, num_ffn_fcs=2, num_heads=8, num_cls_fcs=1, num_reg_fcs=3, feedforward_channels=2048, in_channels=256, dropout=0.0, ffn_act_cfg=dict(type='ReLU', inplace=True), dynamic_conv_cfg=dict( type='DynamicConv', in_channels=256, feat_channels=64, out_channels=256, input_feat_shape=7, act_cfg=dict(type='ReLU', inplace=True), norm_cfg=dict(type='LN')), loss_bbox=dict(type='L1Loss', loss_weight=5.0), loss_iou=dict(type='CIoULoss', loss_weight=2.0), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=2.0), bbox_coder=dict( type='DeltaXYWHBBoxCoder', clip_border=False, target_means=[0., 0., 0., 0.], target_stds=[0.5, 0.5, 1., 1.])) for _ in range(num_stages) ]), # training and testing settings train_cfg=dict( rpn=None, rcnn=[ dict( assigner=dict( type='HungarianAssigner', cls_cost=dict(type='FocalLossCost', weight=2.0), reg_cost=dict(type='BBoxL1Cost', weight=5.0), iou_cost=dict(type='IoUCost', iou_mode='giou', weight=2.0)), sampler=dict(type='PseudoSampler'), pos_weight=1) for _ in range(num_stages) ]), test_cfg=dict(rpn=None, rcnn=dict(max_per_img=100))) # data setting dataset_type = 'CocoDataset' data_root = '/content/data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) albu_train_transforms = [ dict(type='ShiftScaleRotate', shift_limit=0.0625, scale_limit=0.0, rotate_limit=0, interpolation=1, p=0.5), dict(type='RandomBrightnessContrast', brightness_limit=[0.1, 0.3], contrast_limit=[0.1, 0.3], p=0.2), dict( type='OneOf', transforms=[ dict( type='RGBShift', r_shift_limit=10, g_shift_limit=10, b_shift_limit=10, p=1.0), dict( type='HueSaturationValue', hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=1.0) ], p=0.1), dict(type='ImageCompression', quality_lower=85, quality_upper=95, p=0.2), dict(type='ChannelShuffle', p=0.1), dict( type='OneOf', transforms=[ dict(type='Blur', blur_limit=3, p=1.0), dict(type='MedianBlur', blur_limit=3, p=1.0) ], p=0.1), ] train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='RandomCrop', crop_type='relative_range', crop_size=(0.9, 0.9), allow_negative_crop = True), dict( type='Resize', img_scale=[(640, 640), (960, 960)], multiscale_mode='range', keep_ratio=True), dict( type='CutOut', n_holes=(5, 10), cutout_shape=[(4, 4), (4, 8), (8, 4), (8, 8), (16, 8), (8, 16), (16, 16), (16, 32), (32, 16), (32, 32), (32, 48), (48, 32), (48, 48)]), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Pad', size_divisor=32), dict( type='Albu', transforms=albu_train_transforms, bbox_params=dict( type='BboxParams', format='pascal_voc', label_fields=['gt_labels'], min_visibility=0.0, filter_lost_elements=True), keymap={ 'img': 'image', 'gt_bboxes': 'bboxes' }, update_pad_shape=False, skip_img_without_anno=True), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=12, workers_per_gpu=4, train=dict(type = dataset_type, ann_file = data_root + '/annotations/instances_train2017.json', img_prefix = 'train_images/', pipeline=train_pipeline), val=dict(type = dataset_type, ann_file = data_root + '/annotations/instances_val2017.json', img_prefix = 'val_images/', pipeline=test_pipeline, samples_per_gpu = 24), test=dict(pipeline=test_pipeline)) # optimizer optimizer = dict(_delete_=True, type='AdamW', lr=0.000025, weight_decay=0.0001, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.), 'relative_position_bias_table': dict(decay_mult=0.), 'norm': dict(decay_mult=0.)})) optimizer_config = dict(_delete_=True, grad_clip=None) log_config = dict(interval = 10) # learning policy lr_config = dict( policy='CosineAnnealing', min_lr_ratio = 0.12, warmup='linear', warmup_iters=500, warmup_ratio=0.1, ) runner = dict(type='IterBasedRunner', max_iters=3000, max_epochs = None) checkpoint_config = dict(interval = 100) evaluation = dict(interval = 100, metric = 'bbox') fp16 = dict(loss_scale=512.) # runtime #load_from = '/gdrive/My Drive/data/sparse_rcnn_r101_fpn_300_proposals_crop_mstrain_480-800_3x_coco_20201223_023452-c23c3564.pth' resume_from = None workflow = [('train', 1)]
_base_ = ['../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py', '../_base_/swa.py'] num_stages = 6 num_proposals = 512 model = dict(type='SparseRCNN', pretrained='https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22k.pth', backbone=dict(type='SwinTransformer', embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, ape=False, drop_path_rate=0.3, patch_norm=True, out_indices=(0, 1, 2, 3), use_checkpoint=True), neck=dict(type='PAFPNX', in_channels=[128, 256, 512, 1024], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=4, relu_before_extra_convs=True, pafpn_conv_cfg=dict(type='DCNv2'), norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)), rpn_head=dict(type='EmbeddingRPNHead', num_proposals=num_proposals, proposal_feature_channel=256), roi_head=dict(type='SparseRoIHead', num_stages=num_stages, stage_loss_weights=[1] * num_stages, proposal_feature_channel=256, bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[dict(type='DIIHead', num_classes=34, num_ffn_fcs=2, num_heads=8, num_cls_fcs=1, num_reg_fcs=3, feedforward_channels=2048, in_channels=256, dropout=0.0, ffn_act_cfg=dict(type='ReLU', inplace=True), dynamic_conv_cfg=dict(type='DynamicConv', in_channels=256, feat_channels=64, out_channels=256, input_feat_shape=7, act_cfg=dict(type='ReLU', inplace=True), norm_cfg=dict(type='LN')), loss_bbox=dict(type='L1Loss', loss_weight=5.0), loss_iou=dict(type='CIoULoss', loss_weight=2.0), loss_cls=dict(type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=2.0), bbox_coder=dict(type='DeltaXYWHBBoxCoder', clip_border=False, target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.5, 0.5, 1.0, 1.0])) for _ in range(num_stages)]), train_cfg=dict(rpn=None, rcnn=[dict(assigner=dict(type='HungarianAssigner', cls_cost=dict(type='FocalLossCost', weight=2.0), reg_cost=dict(type='BBoxL1Cost', weight=5.0), iou_cost=dict(type='IoUCost', iou_mode='giou', weight=2.0)), sampler=dict(type='PseudoSampler'), pos_weight=1) for _ in range(num_stages)]), test_cfg=dict(rpn=None, rcnn=dict(max_per_img=100))) dataset_type = 'CocoDataset' data_root = '/content/data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) albu_train_transforms = [dict(type='ShiftScaleRotate', shift_limit=0.0625, scale_limit=0.0, rotate_limit=0, interpolation=1, p=0.5), dict(type='RandomBrightnessContrast', brightness_limit=[0.1, 0.3], contrast_limit=[0.1, 0.3], p=0.2), dict(type='OneOf', transforms=[dict(type='RGBShift', r_shift_limit=10, g_shift_limit=10, b_shift_limit=10, p=1.0), dict(type='HueSaturationValue', hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=1.0)], p=0.1), dict(type='ImageCompression', quality_lower=85, quality_upper=95, p=0.2), dict(type='ChannelShuffle', p=0.1), dict(type='OneOf', transforms=[dict(type='Blur', blur_limit=3, p=1.0), dict(type='MedianBlur', blur_limit=3, p=1.0)], p=0.1)] train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='RandomCrop', crop_type='relative_range', crop_size=(0.9, 0.9), allow_negative_crop=True), dict(type='Resize', img_scale=[(640, 640), (960, 960)], multiscale_mode='range', keep_ratio=True), dict(type='CutOut', n_holes=(5, 10), cutout_shape=[(4, 4), (4, 8), (8, 4), (8, 8), (16, 8), (8, 16), (16, 16), (16, 32), (32, 16), (32, 32), (32, 48), (48, 32), (48, 48)]), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Pad', size_divisor=32), dict(type='Albu', transforms=albu_train_transforms, bbox_params=dict(type='BboxParams', format='pascal_voc', label_fields=['gt_labels'], min_visibility=0.0, filter_lost_elements=True), keymap={'img': 'image', 'gt_bboxes': 'bboxes'}, update_pad_shape=False, skip_img_without_anno=True), dict(type='Normalize', **img_norm_cfg), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])] test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img'])])] data = dict(samples_per_gpu=12, workers_per_gpu=4, train=dict(type=dataset_type, ann_file=data_root + '/annotations/instances_train2017.json', img_prefix='train_images/', pipeline=train_pipeline), val=dict(type=dataset_type, ann_file=data_root + '/annotations/instances_val2017.json', img_prefix='val_images/', pipeline=test_pipeline, samples_per_gpu=24), test=dict(pipeline=test_pipeline)) optimizer = dict(_delete_=True, type='AdamW', lr=2.5e-05, weight_decay=0.0001, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.0), 'relative_position_bias_table': dict(decay_mult=0.0), 'norm': dict(decay_mult=0.0)})) optimizer_config = dict(_delete_=True, grad_clip=None) log_config = dict(interval=10) lr_config = dict(policy='CosineAnnealing', min_lr_ratio=0.12, warmup='linear', warmup_iters=500, warmup_ratio=0.1) runner = dict(type='IterBasedRunner', max_iters=3000, max_epochs=None) checkpoint_config = dict(interval=100) evaluation = dict(interval=100, metric='bbox') fp16 = dict(loss_scale=512.0) resume_from = None workflow = [('train', 1)]
abi = '''[ { "inputs": [ { "internalType": "int256", "name": "bp", "type": "int256" }, { "internalType": "int256", "name": "sp", "type": "int256" } ], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "partner", "type": "address" }, { "indexed": false, "internalType": "int256", "name": "amountPayed", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "credit", "type": "int256" } ], "name": "contractPay", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "producer", "type": "address" }, { "indexed": false, "internalType": "int256", "name": "offeredEnergy", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "sellPrice", "type": "int256" } ], "name": "enterEvent", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "int256", "name": "dCover", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "dCoverPricePerUnit", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "batteryDelta", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "bLoad", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "bPricePerUnit", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "oDelta", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "oBp", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "oSp", "type": "int256" } ], "name": "generalInfo", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "matched", "type": "address" }, { "indexed": false, "internalType": "int256", "name": "matchedEnergy", "type": "int256" }, { "indexed": false, "internalType": "int256", "name": "creditChange", "type": "int256" } ], "name": "matchEvent", "type": "event" }, { "constant": false, "inputs": [], "name": "coverCredit", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [], "name": "drainContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "enteredEnergy", "type": "int256" }, { "internalType": "int256", "name": "sPrice", "type": "int256" } ], "name": "enterEnergy", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "getBatteryLoad", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getBatteryPricePerUnit", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getBuyPrice", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getContractFunds", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getCredit", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "internalType": "address", "name": "ofAddr", "type": "address" } ], "name": "getMatchBlock", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getSellPrice", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "getSpecCredit", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getTotalBatteryPrice", "outputs": [ { "internalType": "int256", "name": "", "type": "int256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "internalType": "address", "name": "ofAddr", "type": "address" } ], "name": "getUpdateBlock", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "matchOrders", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "repairBlockNumbers", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "newCredit", "type": "int256" } ], "name": "setAllCredits", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "newCap", "type": "int256" } ], "name": "setBatteryCapacity", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int8", "name": "newEff", "type": "int8" } ], "name": "setBatteryEff", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "newLoad", "type": "int256" } ], "name": "setBatteryLoad", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "newPrice", "type": "int256" } ], "name": "setBuyPrice", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "newPrice", "type": "int256" } ], "name": "setSellPrice", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "int256", "name": "nPr", "type": "int256" } ], "name": "setTotalBatPrice", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]'''
abi = '[\n\t{\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "bp",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "sp",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "constructor"\n\t},\n\t{\n\t\t"anonymous": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"indexed": true,\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "partner",\n\t\t\t\t"type": "address"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "amountPayed",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "credit",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "contractPay",\n\t\t"type": "event"\n\t},\n\t{\n\t\t"anonymous": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"indexed": true,\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "producer",\n\t\t\t\t"type": "address"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "offeredEnergy",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "sellPrice",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "enterEvent",\n\t\t"type": "event"\n\t},\n\t{\n\t\t"anonymous": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "dCover",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "dCoverPricePerUnit",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "batteryDelta",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "bLoad",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "bPricePerUnit",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "oDelta",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "oBp",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "oSp",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "generalInfo",\n\t\t"type": "event"\n\t},\n\t{\n\t\t"anonymous": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"indexed": true,\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "matched",\n\t\t\t\t"type": "address"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "matchedEnergy",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"indexed": false,\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "creditChange",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "matchEvent",\n\t\t"type": "event"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [],\n\t\t"name": "coverCredit",\n\t\t"outputs": [],\n\t\t"payable": true,\n\t\t"stateMutability": "payable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [],\n\t\t"name": "drainContract",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "enteredEnergy",\n\t\t\t\t"type": "int256"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "sPrice",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "enterEnergy",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getBatteryLoad",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getBatteryPricePerUnit",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getBuyPrice",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getContractFunds",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "uint256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "uint256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getCredit",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "ofAddr",\n\t\t\t\t"type": "address"\n\t\t\t}\n\t\t],\n\t\t"name": "getMatchBlock",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "uint256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "uint256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getSellPrice",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "account",\n\t\t\t\t"type": "address"\n\t\t\t}\n\t\t],\n\t\t"name": "getSpecCredit",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [],\n\t\t"name": "getTotalBatteryPrice",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": true,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "address",\n\t\t\t\t"name": "ofAddr",\n\t\t\t\t"type": "address"\n\t\t\t}\n\t\t],\n\t\t"name": "getUpdateBlock",\n\t\t"outputs": [\n\t\t\t{\n\t\t\t\t"internalType": "uint256",\n\t\t\t\t"name": "",\n\t\t\t\t"type": "uint256"\n\t\t\t}\n\t\t],\n\t\t"payable": false,\n\t\t"stateMutability": "view",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [],\n\t\t"name": "matchOrders",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [],\n\t\t"name": "repairBlockNumbers",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "newCredit",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setAllCredits",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "newCap",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setBatteryCapacity",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int8",\n\t\t\t\t"name": "newEff",\n\t\t\t\t"type": "int8"\n\t\t\t}\n\t\t],\n\t\t"name": "setBatteryEff",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "newLoad",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setBatteryLoad",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "newPrice",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setBuyPrice",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "newPrice",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setSellPrice",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t},\n\t{\n\t\t"constant": false,\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "int256",\n\t\t\t\t"name": "nPr",\n\t\t\t\t"type": "int256"\n\t\t\t}\n\t\t],\n\t\t"name": "setTotalBatPrice",\n\t\t"outputs": [],\n\t\t"payable": false,\n\t\t"stateMutability": "nonpayable",\n\t\t"type": "function"\n\t}\n]'
class HashEngine: def __init__(self): self.location_hash = None self.location_auth_hash = None self.request_hashes = [] def hash(self, timestamp, latitude, longitude, altitude, authticket, sessiondata, requests): raise NotImplementedError() def get_location_hash(self): return self.location_hash def get_location_auth_hash(self): return self.location_auth_hash def get_request_hashes(self): return self.request_hashes
class Hashengine: def __init__(self): self.location_hash = None self.location_auth_hash = None self.request_hashes = [] def hash(self, timestamp, latitude, longitude, altitude, authticket, sessiondata, requests): raise not_implemented_error() def get_location_hash(self): return self.location_hash def get_location_auth_hash(self): return self.location_auth_hash def get_request_hashes(self): return self.request_hashes
for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) flag = 0 for i in arr: if i < 0: flag = 1 break if flag: print('NO') continue for i in range(max(arr)): if i not in arr: arr.append(i) print('YES') print(len(arr)) print(*arr)
for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) flag = 0 for i in arr: if i < 0: flag = 1 break if flag: print('NO') continue for i in range(max(arr)): if i not in arr: arr.append(i) print('YES') print(len(arr)) print(*arr)
bind = '0.0.0.0:8000' # Assuming one CPU. http://docs.gunicorn.org/en/stable/design.html#how-many-workers # 2 * cores + 1 workers = 3 # You can send signals to it http://docs.gunicorn.org/en/latest/signals.html pidfile = '/run/gunicorn.pid' # Logformat including request time. access_log_format = '%(h)s %({X-Forwarded-For}i)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%(L)s seconds"' # noqa loglevel = 'info' accesslog = '-' # stdout errorlog = '-' # stdout # Also send logs to syslog. syslog = False syslog_prefix = '[asoc_members-wsgi]' timeout = 84000
bind = '0.0.0.0:8000' workers = 3 pidfile = '/run/gunicorn.pid' access_log_format = '%(h)s %({X-Forwarded-For}i)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%(L)s seconds"' loglevel = 'info' accesslog = '-' errorlog = '-' syslog = False syslog_prefix = '[asoc_members-wsgi]' timeout = 84000
class Constants: RESPONSE_CODES_SUCCESS = [200, 201] RESPONSE_CODES_FAILURE = [400, 401, 404, 500] RESPONSE_500 = 500 URL = "https://api.coingecko.com/api/v3/coins/{}?localization=false&tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false" CONTENT_TYPE = "application/json"
class Constants: response_codes_success = [200, 201] response_codes_failure = [400, 401, 404, 500] response_500 = 500 url = 'https://api.coingecko.com/api/v3/coins/{}?localization=false&tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false' content_type = 'application/json'
colddrinks = "pepsi", "cola", "sprite", "7up", 58 num = [89, 38,94,23,98,192] #num.sort() #num.reverse() print(colddrinks[:4]) print(num[:: 2])
colddrinks = ('pepsi', 'cola', 'sprite', '7up', 58) num = [89, 38, 94, 23, 98, 192] print(colddrinks[:4]) print(num[::2])
#Author: Bhumi Patel #The given function will take in an educational website and count the number #of clicks it takes for users to reach privacy policy and end-user license agreement ''' -> With the current pandemic, lives all around the world has been disturbed and changed completely. With change in lifestyle and social behaviour, learning has also been affected. Overnight schools were shutdown, universities need to close their doors and educators, students, and parents needed to figure out ways to keep learning continue, that adaptes to the "new normal." Online learning became popular; however, security and privacy raised a huge concern as kids and learners from all ages started learning online. -> To address this huge we are trying to suggest a potential solution that involves closly examing the educational sites and the amount of data they collect from student learners. All the information that these sites collects makes users vulnerable and affect their online presence and mental health. -> With our solution we want users to have safe experience online and learn more about these educational sites. ''' #analyzing number of clicks required to search for privacy class click: #using a binary tree to store website and privacy links def __init__(self, web_link): self.random_links = [] self.data = web_link #searching for target hit "privacy" def search_target(random_links, w_link): for i in rnadom_links: if i.find("/privacy") != -1: w_link = i return w_link #returns the string with privacy def distance_helper(node, target_link, distance): if node.data == target_link: return distance else: for j in range(len(node.random_links)): distance = distance_helper(node.random_links[i], target_link, distance+1) if distance == -1: return -1 def find_distance(root): return distance_helper(root, target_link, 0) if __name__ == '__main__': #Step:1 load all the web_links in a N-ary tree #Step:2 find the link that contains privacy/policy #Step:3 pass that node in our distance function, to find how many clicks it takes to find privacy policy #populating the list with privacy policies, terms of use agreements links, and other random links #root objects for a N-ary tree known as Educational Websites root_n = click("https://www.khanacademy.org/") root_n.random_links.append(click("https://www.khanacademy.org/about/privacy-policy")) root_n.random_links.append(click("https://www.khanacademy.org/about/tos")) root_n.random_links[0].random_links.append(click("https://www.khanacademy.org/about/%7B%7B%22/about/api-tos%22%7Cpropagate_embedded%7D%7D")) root_n.random_links.append(click("https://www.khanacademy.org/science")) root_n1 = click("https://kahoot.com/") root_n1.random_links.append(click("https://kahoot.com/privacy-policy/")) root_n1.random_links.append(click("https://kahoot.com/study/")) root_n1.random_links[0].random_links.append(click("https://kahoot.com/schools/ways-to-play/")) root_n1.random_links[1].random_links.append(click("https://kahoot.com/home/learning-apps/dragonbox/")) root_n2 = click("https://code.org/") root_n2.random_links.append(click("https://studio.code.org/projects/public")) root_n2.random_links.append(click("https://code.org/about")) root_n2.random_links.append(click("https://code.org/promote")) root_n2.random_links.append(click("https://code.org/tos")) root_n3 = click("https://www.udemy.com/") root_n3.random_links.append(click("https://about.udemy.com/careers/?locale=en-us")) root_n3.random_links[0].random_links.append(click("https://about.udemy.com/tag/stories/")) root_n3.random_links[0].random_links[0].random_links.append(click("https://www.udemy.com/terms/copyright/")) root_n3.random_links.append(click("https://www.udemy.com/terms/privacy/")) #displays the number of clicks print("The number of click is" , find_distance(root_n))
""" -> With the current pandemic, lives all around the world has been disturbed and changed completely. With change in lifestyle and social behaviour, learning has also been affected. Overnight schools were shutdown, universities need to close their doors and educators, students, and parents needed to figure out ways to keep learning continue, that adaptes to the "new normal." Online learning became popular; however, security and privacy raised a huge concern as kids and learners from all ages started learning online. -> To address this huge we are trying to suggest a potential solution that involves closly examing the educational sites and the amount of data they collect from student learners. All the information that these sites collects makes users vulnerable and affect their online presence and mental health. -> With our solution we want users to have safe experience online and learn more about these educational sites. """ class Click: def __init__(self, web_link): self.random_links = [] self.data = web_link def search_target(random_links, w_link): for i in rnadom_links: if i.find('/privacy') != -1: w_link = i return w_link def distance_helper(node, target_link, distance): if node.data == target_link: return distance else: for j in range(len(node.random_links)): distance = distance_helper(node.random_links[i], target_link, distance + 1) if distance == -1: return -1 def find_distance(root): return distance_helper(root, target_link, 0) if __name__ == '__main__': root_n = click('https://www.khanacademy.org/') root_n.random_links.append(click('https://www.khanacademy.org/about/privacy-policy')) root_n.random_links.append(click('https://www.khanacademy.org/about/tos')) root_n.random_links[0].random_links.append(click('https://www.khanacademy.org/about/%7B%7B%22/about/api-tos%22%7Cpropagate_embedded%7D%7D')) root_n.random_links.append(click('https://www.khanacademy.org/science')) root_n1 = click('https://kahoot.com/') root_n1.random_links.append(click('https://kahoot.com/privacy-policy/')) root_n1.random_links.append(click('https://kahoot.com/study/')) root_n1.random_links[0].random_links.append(click('https://kahoot.com/schools/ways-to-play/')) root_n1.random_links[1].random_links.append(click('https://kahoot.com/home/learning-apps/dragonbox/')) root_n2 = click('https://code.org/') root_n2.random_links.append(click('https://studio.code.org/projects/public')) root_n2.random_links.append(click('https://code.org/about')) root_n2.random_links.append(click('https://code.org/promote')) root_n2.random_links.append(click('https://code.org/tos')) root_n3 = click('https://www.udemy.com/') root_n3.random_links.append(click('https://about.udemy.com/careers/?locale=en-us')) root_n3.random_links[0].random_links.append(click('https://about.udemy.com/tag/stories/')) root_n3.random_links[0].random_links[0].random_links.append(click('https://www.udemy.com/terms/copyright/')) root_n3.random_links.append(click('https://www.udemy.com/terms/privacy/')) print('The number of click is', find_distance(root_n))
# Complete the function below. def main(): conn = sqlite3.connect('SAMPLE.db') cursor = conn.cursor() cursor.execute("drop table if exists ITEMS") sql_statement = '''CREATE TABLE ITEMS (item_id integer not null, item_name varchar(300), item_description text, item_category text, quantity_in_stock integer)''' cursor.execute(sql_statement) items = [(101, 'Nik D300', 'Nik D300', 'DSLR Camera', 3), (102, 'Can 1300', 'Can 1300', 'DSLR Camera', 5), (103, 'gPhone 13S', 'gPhone 13S', 'Mobile', 10), (104, 'Mic canvas', 'Mic canvas', 'Tab', 5), (105, 'SnDisk 10T', 'SnDisk 10T', 'Hard Drive', 1) ] #Add code to insert records to ITEM table for item in items: cursor.execute('insert into ITEMS values (?,?,?,?,?)', item) try: cursor.execute("select * from ITEMS") except: return 'Unable to perform the transaction.' rowout=[] for row in cursor.fetchall(): rowout.append(row) return rowout conn.close() '''For testing the code, no input is required'''
def main(): conn = sqlite3.connect('SAMPLE.db') cursor = conn.cursor() cursor.execute('drop table if exists ITEMS') sql_statement = 'CREATE TABLE ITEMS\n (item_id integer not null, item_name varchar(300), \n item_description text, item_category text, \n quantity_in_stock integer)' cursor.execute(sql_statement) items = [(101, 'Nik D300', 'Nik D300', 'DSLR Camera', 3), (102, 'Can 1300', 'Can 1300', 'DSLR Camera', 5), (103, 'gPhone 13S', 'gPhone 13S', 'Mobile', 10), (104, 'Mic canvas', 'Mic canvas', 'Tab', 5), (105, 'SnDisk 10T', 'SnDisk 10T', 'Hard Drive', 1)] for item in items: cursor.execute('insert into ITEMS values (?,?,?,?,?)', item) try: cursor.execute('select * from ITEMS') except: return 'Unable to perform the transaction.' rowout = [] for row in cursor.fetchall(): rowout.append(row) return rowout conn.close() 'For testing the code, no input is required'
class LearnedEquivalence: def __init__(self, eq_class): self.equivalence_class = eq_class def __str__(self): return "LEARNED_EQCLASS_" + self.equivalence_class
class Learnedequivalence: def __init__(self, eq_class): self.equivalence_class = eq_class def __str__(self): return 'LEARNED_EQCLASS_' + self.equivalence_class
# data is [ 0 name of game, # 1 path to game saves, # 2 backups directory] ''' self.game.name self.game.saveLocation self.game.backupLocation ''' class gameInfo: def __init__( self, name, saveLocation, backupLocation ): self.name = name self.saveLocation = saveLocation self.backupLocation = backupLocation
""" self.game.name self.game.saveLocation self.game.backupLocation """ class Gameinfo: def __init__(self, name, saveLocation, backupLocation): self.name = name self.saveLocation = saveLocation self.backupLocation = backupLocation
class Field(): def __init__(self, dictionary = {}): self.name = dictionary.get("name") self.rname = dictionary.get("rname") self.domain = dictionary.get("domain") self.description = dictionary.get("description") # Props self.input = dictionary.get("input", False) self.edit = dictionary.get("edit", False) self.show_in_grid = dictionary.get("show_in_grid", False) self.show_in_details = dictionary.get("show_in_details", False) self.is_mean = dictionary.get("is_mean", False) self.autocalculated = dictionary.get("autocalculated", False) self.required = dictionary.get("required", False)
class Field: def __init__(self, dictionary={}): self.name = dictionary.get('name') self.rname = dictionary.get('rname') self.domain = dictionary.get('domain') self.description = dictionary.get('description') self.input = dictionary.get('input', False) self.edit = dictionary.get('edit', False) self.show_in_grid = dictionary.get('show_in_grid', False) self.show_in_details = dictionary.get('show_in_details', False) self.is_mean = dictionary.get('is_mean', False) self.autocalculated = dictionary.get('autocalculated', False) self.required = dictionary.get('required', False)
# QuickSort def quicksort(L,l,r): #If list has only one element, return the list as is if(r-l <=1): return L # Set pivot as the very first position in the list, upper and lower are the next element (pivot,lower,upper) = (L[l],l+1,l+1) # Loop from the item after pivot to the end for i in range(l+1,r): #If L[i] is higher than pivot, upper is incremented if L[i] > pivot: upper +=1 else: # exchange L[i] with start of upper segment (L[i],L[lower]) = (L[lower],L[i]) upper +=1 lower +=1 #Move pivot to the center of the list (L[l],L[lower-1]) = (L[lower-1],L[l]) lower -=1 #Recursively sort the LHS and RHS of pivot now quicksort(L,l,lower) quicksort(L,lower+1,upper) #Return the list return L A = [4,5,6,2,3,7,8,9] print(quicksort(A,0,len(A)))
def quicksort(L, l, r): if r - l <= 1: return L (pivot, lower, upper) = (L[l], l + 1, l + 1) for i in range(l + 1, r): if L[i] > pivot: upper += 1 else: (L[i], L[lower]) = (L[lower], L[i]) upper += 1 lower += 1 (L[l], L[lower - 1]) = (L[lower - 1], L[l]) lower -= 1 quicksort(L, l, lower) quicksort(L, lower + 1, upper) return L a = [4, 5, 6, 2, 3, 7, 8, 9] print(quicksort(A, 0, len(A)))
# import pytest class TestMessageFolder: def test_folders(self): # synced assert True def test_messages(self): # synced assert True def test_order_messages_by_date(): # synced assert True class TestAttributes: class TestChildFolderCount: pass class TestTotalItemCount: pass class TestUnreadItemCount: pass class TestName: pass class TestChildFolders: pass class TestMessages: pass class TestBulkMessageFolderAction: def test_move(self): # synced assert True def test_delete(self): # synced assert True def test_copy(self): # synced assert True class TestMessageFolderQuery: def test___getitem__(self): # synced assert True def test_execute(self): # synced assert True def test_bulk(self): # synced assert True
class Testmessagefolder: def test_folders(self): assert True def test_messages(self): assert True def test_order_messages_by_date(): assert True class Testattributes: class Testchildfoldercount: pass class Testtotalitemcount: pass class Testunreaditemcount: pass class Testname: pass class Testchildfolders: pass class Testmessages: pass class Testbulkmessagefolderaction: def test_move(self): assert True def test_delete(self): assert True def test_copy(self): assert True class Testmessagefolderquery: def test___getitem__(self): assert True def test_execute(self): assert True def test_bulk(self): assert True
def character_xor(input_string, char): output_string = "" for c in input_string: output_string += chr(ord(c)^char) return output_string def calculate_score(input_string): frequencies = { 'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253, 'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094, 'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025, 'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929, 'q': .00095, 'r': .05987, 's': .06327, 't': .09056, 'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150, 'y': .01974, 'z': .00074, ' ': .13000 } #frequencies taken from wikipedia (https://en.wikipedia.org/wiki/Letter_frequency) calculated_sum = 0 for c in input_string: if c in frequencies: calculated_sum += frequencies[c] return calculated_sum def main(): hex_string = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' decoded_string = bytearray.fromhex(hex_string).decode() all_character_xors = [] for i in range(256): char_xor = character_xor(decoded_string, i) all_character_xors.append([calculate_score(char_xor.lower()), char_xor]) all_character_xors.sort() print(all_character_xors[-1][1]) if __name__ == '__main__': main()
def character_xor(input_string, char): output_string = '' for c in input_string: output_string += chr(ord(c) ^ char) return output_string def calculate_score(input_string): frequencies = {'a': 0.08167, 'b': 0.01492, 'c': 0.02782, 'd': 0.04253, 'e': 0.12702, 'f': 0.02228, 'g': 0.02015, 'h': 0.06094, 'i': 0.06094, 'j': 0.00153, 'k': 0.00772, 'l': 0.04025, 'm': 0.02406, 'n': 0.06749, 'o': 0.07507, 'p': 0.01929, 'q': 0.00095, 'r': 0.05987, 's': 0.06327, 't': 0.09056, 'u': 0.02758, 'v': 0.00978, 'w': 0.0236, 'x': 0.0015, 'y': 0.01974, 'z': 0.00074, ' ': 0.13} calculated_sum = 0 for c in input_string: if c in frequencies: calculated_sum += frequencies[c] return calculated_sum def main(): hex_string = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' decoded_string = bytearray.fromhex(hex_string).decode() all_character_xors = [] for i in range(256): char_xor = character_xor(decoded_string, i) all_character_xors.append([calculate_score(char_xor.lower()), char_xor]) all_character_xors.sort() print(all_character_xors[-1][1]) if __name__ == '__main__': main()
_base_ = './cifar10split_bs16.py' data = dict( unlabeled=dict( type='TVDatasetSplit', base='CIFAR10', train=True, data_prefix='data/torchvision/cifar10', num_images=1000, download=True ) )
_base_ = './cifar10split_bs16.py' data = dict(unlabeled=dict(type='TVDatasetSplit', base='CIFAR10', train=True, data_prefix='data/torchvision/cifar10', num_images=1000, download=True))
def runModels(sproc,modelList,testPredictionPaths,CVPredictionPaths,trials,RMSEPaths,useRMSE): subprocesses = [] for trial in range(0,trials): # Setup utility arrays testPredictionPaths.append([]) CVPredictionPaths.append([]) for model in modelList: print("Running Model " + model.tag) model.run(sproc,subprocesses) testPredictionPaths[int(model.trial)].append(model.predTest) CVPredictionPaths[int(model.trial)].append(model.predCV) if useRMSE: RMSEPaths.append(model.RMSEPath) for p in subprocesses: p.wait() def fixRun(mproc,modelList): processes = [] for model in modelList: p = mproc.Process(target=model.fixRun) p.start() processes.append(p) for p in processes: p.join()
def run_models(sproc, modelList, testPredictionPaths, CVPredictionPaths, trials, RMSEPaths, useRMSE): subprocesses = [] for trial in range(0, trials): testPredictionPaths.append([]) CVPredictionPaths.append([]) for model in modelList: print('Running Model ' + model.tag) model.run(sproc, subprocesses) testPredictionPaths[int(model.trial)].append(model.predTest) CVPredictionPaths[int(model.trial)].append(model.predCV) if useRMSE: RMSEPaths.append(model.RMSEPath) for p in subprocesses: p.wait() def fix_run(mproc, modelList): processes = [] for model in modelList: p = mproc.Process(target=model.fixRun) p.start() processes.append(p) for p in processes: p.join()
def faculty_evaluation_result(nev, rar, som, oft, voft, alw): ''' Write code to calculate faculty evaluation rating according to assignment instructions :param nev: Never :param rar: Rarely :param som: Sometimes :param oft: Often :param voft: Very Often :param alw: Always :return: rating as a string ''' #Find the ratios of each parameter total = nev + rar + som + oft + voft + alw nev_ratio = (nev / total) rar_ratio = (rar / total) som_ratio = (som / total) oft_ratio = (oft / total) voft_ratio = (voft / total) alw_ratio = (alw / total) if alw_ratio + voft_ratio >= 90: return 'Excellent' elif alw_ratio + voft_ratio + oft_ratio >= 80: return 'Very Good' elif alw_ratio + voft_ratio + oft_ratio + som_ratio >= 70: return 'Good' elif alw_ratio + voft_ratio + oft_ratio + som_ratio + rar_ratio >= 60: return 'Needs Improvment' else: return 'Unacceptable' def get_ratings(nev,rar,som, oft,voft, alw): ''' Students aren't expected to know this material yet! ''' ratings = [] total = nev + rar + som + oft + voft + alw ratings.append(round(alw / total, 2)) ratings.append(round(voft / total, 2)) ratings.append(round(oft / total, 2)) ratings.append(round(som / total, 2)) ratings.append(round(rar / total, 2)) ratings.append(round(nev / total, 2)) return ratings
def faculty_evaluation_result(nev, rar, som, oft, voft, alw): """ Write code to calculate faculty evaluation rating according to assignment instructions :param nev: Never :param rar: Rarely :param som: Sometimes :param oft: Often :param voft: Very Often :param alw: Always :return: rating as a string """ total = nev + rar + som + oft + voft + alw nev_ratio = nev / total rar_ratio = rar / total som_ratio = som / total oft_ratio = oft / total voft_ratio = voft / total alw_ratio = alw / total if alw_ratio + voft_ratio >= 90: return 'Excellent' elif alw_ratio + voft_ratio + oft_ratio >= 80: return 'Very Good' elif alw_ratio + voft_ratio + oft_ratio + som_ratio >= 70: return 'Good' elif alw_ratio + voft_ratio + oft_ratio + som_ratio + rar_ratio >= 60: return 'Needs Improvment' else: return 'Unacceptable' def get_ratings(nev, rar, som, oft, voft, alw): """ Students aren't expected to know this material yet! """ ratings = [] total = nev + rar + som + oft + voft + alw ratings.append(round(alw / total, 2)) ratings.append(round(voft / total, 2)) ratings.append(round(oft / total, 2)) ratings.append(round(som / total, 2)) ratings.append(round(rar / total, 2)) ratings.append(round(nev / total, 2)) return ratings
# Variables which should not be accessed outside a class are called private variables. # In Python you can easily create private variables by prefixing it with a double underscore ( __ ) # Whenever you create a private variable, python internally changes its name as _ClassName__variableName. # For example, here __salary is actually internally stored as _Trainer__salary. # Methods used to set values are called as 'mutator' methods and methods used to get values are called as 'accessor' methods! class Trainer: def __init__(self): self.name=None self.__salary=1000 def set_salary(self,salary): self.__salary=salary def get_salary(self): return self.__salary lion_trainer=Trainer() lion_trainer.name="Mark" # You can set a private variable using obj._Trainer__salary. Ex: lion_trainer._Trainer__salary = 2000 # But this is not a right way, the correct way is to use mutator methods. lion_trainer.set_salary(2000) print("Lion's trainer is", lion_trainer.name) # You can also access the private variable using obj._Trainer__salary. Ex: print("Salary of Trainer" , lion_trainer._Trainer__salary) # But this is not a right way, the correct way is to use accessor methods. print("His salary is Rs.", lion_trainer.get_salary())
class Trainer: def __init__(self): self.name = None self.__salary = 1000 def set_salary(self, salary): self.__salary = salary def get_salary(self): return self.__salary lion_trainer = trainer() lion_trainer.name = 'Mark' lion_trainer.set_salary(2000) print("Lion's trainer is", lion_trainer.name) print('His salary is Rs.', lion_trainer.get_salary())
class Solution: def connect(self, root: 'Node') -> 'Node': node = root while node: next_level = node.left while node and node.left: node.left.next = node.right node.right.next = node.next and node.next.left node = node.next node = next_level return root
class Solution: def connect(self, root: 'Node') -> 'Node': node = root while node: next_level = node.left while node and node.left: node.left.next = node.right node.right.next = node.next and node.next.left node = node.next node = next_level return root
UNUSED_PRETRAINED_LAYERS = ['"fc_1.weight", ' '"fc_1.bias", ' '"fc_2.weight", ' '"fc_2.bias", ' '"fc_3.weight", ' '"fc_3.bias", ' '"fc_4.weight", ' '"fc_4.bias", ' '"bn_1.weight", ' '"bn_1.bias", ' '"bn_1.running_mean", ' '"bn_1.running_var", ' '"bn_1.num_batches_tracked", ' '"bn_2.weight", "bn_2.bias", ' '"bn_2.running_mean", ' '"bn_2.running_var", ' '"bn_2.num_batches_tracked", ' '"bn_3.weight", "bn_3.bias", ' '"bn_3.running_mean", ' '"bn_3.running_var", ' '"bn_3.num_batches_tracked", ' '"bn_4.weight", ' '"bn_4.bias", ' '"bn_4.running_mean", ' '"bn_4.running_var", ' '"bn_4.num_batches_tracked"']
unused_pretrained_layers = ['"fc_1.weight", "fc_1.bias", "fc_2.weight", "fc_2.bias", "fc_3.weight", "fc_3.bias", "fc_4.weight", "fc_4.bias", "bn_1.weight", "bn_1.bias", "bn_1.running_mean", "bn_1.running_var", "bn_1.num_batches_tracked", "bn_2.weight", "bn_2.bias", "bn_2.running_mean", "bn_2.running_var", "bn_2.num_batches_tracked", "bn_3.weight", "bn_3.bias", "bn_3.running_mean", "bn_3.running_var", "bn_3.num_batches_tracked", "bn_4.weight", "bn_4.bias", "bn_4.running_mean", "bn_4.running_var", "bn_4.num_batches_tracked"']
class Observer(object): def __init__(self, **kwargs): self._listeners = [] def add_listener(self, listener): self._listeners.append(listener) def _call_event(self, msg): for listener in self._listeners: listener(msg)
class Observer(object): def __init__(self, **kwargs): self._listeners = [] def add_listener(self, listener): self._listeners.append(listener) def _call_event(self, msg): for listener in self._listeners: listener(msg)
def mergeSort(arrInput): if len(arrInput) > 1: mid = len(arrInput) // 2 # midpoint of input array left = arrInput[:mid] # Dividing the left side of elements right = arrInput[mid:] # Divide into second half mergeSort(left) # Sorting first half mergeSort(right) # Sorting second half i = 0 j = 0 k = 0 # Copy data to temp arrInput left[] and right[] while i < len(left) and j < len(right): if left[i] < right[j]: arrInput[k] = left[i] i += 1 else: arrInput[k] = right[j] j += 1 k += 1 # Checking if any element was left while i < len(left): arrInput[k] = left[i] i += 1 k += 1 while j < len(right): arrInput[k] = right[j] j += 1 k += 1
def merge_sort(arrInput): if len(arrInput) > 1: mid = len(arrInput) // 2 left = arrInput[:mid] right = arrInput[mid:] merge_sort(left) merge_sort(right) i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arrInput[k] = left[i] i += 1 else: arrInput[k] = right[j] j += 1 k += 1 while i < len(left): arrInput[k] = left[i] i += 1 k += 1 while j < len(right): arrInput[k] = right[j] j += 1 k += 1
# !/usr/bin/env python3 class Classification: def __init__(self): self.description = '' self.direct_parent = '' self.kingdom = '' self.superclass = '' self.class_type ='' self.subclass = '' def __init__(self, description, direct_parent, kingdom, superclass, class_type, subclass): self.description = description self.direct_parent = direct_parent self.kingdom = kingdom self.superclass = superclass self.class_type = class_type self.subclass = subclass def printout(self): print ('Classification: ') print ('\t> Description: ' + self.description) print ('\t> Direct parent: ' + self.direct_parent) print ('\t> Kingdom: ' + self.kingdom) print ('\t> Superclass: ' + self.superclass) print ('\t> Class: ' + self.class_type) print ('\t> Subclass: ' + self.subclass) ## Example of how the information realted to 'Classification' appears in DrugBank database. # <classification> # <description/> # <direct-parent>Peptides</direct-parent> # <kingdom>Organic Compounds</kingdom> # <superclass>Organic Acids</superclass> # <class>Carboxylic Acids and Derivatives</class> # <subclass>Amino Acids, Peptides, and Analogues</subclass> # </classification>
class Classification: def __init__(self): self.description = '' self.direct_parent = '' self.kingdom = '' self.superclass = '' self.class_type = '' self.subclass = '' def __init__(self, description, direct_parent, kingdom, superclass, class_type, subclass): self.description = description self.direct_parent = direct_parent self.kingdom = kingdom self.superclass = superclass self.class_type = class_type self.subclass = subclass def printout(self): print('Classification: ') print('\t> Description: ' + self.description) print('\t> Direct parent: ' + self.direct_parent) print('\t> Kingdom: ' + self.kingdom) print('\t> Superclass: ' + self.superclass) print('\t> Class: ' + self.class_type) print('\t> Subclass: ' + self.subclass)
# INDEX MULTIPLIER EDABIT SOLUTION: def index_multiplier(lst): # creating a variable to store the sum. summ = 0 # creating a for-loop using 'enumerate' to access the index and the value. for idx, num in enumerate(nums): # code to add the product of the index and value to the sum variable. summ += (idx * num) # returning the value of the sum. return summ
def index_multiplier(lst): summ = 0 for (idx, num) in enumerate(nums): summ += idx * num return summ
#!/usr/bin/env python # * coding: utf8 * ''' api.py A module that holds the api credentials to get the offender data ''' AUTHORIZATION_HEADER = {'Authorization': 'Apikey 0000'} ENDPOINT_AT = 'qa url' ENDPOINT = 'production url'
""" api.py A module that holds the api credentials to get the offender data """ authorization_header = {'Authorization': 'Apikey 0000'} endpoint_at = 'qa url' endpoint = 'production url'
# first input = "racecar" input2 = "nada" def palindromo_checker(input): print(input) return input == input[::-1] if __name__ == '__main__': print(palindromo_checker(input)) print(palindromo_checker(input2))
input = 'racecar' input2 = 'nada' def palindromo_checker(input): print(input) return input == input[::-1] if __name__ == '__main__': print(palindromo_checker(input)) print(palindromo_checker(input2))
def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + b if __name__ == '__main__': f = fibonacci() for _ in range(10): print(next(f))
def fibonacci(): (a, b) = (0, 1) while True: yield b (a, b) = (b, a + b) if __name__ == '__main__': f = fibonacci() for _ in range(10): print(next(f))
def calculate(): operation = input(''' Please Type the math operation you would like to complete: + for addition - for Subtraction * for Multiplication / for division ''') number_1 = float(input('Please enter the First number: ')) number_2 = float(input('Please enter the Second number: ')) if operation == '+': print('{} + {} = '.format(number_1, number_2)) print(number_1 + number_2) elif operation == '-': print('{} - {} = '.format(number_1, number_2)) print(number_1 - number_2) elif operation == '*': print('{} * {} = '.format(number_1, number_2)) print(number_1 * number_2) elif operation == '/': print('{} / {} = '.format(number_1, number_2)) print(number_1 / number_2) else: print('You have entered a wrong math operator!') again() def again(): calculation_again = input(''' Do you want to Calculate again? Please type Y for Yes or N for No ''') if calculation_again.upper() == 'Y': calculate() elif calculation_again.upper() == 'N': print('Bye Bye, thank you for coming.') else: again() calculate()
def calculate(): operation = input('\nPlease Type the math operation you would like to complete:\n+ for addition\n- for Subtraction\n* for Multiplication\n/ for division\n') number_1 = float(input('Please enter the First number: ')) number_2 = float(input('Please enter the Second number: ')) if operation == '+': print('{} + {} = '.format(number_1, number_2)) print(number_1 + number_2) elif operation == '-': print('{} - {} = '.format(number_1, number_2)) print(number_1 - number_2) elif operation == '*': print('{} * {} = '.format(number_1, number_2)) print(number_1 * number_2) elif operation == '/': print('{} / {} = '.format(number_1, number_2)) print(number_1 / number_2) else: print('You have entered a wrong math operator!') again() def again(): calculation_again = input('\nDo you want to Calculate again?\nPlease type Y for Yes or N for No\n') if calculation_again.upper() == 'Y': calculate() elif calculation_again.upper() == 'N': print('Bye Bye, thank you for coming.') else: again() calculate()
for x in range(5, 0, -1): for y in range(x, 5): print(" ", end="") for z in range(0, x): print("* ", end="") print()
for x in range(5, 0, -1): for y in range(x, 5): print(' ', end='') for z in range(0, x): print('* ', end='') print()
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: length = sys.maxsize result = None letters = collections.defaultdict() for letter in licensePlate: if letter.isalpha(): letter = letter.lower() letters[letter] = letters.get(letter, 0 ) + 1 for word in words: cur = collections.Counter(word) valid = True for letter in letters: if letter not in cur or cur[letter] < letters[letter]: valid = False break if valid and len(word) < length: result = word length = len(word) return result
class Solution: def shortest_completing_word(self, licensePlate: str, words: List[str]) -> str: length = sys.maxsize result = None letters = collections.defaultdict() for letter in licensePlate: if letter.isalpha(): letter = letter.lower() letters[letter] = letters.get(letter, 0) + 1 for word in words: cur = collections.Counter(word) valid = True for letter in letters: if letter not in cur or cur[letter] < letters[letter]: valid = False break if valid and len(word) < length: result = word length = len(word) return result
originallist=[[1,'a',['cat'],2],[[[3]],'dog'],4,5] newlist=[] def flattenlist(x): for i in x: if type(i) == list: flattenlist(i) else: newlist.append(i) return newlist print(flattenlist(originallist)) list1=[[1, 2], [3, 4], [5, 6, 7]] list2=[] def reverselist(y): for i in sorted(y,reverse=True): list2.append(sorted(i, reverse=True)) return print(list2) reverselist(list1)
originallist = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5] newlist = [] def flattenlist(x): for i in x: if type(i) == list: flattenlist(i) else: newlist.append(i) return newlist print(flattenlist(originallist)) list1 = [[1, 2], [3, 4], [5, 6, 7]] list2 = [] def reverselist(y): for i in sorted(y, reverse=True): list2.append(sorted(i, reverse=True)) return print(list2) reverselist(list1)
#file : InMoov3.minimalArm.py # this will run with versions of MRL above 1695 # a very minimal script for InMoov # although this script is very short you can still # do voice control of a right Arm # It uses WebkitSpeechRecognition, so you need to use Chrome as your default browser for this script to work # Start the webgui service without starting the browser webgui = Runtime.create("WebGui","WebGui") webgui.autoStartBrowser(False) webgui.startService() # Then start the browsers and show the WebkitSpeechRecognition service named i01.ear webgui.startBrowser("http://localhost:8888/#/service/i01.ear") # As an alternative you can use the line below to show all services in the browser. In that case you should comment out all lines above that starts with webgui. # webgui = Runtime.createAndStart("webgui","WebGui") leftPort = "COM13" #modify port according to your board rightPort = "COM17" #modify port according to your board #to tweak the default voice Voice="cmu-slt-hsmm" # Default female for MarySpeech #Voice="cmu-bdl" #Male US voice.You need to add the necessary file.jar to myrobotlab.1.0.XXXX/library/jar #https://github.com/MyRobotLab/pyrobotlab/blob/ff6e2cef4d0642e47ee15e353ef934ac6701e713/home/hairygael/voice-cmu-bdl-5.2.jar voiceType = Voice mouth = Runtime.createAndStart("i01.mouth", "MarySpeech") mouth.setVoice(voiceType) ############## # starting parts i01 = Runtime.createAndStart("i01", "InMoov") i01.startEar() i01.startMouth() ############## i01.startLeftArm(leftPort) #tweak defaults LeftArm #i01.leftArm.bicep.setMinMax(0,90) #i01.leftArm.rotate.setMinMax(46,160) #i01.leftArm.shoulder.setMinMax(30,100) #i01.leftArm.omoplate.setMinMax(10,75) ################# i01.startRightArm(rightPort) # tweak default RightArm #i01.rightArm.bicep.setMinMax(0,90) #i01.rightArm.rotate.setMinMax(46,160) #i01.rightArm.shoulder.setMinMax(30,100) #i01.rightArm.omoplate.setMinMax(10,75) ################# # verbal commands ear = i01.ear ear.addCommand("attach everything", "i01", "attach") ear.addCommand("disconnect everything", "i01", "detach") ear.addCommand("attach left arm", "i01.leftArm", "attach") ear.addCommand("disconnect left arm", "i01.leftArm", "detach") ear.addCommand("attach right arm", "i01.rightArm", "attach") ear.addCommand("disconnect right arm", "i01.rightArm", "detach") ear.addCommand("rest", "python", "rest") ear.addCommand("arms front", i01.getName(), "armsFront") ear.addCommand("da vinci", i01.getName(), "daVinci") ear.addCommand("capture gesture", ear.getName(), "captureGesture") ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control") ear.addCommand("voice control", ear.getName(), "clearLock") # Confirmations and Negations are not supported yet in WebkitSpeechRecognition # So commands will execute immediatley ear.addComfirmations("yes","correct","ya","yeah", "yes please", "yes of course") ear.addNegations("no","wrong","nope","nah","no thank you", "no thanks") ear.startListening() def rest(): i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0) i01.moveArm("left",5,90,30,10) i01.moveArm("right",5,90,30,10)
webgui = Runtime.create('WebGui', 'WebGui') webgui.autoStartBrowser(False) webgui.startService() webgui.startBrowser('http://localhost:8888/#/service/i01.ear') left_port = 'COM13' right_port = 'COM17' voice = 'cmu-slt-hsmm' voice_type = Voice mouth = Runtime.createAndStart('i01.mouth', 'MarySpeech') mouth.setVoice(voiceType) i01 = Runtime.createAndStart('i01', 'InMoov') i01.startEar() i01.startMouth() i01.startLeftArm(leftPort) i01.startRightArm(rightPort) ear = i01.ear ear.addCommand('attach everything', 'i01', 'attach') ear.addCommand('disconnect everything', 'i01', 'detach') ear.addCommand('attach left arm', 'i01.leftArm', 'attach') ear.addCommand('disconnect left arm', 'i01.leftArm', 'detach') ear.addCommand('attach right arm', 'i01.rightArm', 'attach') ear.addCommand('disconnect right arm', 'i01.rightArm', 'detach') ear.addCommand('rest', 'python', 'rest') ear.addCommand('arms front', i01.getName(), 'armsFront') ear.addCommand('da vinci', i01.getName(), 'daVinci') ear.addCommand('capture gesture', ear.getName(), 'captureGesture') ear.addCommand('manual', ear.getName(), 'lockOutAllGrammarExcept', 'voice control') ear.addCommand('voice control', ear.getName(), 'clearLock') ear.addComfirmations('yes', 'correct', 'ya', 'yeah', 'yes please', 'yes of course') ear.addNegations('no', 'wrong', 'nope', 'nah', 'no thank you', 'no thanks') ear.startListening() def rest(): i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0) i01.moveArm('left', 5, 90, 30, 10) i01.moveArm('right', 5, 90, 30, 10)
my_ssid = "ElchlandGast" my_wp2_pwd = "R1ng0Lu7713" ntp_server = "0.de.pool.ntp.org" my_mqtt_usr = "" my_mqtt_pwd = "" my_mqtt_srv = "192.168.178.35" my_mqtt_port = 1883 my_mqtt_alive_s = 60 my_mqtt_encrypt_key = None # e.g. b'1234123412341234' my_mqtt_encrypt_CBC = None # e.g. b'5678567856785678'
my_ssid = 'ElchlandGast' my_wp2_pwd = 'R1ng0Lu7713' ntp_server = '0.de.pool.ntp.org' my_mqtt_usr = '' my_mqtt_pwd = '' my_mqtt_srv = '192.168.178.35' my_mqtt_port = 1883 my_mqtt_alive_s = 60 my_mqtt_encrypt_key = None my_mqtt_encrypt_cbc = None
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: heightCache = defaultdict(lambda : float('-inf')) def preorder(node, depth): if not node: return heightCache[depth] = max(heightCache[depth], node.val) preorder(node.left, depth + 1) preorder(node.right, depth + 1) preorder(root, 0) result = [] for i, val in sorted(heightCache.items()): result.append(val) return result
class Solution: def largest_values(self, root: TreeNode) -> List[int]: height_cache = defaultdict(lambda : float('-inf')) def preorder(node, depth): if not node: return heightCache[depth] = max(heightCache[depth], node.val) preorder(node.left, depth + 1) preorder(node.right, depth + 1) preorder(root, 0) result = [] for (i, val) in sorted(heightCache.items()): result.append(val) return result
# -*- coding: utf-8 -*- class AuthInfo(object): def __init__(self, username, projectname, commit_id, auth_key): self.username = username self.projectname = projectname self.commit_id = commit_id self.auth_key = auth_key @classmethod def parse(cls, s): if not s: return None try: return cls(*s.split("_:_")) except: return None def to_dict(self): return { "username": self.username, "projectname": self.projectname, "commit_id": self.commit_id, "auth_key": self.auth_key }
class Authinfo(object): def __init__(self, username, projectname, commit_id, auth_key): self.username = username self.projectname = projectname self.commit_id = commit_id self.auth_key = auth_key @classmethod def parse(cls, s): if not s: return None try: return cls(*s.split('_:_')) except: return None def to_dict(self): return {'username': self.username, 'projectname': self.projectname, 'commit_id': self.commit_id, 'auth_key': self.auth_key}
map = 200090300 string = "Mu Lung?" if sm.getFieldID() == 250000100: map = 200090310 string = "Orbis?" response = sm.sendAskYesNo("Would you like to go to " + (string)) if response: sm.warp(map, 0)
map = 200090300 string = 'Mu Lung?' if sm.getFieldID() == 250000100: map = 200090310 string = 'Orbis?' response = sm.sendAskYesNo('Would you like to go to ' + string) if response: sm.warp(map, 0)
def get_baseline_rule(): rule = ".highlight { border-radius: 3.25px; }\n" rule += ".highlight pre { font-family: monospace; font-size: 14px; overflow-x: auto; padding: 1.25rem 1.5rem; white-space: pre; word-wrap: normal; line-height: 1.5; " rule += "}\n" return rule def get_line_no_rule(comment_rule: str, line_no_type: str, num_lines: int) -> str: num_digits = len(str(num_lines)) line_no_color = _comment_rule_to_color(comment_rule) rule = ( ".highlight { counter-reset: line; }\n" "/* from: https://codepen.io/elomatreb/pen/hbgxp */\n" ".highlight .highlight-line::before { " "counter-increment: line; " "content: counter(line); " "display: inline-block; " "padding: 0 .5em 0 0; " f"width: {num_digits}em; " f"color: {line_no_color} " ) if num_digits > 1: rule += "text-align: right; " if line_no_type == "ruled": rule += f"border-right: 1px solid {line_no_color}" "margin-right: 0.5em;" rule += "}\n" return rule def _comment_rule_to_color(comment_rule: str) -> str: words = comment_rule.split(" ") for word in words: if word[0] == "#": if word[-1] == ";": return word else: return word + "; " return "currentColor; "
def get_baseline_rule(): rule = '.highlight { border-radius: 3.25px; }\n' rule += '.highlight pre { font-family: monospace; font-size: 14px; overflow-x: auto; padding: 1.25rem 1.5rem; white-space: pre; word-wrap: normal; line-height: 1.5; ' rule += '}\n' return rule def get_line_no_rule(comment_rule: str, line_no_type: str, num_lines: int) -> str: num_digits = len(str(num_lines)) line_no_color = _comment_rule_to_color(comment_rule) rule = f'.highlight {{ counter-reset: line; }}\n/* from: https://codepen.io/elomatreb/pen/hbgxp */\n.highlight .highlight-line::before {{ counter-increment: line; content: counter(line); display: inline-block; padding: 0 .5em 0 0; width: {num_digits}em; color: {line_no_color} ' if num_digits > 1: rule += 'text-align: right; ' if line_no_type == 'ruled': rule += f'border-right: 1px solid {line_no_color}margin-right: 0.5em;' rule += '}\n' return rule def _comment_rule_to_color(comment_rule: str) -> str: words = comment_rule.split(' ') for word in words: if word[0] == '#': if word[-1] == ';': return word else: return word + '; ' return 'currentColor; '
model=dict( type='Recognizer3D', backbone=dict( type='SwinTransformer3D', patch_size=(2,4,4), embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=(8,7,7), mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, patch_norm=True), cls_head=dict( type='TranSTHead', in_channels=768, dropout_ratio=0.5, num_classes=157, multi_class=True, label_smooth_eps=0.1, topk=(3), tranST=dict(hidden_dim=512, enc_layer_num=0, stld_layer_num=2, n_head=8, dim_feedforward=2048, dropout=0.1, normalize_before=False, fusion=False, rm_self_attn_dec=False, rm_first_self_attn=False, activation="gelu", return_intermediate_dec=False, t_only=False ), loss_cls=dict(type='AsymmetricLossOptimized', gamma_neg=2, gamma_pos=1), ), test_cfg=dict( maximize_clips='score', max_testing_views=4 )) # dataset settings dataset_type = 'CharadesDataset' data_root = 'data/charades/Charades_rgb' data_root_val = 'data/charades/Charades_rgb' ann_file_train = 'data/charades/annotations/charades_train_list_rawframes.csv' ann_file_val = 'data/charades/annotations/charades_val_list_rawframes.csv' ann_file_test = 'data/charades/annotations/charades_val_list_rawframes.csv' img_norm_cfg = dict( # mean=[105.315, 93.84, 86.19], # std=[33.405, 31.875, 33.66], mean=[105.315, 93.84, 86.19], std=[33.405, 31.875, 33.66], to_bgr=False) train_pipeline = [ dict( type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=1), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='RandomResizedCrop'), dict(type='Resize', scale=(224, 224), keep_ratio=False), dict(type='Flip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label']) ] val_pipeline = [ dict( type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=1, test_mode=True), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='CenterCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict( type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=10, test_mode=True), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8, workers_per_gpu=2, val_dataloader=dict(videos_per_gpu=1), test_dataloader=dict(videos_per_gpu=1), train=dict( type=dataset_type, ann_file=ann_file_train, data_prefix=data_root, pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline), test=dict( type=dataset_type, ann_file=ann_file_test, data_prefix=data_root_val, pipeline=test_pipeline)) evaluation = dict( interval=1, metrics=['mean_average_precision']) # optimizer optimizer = dict(type='AdamW', lr=1e-4, betas=(0.9, 0.999), weight_decay=0.05, constructor='freeze_backbone_constructor', paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.), 'relative_position_bias_table': dict(decay_mult=0.), 'norm': dict(decay_mult=0.), 'pos_s': dict(decay_mult=0.), 'pos_t': dict(decay_mult=0.), 'norm1': dict(decay_mult=0.), 'norm2': dict(decay_mult=0.), 'backbone': dict(lr_mult=0.1), 'TranST':dict(lr_mult=0.2)})) # optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict( policy='OneCycle', max_lr=1e-04, anneal_strategy='cos', final_div_factor=1e3, ) total_epochs = 80 # runtime settings work_dir = './work_dirs/k400_swin_tiny_1k_patch244_freeze_backbone_window877_tranST_charades' find_unused_parameters = True checkpoint_config = dict(interval=5) log_config = dict( interval=10, hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) # runtime settings dist_params = dict(backend='nccl') log_level = 'INFO' # load_from = ('https://github.com/SwinTransformer/storage/releases/download/' # 'v1.0.4/swin_tiny_patch244_window877_kinetics400_1k.pth') # load_from = ('work_dirs/k400_swin_tiny_1k_patch244_window877_charades/map4210.pth') load_from = ('work_dirs/k400_swin_tiny_1k_patch244_window877_charades/map4048_32f.pth') # load_from = None resume_from = None workflow = [('train', 1)] # do not use mmdet version fp16 fp16 = None optimizer_config = dict( type="DistOptimizerHook", update_interval=2, grad_clip=None, coalesce=True, bucket_size_mb=-1, use_fp16=True, )
model = dict(type='Recognizer3D', backbone=dict(type='SwinTransformer3D', patch_size=(2, 4, 4), embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=(8, 7, 7), mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1, patch_norm=True), cls_head=dict(type='TranSTHead', in_channels=768, dropout_ratio=0.5, num_classes=157, multi_class=True, label_smooth_eps=0.1, topk=3, tranST=dict(hidden_dim=512, enc_layer_num=0, stld_layer_num=2, n_head=8, dim_feedforward=2048, dropout=0.1, normalize_before=False, fusion=False, rm_self_attn_dec=False, rm_first_self_attn=False, activation='gelu', return_intermediate_dec=False, t_only=False), loss_cls=dict(type='AsymmetricLossOptimized', gamma_neg=2, gamma_pos=1)), test_cfg=dict(maximize_clips='score', max_testing_views=4)) dataset_type = 'CharadesDataset' data_root = 'data/charades/Charades_rgb' data_root_val = 'data/charades/Charades_rgb' ann_file_train = 'data/charades/annotations/charades_train_list_rawframes.csv' ann_file_val = 'data/charades/annotations/charades_val_list_rawframes.csv' ann_file_test = 'data/charades/annotations/charades_val_list_rawframes.csv' img_norm_cfg = dict(mean=[105.315, 93.84, 86.19], std=[33.405, 31.875, 33.66], to_bgr=False) train_pipeline = [dict(type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=1), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='RandomResizedCrop'), dict(type='Resize', scale=(224, 224), keep_ratio=False), dict(type='Flip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label'])] val_pipeline = [dict(type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=1, test_mode=True), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='CenterCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])] test_pipeline = [dict(type='SampleCharadesFrames', clip_len=32, frame_interval=2, num_clips=10, test_mode=True), dict(type='RawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])] data = dict(videos_per_gpu=8, workers_per_gpu=2, val_dataloader=dict(videos_per_gpu=1), test_dataloader=dict(videos_per_gpu=1), train=dict(type=dataset_type, ann_file=ann_file_train, data_prefix=data_root, pipeline=train_pipeline), val=dict(type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline), test=dict(type=dataset_type, ann_file=ann_file_test, data_prefix=data_root_val, pipeline=test_pipeline)) evaluation = dict(interval=1, metrics=['mean_average_precision']) optimizer = dict(type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.05, constructor='freeze_backbone_constructor', paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.0), 'relative_position_bias_table': dict(decay_mult=0.0), 'norm': dict(decay_mult=0.0), 'pos_s': dict(decay_mult=0.0), 'pos_t': dict(decay_mult=0.0), 'norm1': dict(decay_mult=0.0), 'norm2': dict(decay_mult=0.0), 'backbone': dict(lr_mult=0.1), 'TranST': dict(lr_mult=0.2)})) lr_config = dict(policy='OneCycle', max_lr=0.0001, anneal_strategy='cos', final_div_factor=1000.0) total_epochs = 80 work_dir = './work_dirs/k400_swin_tiny_1k_patch244_freeze_backbone_window877_tranST_charades' find_unused_parameters = True checkpoint_config = dict(interval=5) log_config = dict(interval=10, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = 'work_dirs/k400_swin_tiny_1k_patch244_window877_charades/map4048_32f.pth' resume_from = None workflow = [('train', 1)] fp16 = None optimizer_config = dict(type='DistOptimizerHook', update_interval=2, grad_clip=None, coalesce=True, bucket_size_mb=-1, use_fp16=True)
list_a = [5, 20, 3, 7, 6, 8] n = int(input()) list_a = sorted(list_a) list_len = len(list_a) res = list_a[list_len - n:] for i in range(n): res[i] = str(res[i]) print(" ".join(res))
list_a = [5, 20, 3, 7, 6, 8] n = int(input()) list_a = sorted(list_a) list_len = len(list_a) res = list_a[list_len - n:] for i in range(n): res[i] = str(res[i]) print(' '.join(res))
# level1.py def first_room(): print("Welcome to the dungeon. You walk into the first room and see an empty hall.") print("There is an ominous door at the far end of this hall.") options = {1: "Go back home to safety", 2: "Go through door"} for k, v in options.items(): print("[" + str(k) + "] " + v) val = input("Select the number of your choice ") return int(val) def second_room(): print("A box stands in the middle of this room. There is a skull and crossbones on the box.") print("Do you open the box or ignore it and continue through the next door?") options = {1: "Open the box", 2: "Continue through the next door", 3: "Go back to entrance"} for k, v in options.items(): print("[" + str(k) + "] " + v) val = input("Select the number of your choice ") return int(val) def next_level(): print("There are stairs leading down.") options = {1: "Go back home to safety", 2: "Descend the stairs"} for k, v in options.items(): print("[" + str(k) + "] " + v) val = input("Select the number of your choice ") return int(val)
def first_room(): print('Welcome to the dungeon. You walk into the first room and see an empty hall.') print('There is an ominous door at the far end of this hall.') options = {1: 'Go back home to safety', 2: 'Go through door'} for (k, v) in options.items(): print('[' + str(k) + '] ' + v) val = input('Select the number of your choice ') return int(val) def second_room(): print('A box stands in the middle of this room. There is a skull and crossbones on the box.') print('Do you open the box or ignore it and continue through the next door?') options = {1: 'Open the box', 2: 'Continue through the next door', 3: 'Go back to entrance'} for (k, v) in options.items(): print('[' + str(k) + '] ' + v) val = input('Select the number of your choice ') return int(val) def next_level(): print('There are stairs leading down.') options = {1: 'Go back home to safety', 2: 'Descend the stairs'} for (k, v) in options.items(): print('[' + str(k) + '] ' + v) val = input('Select the number of your choice ') return int(val)
# Stack and Queue # https://stackabuse.com/stacks-and-queues-in-python/ # A simple class stack that only allows pop and push operations class Stack: def __init__(self): self.stack = [] def pop(self): if len(self.stack) < 1: return None return self.stack.pop() def push(self, item): self.stack.append(item) def size(self): return len(self.stack) # And a queue that only has enqueue and dequeue operations class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if len(self.queue) < 1: return None return self.queue.pop(0) def size(self): return len(self.queue)
class Stack: def __init__(self): self.stack = [] def pop(self): if len(self.stack) < 1: return None return self.stack.pop() def push(self, item): self.stack.append(item) def size(self): return len(self.stack) class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if len(self.queue) < 1: return None return self.queue.pop(0) def size(self): return len(self.queue)
class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: hashMap = collections.Counter(arr1) array = [] for num in arr2: array += [num] * hashMap.pop(num) return array + sorted(hashMap.elements()) class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: hashMap = collections.Counter(arr1) array = [] for num in arr2: array += [num] * hashMap.pop(num) for num in sorted(hashMap.keys()): array += [num] * hashMap[num] return array class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: hashMap = {} for num in arr1: if num not in hashMap: hashMap[num] = 1 else: hashMap[num] += 1 array = [] for num in arr2: array += [num] * hashMap.pop(num) for num in sorted(hashMap.keys()): array += [num] * hashMap[num] return array
class Solution: def relative_sort_array(self, arr1: List[int], arr2: List[int]) -> List[int]: hash_map = collections.Counter(arr1) array = [] for num in arr2: array += [num] * hashMap.pop(num) return array + sorted(hashMap.elements()) class Solution: def relative_sort_array(self, arr1: List[int], arr2: List[int]) -> List[int]: hash_map = collections.Counter(arr1) array = [] for num in arr2: array += [num] * hashMap.pop(num) for num in sorted(hashMap.keys()): array += [num] * hashMap[num] return array class Solution: def relative_sort_array(self, arr1: List[int], arr2: List[int]) -> List[int]: hash_map = {} for num in arr1: if num not in hashMap: hashMap[num] = 1 else: hashMap[num] += 1 array = [] for num in arr2: array += [num] * hashMap.pop(num) for num in sorted(hashMap.keys()): array += [num] * hashMap[num] return array
# Program to check if number is Disarium Number or Nor :) n = input("Enter a number: ") num = [i for i in n] # splitting the number into array of digits a = 0 # creating empty variable for x in range(len(n)): a += int(num[x]) ** (x+1) # Logic for Disarium Number if a == int(n): # Checks whether the sum is equal to the number itself print(n, "is a Disarium.") else: print(n, "is not a Disarium.")
n = input('Enter a number: ') num = [i for i in n] a = 0 for x in range(len(n)): a += int(num[x]) ** (x + 1) if a == int(n): print(n, 'is a Disarium.') else: print(n, 'is not a Disarium.')
# OpenWeatherMap API Key weather_api_key = "a03abb9d3c267db1cbe474a809d9d185" # Google API Key g_key = "AIzaSyCCCDtBWuZZ51TMovxlWIkmC7z_VPlfrzA"
weather_api_key = 'a03abb9d3c267db1cbe474a809d9d185' g_key = 'AIzaSyCCCDtBWuZZ51TMovxlWIkmC7z_VPlfrzA'
tempo = int(input('Quantos anos tem seu carro ?')) if tempo <=3: print('Carro Novo') else: print('Carro Velho') print('__FIM__')
tempo = int(input('Quantos anos tem seu carro ?')) if tempo <= 3: print('Carro Novo') else: print('Carro Velho') print('__FIM__')
# Copyright (c) 2020 original authors # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Position: def __init__(self, start=0, end=0): self._start = start self._end = end @property def start(self): return self._start @property def end(self): return self._end
class Position: def __init__(self, start=0, end=0): self._start = start self._end = end @property def start(self): return self._start @property def end(self): return self._end
for i in range(10000): class A: def __init__(self, x): self.x = x
for i in range(10000): class A: def __init__(self, x): self.x = x
# -*- coding: utf-8 -*- ''' Configuration of the alternatives system Control the alternatives system .. code-block:: yaml {% set my_hadoop_conf = '/opt/hadoop/conf' %} {{ my_hadoop_conf }}: file.directory hadoop-0.20-conf: alternatives.install: - name: hadoop-0.20-conf - link: /etc/hadoop-0.20/conf - path: {{ my_hadoop_conf }} - priority: 30 - require: - file: {{ my_hadoop_conf }} hadoop-0.20-conf: alternatives.remove: - name: hadoop-0.20-conf - path: {{ my_hadoop_conf }} ''' # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def install(name, link, path, priority): ''' Install new alternative for defined <name> name is the master name for this link group (e.g. pager) link is the symlink pointing to /etc/alternatives/<name>. (e.g. /usr/bin/pager) path is the location of the new alternative target. NB: This file / directory must already exist. (e.g. /usr/bin/less) priority is an integer; options with higher numbers have higher priority in automatic mode. ''' ret = {'name': name, 'link': link, 'path': path, 'priority': priority, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if not isinstalled: if __opts__['test']: ret['comment'] = ( 'Alternative will be set for {0} to {1} with priority {2}' ).format(name, path, priority) ret['result'] = None return ret __salt__['alternatives.install'](name, link, path, priority) ret['comment'] = ( 'Setting alternative for {0} to {1} with priority {2}' ).format(name, path, priority) ret['changes'] = {'name': name, 'link': link, 'path': path, 'priority': priority} return ret ret['comment'] = 'Alternatives for {0} is already set to {1}'.format(name, path) return ret def remove(name, path): ''' Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if isinstalled: if __opts__['test']: ret['comment'] = ('Alternative for {0} will be removed' .format(name)) ret['result'] = None return ret __salt__['alternatives.remove'](name, path) current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} removed. Falling back to path {1}' ).format(name, current) ret['changes'] = {'path': current} return ret ret['comment'] = 'Alternative for {0} removed'.format(name) ret['changes'] = {} return ret current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} is set to it\'s default path {1}' ).format(name, current) return ret ret['result'] = False ret['comment'] = ( 'Alternative for {0} doesn\'t exist' ).format(name) return ret def auto(name): ''' .. versionadded:: 0.17.0 Instruct alternatives to use the highest priority path for <name> name is the master name for this link group (e.g. pager) ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} display = __salt__['alternatives.display'](name) line = display.splitlines()[0] if line.endswith(' auto mode'): ret['comment'] = '{0} already in auto mode'.format(name) return ret if __opts__['test']: ret['comment'] = '{0} will be put in auto mode'.format(name) ret['result'] = None return ret ret['changes']['result'] = __salt__['alternatives.auto'](name) return ret def set_(name, path): ''' .. versionadded:: 0.17.0 Sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = 'Alternative for {0} already set to {1}'.format(name, path) return ret display = __salt__['alternatives.display'](name) isinstalled = False for line in display.splitlines(): if line.startswith(path): isinstalled = True break if isinstalled: if __opts__['test']: ret['comment'] = ( 'Alternative for {0} will be set to path {1}' ).format(name, current) ret['result'] = None return ret __salt__['alternatives.set'](name, path) current = __salt__['alternatives.show_current'](name) if current == path: ret['result'] = True ret['comment'] = ( 'Alternative for {0} set to path {1}' ).format(name, current) ret['changes'] = {'path': current} else: ret['comment'] = 'Alternative for {0} not updated'.format(name) return ret else: ret['result'] = False ret['comment'] = ( 'Alternative {0} for {1} doesn\'t exist' ).format(path, name) return ret
""" Configuration of the alternatives system Control the alternatives system .. code-block:: yaml {% set my_hadoop_conf = '/opt/hadoop/conf' %} {{ my_hadoop_conf }}: file.directory hadoop-0.20-conf: alternatives.install: - name: hadoop-0.20-conf - link: /etc/hadoop-0.20/conf - path: {{ my_hadoop_conf }} - priority: 30 - require: - file: {{ my_hadoop_conf }} hadoop-0.20-conf: alternatives.remove: - name: hadoop-0.20-conf - path: {{ my_hadoop_conf }} """ __func_alias__ = {'set_': 'set'} def install(name, link, path, priority): """ Install new alternative for defined <name> name is the master name for this link group (e.g. pager) link is the symlink pointing to /etc/alternatives/<name>. (e.g. /usr/bin/pager) path is the location of the new alternative target. NB: This file / directory must already exist. (e.g. /usr/bin/less) priority is an integer; options with higher numbers have higher priority in automatic mode. """ ret = {'name': name, 'link': link, 'path': path, 'priority': priority, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if not isinstalled: if __opts__['test']: ret['comment'] = 'Alternative will be set for {0} to {1} with priority {2}'.format(name, path, priority) ret['result'] = None return ret __salt__['alternatives.install'](name, link, path, priority) ret['comment'] = 'Setting alternative for {0} to {1} with priority {2}'.format(name, path, priority) ret['changes'] = {'name': name, 'link': link, 'path': path, 'priority': priority} return ret ret['comment'] = 'Alternatives for {0} is already set to {1}'.format(name, path) return ret def remove(name, path): """ Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) """ ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if isinstalled: if __opts__['test']: ret['comment'] = 'Alternative for {0} will be removed'.format(name) ret['result'] = None return ret __salt__['alternatives.remove'](name, path) current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = 'Alternative for {0} removed. Falling back to path {1}'.format(name, current) ret['changes'] = {'path': current} return ret ret['comment'] = 'Alternative for {0} removed'.format(name) ret['changes'] = {} return ret current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = "Alternative for {0} is set to it's default path {1}".format(name, current) return ret ret['result'] = False ret['comment'] = "Alternative for {0} doesn't exist".format(name) return ret def auto(name): """ .. versionadded:: 0.17.0 Instruct alternatives to use the highest priority path for <name> name is the master name for this link group (e.g. pager) """ ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} display = __salt__['alternatives.display'](name) line = display.splitlines()[0] if line.endswith(' auto mode'): ret['comment'] = '{0} already in auto mode'.format(name) return ret if __opts__['test']: ret['comment'] = '{0} will be put in auto mode'.format(name) ret['result'] = None return ret ret['changes']['result'] = __salt__['alternatives.auto'](name) return ret def set_(name, path): """ .. versionadded:: 0.17.0 Sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) """ ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = 'Alternative for {0} already set to {1}'.format(name, path) return ret display = __salt__['alternatives.display'](name) isinstalled = False for line in display.splitlines(): if line.startswith(path): isinstalled = True break if isinstalled: if __opts__['test']: ret['comment'] = 'Alternative for {0} will be set to path {1}'.format(name, current) ret['result'] = None return ret __salt__['alternatives.set'](name, path) current = __salt__['alternatives.show_current'](name) if current == path: ret['result'] = True ret['comment'] = 'Alternative for {0} set to path {1}'.format(name, current) ret['changes'] = {'path': current} else: ret['comment'] = 'Alternative for {0} not updated'.format(name) return ret else: ret['result'] = False ret['comment'] = "Alternative {0} for {1} doesn't exist".format(path, name) return ret
class line_dp: def reader(self,FileName): #puts each line of a file into an entry of a list, removing "\n" f = open(FileName,'r') out =[] i = 0 for lin in f: out.append(lin) if out[i].count("\n") != 0: #removes "\n" out[i] = out[i].replace("\n","") i = i + 1 numlines = len(out) return out def writer(self,FileName, linelist): f = open(FileName,'w') f.seek(0) for line in linelist: f.write(line) f.write("\n") ### Some handy tools def STR(self,linelist): ''' converts all elements in a list to strings ''' out = [] for x in linelist: out.append(str(x)) return out def reducespaces(self,line): ''' removes excessive spaces; separates ''' i = 0 out = [] for string in line: if line[i] == ' ' and line[i-1] == ' ': pass else: out.append(line[i]) i = i + 1 s_out = ''.join(out) ready_out = s_out.split(' ') return ready_out def redspfile(self,linelist): '''extension of reducespaces(): converts a linelist to a list of nested lists''' newlist = [] for line in linelist: newlist.append(self.reducespaces(line)) #should be in line I/O return newlist def getlineslists(self,listnl): new = [] for List in listnl: new.append(' '.join(List)) return new def listToFlt(self,List): convert = [] for y in List: try: convert.append(float(y)) except: convert.append(y) #convert = [float(y) for y in List] # return convert def nestedToFlt(self,ListNestedLists): convert = ListNestedLists #placeholder i= 0 #counter for x in convert: convert[i]= self.listToFlt(x)#returns a list to replace the original i = i + 1 #...nested list return convert # def Indir(self, path, ftype): # return path, self.reader(path+'/'ftype+'_ls.dir') lin = line_dp()
class Line_Dp: def reader(self, FileName): f = open(FileName, 'r') out = [] i = 0 for lin in f: out.append(lin) if out[i].count('\n') != 0: out[i] = out[i].replace('\n', '') i = i + 1 numlines = len(out) return out def writer(self, FileName, linelist): f = open(FileName, 'w') f.seek(0) for line in linelist: f.write(line) f.write('\n') def str(self, linelist): """ converts all elements in a list to strings """ out = [] for x in linelist: out.append(str(x)) return out def reducespaces(self, line): """ removes excessive spaces; separates """ i = 0 out = [] for string in line: if line[i] == ' ' and line[i - 1] == ' ': pass else: out.append(line[i]) i = i + 1 s_out = ''.join(out) ready_out = s_out.split(' ') return ready_out def redspfile(self, linelist): """extension of reducespaces(): converts a linelist to a list of nested lists""" newlist = [] for line in linelist: newlist.append(self.reducespaces(line)) return newlist def getlineslists(self, listnl): new = [] for list in listnl: new.append(' '.join(List)) return new def list_to_flt(self, List): convert = [] for y in List: try: convert.append(float(y)) except: convert.append(y) return convert def nested_to_flt(self, ListNestedLists): convert = ListNestedLists i = 0 for x in convert: convert[i] = self.listToFlt(x) i = i + 1 return convert lin = line_dp()
# This will manage all broadcasts class Broadcaster(object): def __init__(self): self.broadcasts = [] broadcaster = Broadcaster()
class Broadcaster(object): def __init__(self): self.broadcasts = [] broadcaster = broadcaster()
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For op in NO_FP64_CHECK_GRAD_OP_LIST, the op test requires check_grad with fp64 precision NO_FP64_CHECK_GRAD_OP_LIST = [ 'affine_grid', \ 'clip', \ 'conv2d', \ 'conv2d_transpose', \ 'conv3d', \ 'conv3d_transpose', \ 'conv_shift', \ 'cos_sim', \ 'cudnn_lstm', \ 'cvm', \ 'data_norm', \ 'deformable_conv', \ 'deformable_conv_v1', \ 'deformable_psroi_pooling', \ 'depthwise_conv2d', \ 'depthwise_conv2d_transpose', \ 'dropout', \ 'fused_elemwise_activation', \ 'hinge_loss', \ 'huber_loss', \ 'im2sequence', \ 'increment', \ 'l1_norm', \ 'log_loss', \ 'lrn', \ 'margin_rank_loss', \ 'match_matrix_tensor', \ 'matmul', \ 'max_pool2d_with_index', \ 'max_pool3d_with_index', \ 'minus', \ 'modified_huber_loss', \ 'nce', \ 'pool2d', \ 'pool3d', \ 'prroi_pool', \ 'rank_loss', \ 'reduce_max', \ 'reduce_min', \ 'reshape2', \ 'roi_perspective_transform', \ 'row_conv', \ 'scatter', \ 'sequence_conv', \ 'sequence_pool', \ 'sequence_reverse', \ 'sequence_slice', \ 'sequence_topk_avg_pooling', \ 'shuffle_channel', \ 'sigmoid', \ 'smooth_l1_loss', \ 'softmax', \ 'spectral_norm', \ 'squared_l2_distance', \ 'squared_l2_norm', \ 'tanh', \ 'mish', \ 'transpose2', \ 'trilinear_interp', \ 'var_conv_2d', \ 'warpctc' ] NO_FP16_CHECK_GRAD_OP_LIST = [ 'fused_elemwise_activation', \ 'pool2d', \ 'pool3d', \ 'softmax',\ 'conv2d_transpose' ]
no_fp64_check_grad_op_list = ['affine_grid', 'clip', 'conv2d', 'conv2d_transpose', 'conv3d', 'conv3d_transpose', 'conv_shift', 'cos_sim', 'cudnn_lstm', 'cvm', 'data_norm', 'deformable_conv', 'deformable_conv_v1', 'deformable_psroi_pooling', 'depthwise_conv2d', 'depthwise_conv2d_transpose', 'dropout', 'fused_elemwise_activation', 'hinge_loss', 'huber_loss', 'im2sequence', 'increment', 'l1_norm', 'log_loss', 'lrn', 'margin_rank_loss', 'match_matrix_tensor', 'matmul', 'max_pool2d_with_index', 'max_pool3d_with_index', 'minus', 'modified_huber_loss', 'nce', 'pool2d', 'pool3d', 'prroi_pool', 'rank_loss', 'reduce_max', 'reduce_min', 'reshape2', 'roi_perspective_transform', 'row_conv', 'scatter', 'sequence_conv', 'sequence_pool', 'sequence_reverse', 'sequence_slice', 'sequence_topk_avg_pooling', 'shuffle_channel', 'sigmoid', 'smooth_l1_loss', 'softmax', 'spectral_norm', 'squared_l2_distance', 'squared_l2_norm', 'tanh', 'mish', 'transpose2', 'trilinear_interp', 'var_conv_2d', 'warpctc'] no_fp16_check_grad_op_list = ['fused_elemwise_activation', 'pool2d', 'pool3d', 'softmax', 'conv2d_transpose']
class InsertResponse: def __init__(self, entry_id, error_msg: str): self.entry_id = entry_id self.error_msg = error_msg class UpdateResponse: def __init__(self, entry_id, error_msg: str): self.entry_id = entry_id self.error_msg = error_msg
class Insertresponse: def __init__(self, entry_id, error_msg: str): self.entry_id = entry_id self.error_msg = error_msg class Updateresponse: def __init__(self, entry_id, error_msg: str): self.entry_id = entry_id self.error_msg = error_msg
def translator(en_word): if en_word == 'dog': print('sobaka') elif en_word == 'kat': print('koshka') translator('dog')
def translator(en_word): if en_word == 'dog': print('sobaka') elif en_word == 'kat': print('koshka') translator('dog')
class TestLandingPage: def test_we_can_get_the_page(self, app): result = app.get("/", status=200) assert "<html" in result
class Testlandingpage: def test_we_can_get_the_page(self, app): result = app.get('/', status=200) assert '<html' in result
local = {"latitude": 100000, "longitude": 200000} for i in range(0,10): print("{1} {0:>20} {latitude} {longitude}".format("100", "10",**local))
local = {'latitude': 100000, 'longitude': 200000} for i in range(0, 10): print('{1} {0:>20} {latitude} {longitude}'.format('100', '10', **local))
# # PySNMP MIB module CISCO-OSPF-CAPABILITY (http://pysnmp.sf.net) # Produced by pysmi-0.0.1 from CISCO-OSPF-CAPABILITY at Fri May 8 20:20:05 2015 # On host cray platform Linux version 2.6.37.6-smp by user tt # Using Python version 2.7.2 (default, Apr 2 2012, 20:32:47) # ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint") ( ciscoAgentCapability, ) = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability") ( AgentCapabilities, ) = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities") ( Integer32, MibIdentifier, TimeTicks, iso, Gauge32, ModuleIdentity, Bits, Counter32, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibIdentifier", "TimeTicks", "iso", "Gauge32", "ModuleIdentity", "Bits", "Counter32") ciscoOspfCapability = ModuleIdentity(ciscoAgentCapability.getName() + (287,)).setRevisions(("2002-11-26 00:00",)) ciscoOspfCapabilityV12R025S = AgentCapabilities(ciscoOspfCapability.getName() + (1,)) mibBuilder.exportSymbols("CISCO-OSPF-CAPABILITY", ciscoOspfCapability=ciscoOspfCapability, ciscoOspfCapabilityV12R025S=ciscoOspfCapabilityV12R025S, PYSNMP_MODULE_ID=ciscoOspfCapability)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint') (cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability') (agent_capabilities,) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities') (integer32, mib_identifier, time_ticks, iso, gauge32, module_identity, bits, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'MibIdentifier', 'TimeTicks', 'iso', 'Gauge32', 'ModuleIdentity', 'Bits', 'Counter32') cisco_ospf_capability = module_identity(ciscoAgentCapability.getName() + (287,)).setRevisions(('2002-11-26 00:00',)) cisco_ospf_capability_v12_r025_s = agent_capabilities(ciscoOspfCapability.getName() + (1,)) mibBuilder.exportSymbols('CISCO-OSPF-CAPABILITY', ciscoOspfCapability=ciscoOspfCapability, ciscoOspfCapabilityV12R025S=ciscoOspfCapabilityV12R025S, PYSNMP_MODULE_ID=ciscoOspfCapability)
class Mover(object): def __init__(self): self.location = PVector(random(width), random(height)) self.velocity = PVector(random(-5, 5), random(-5, 5)) self.r = 15 def update(self): self.location.add(self.velocity) def display(self): stroke(0) fill(255, 100, 255) ellipse(self.location.x, self.location.y, 2*self.r, 2*self.r) def checkBoundaries(self): if (self.location.x > width + self.r): self.location.x = -self.r elif (self.location.x < -self.r): self.location.x = width + self.r if (self.location.y > height + self.r): self.location.y = -self.r elif (self.location.y < -self.r): self.location.y = height + self.r
class Mover(object): def __init__(self): self.location = p_vector(random(width), random(height)) self.velocity = p_vector(random(-5, 5), random(-5, 5)) self.r = 15 def update(self): self.location.add(self.velocity) def display(self): stroke(0) fill(255, 100, 255) ellipse(self.location.x, self.location.y, 2 * self.r, 2 * self.r) def check_boundaries(self): if self.location.x > width + self.r: self.location.x = -self.r elif self.location.x < -self.r: self.location.x = width + self.r if self.location.y > height + self.r: self.location.y = -self.r elif self.location.y < -self.r: self.location.y = height + self.r
fname = input("Enter file name: ") fh = open(fname) content = fh.read() print(content.upper().rstrip())
fname = input('Enter file name: ') fh = open(fname) content = fh.read() print(content.upper().rstrip())
def count_unlocked_achievements(achievements: list) -> int: # Set counter for unlocker achievements 'unlocked' to 0 unlocked = 0 # count achievements stored in "achieved" within achievements array for x in achievements: if x["achieved"] == 1: unlocked = unlocked + 1 return unlocked def list_unlocked_achievements(achievements: list) -> list: unlocked_achievements = [] for x in achievements: if x["achieved"] == 1: unlocked_achievements.append(x) return unlocked_achievements
def count_unlocked_achievements(achievements: list) -> int: unlocked = 0 for x in achievements: if x['achieved'] == 1: unlocked = unlocked + 1 return unlocked def list_unlocked_achievements(achievements: list) -> list: unlocked_achievements = [] for x in achievements: if x['achieved'] == 1: unlocked_achievements.append(x) return unlocked_achievements
# Decorator to check params of BraidWord def checkparams_braidword(func: 'func') -> 'func': def wrapper(*args, **kwargs): if len(args) > 1: # args will have self since for class initword = args[1] # Check if type is not list if not isinstance(initword, list): msg = "BraidWord initword argument must be a list." raise TypeError(msg) # Check if any generators are zero elif 0 in initword: msg = ('Braid generators are indexed starting at one. ' 'No zero braid generators allowed.') raise ValueError(msg) else: return func(*args, **kwargs) else: initword = kwargs[list(kwargs.keys())[0]] # Check if type is not list if not isinstance(initword, list): msg = "initword argument must be a list." raise TypeError(msg) # Check if any generators are zero elif 0 in initword: msg = ('Braid generators are indexed starting at one. ' 'No zero braid generators allowed.') raise ValueError(msg) else: return func(*args, **kwargs) return wrapper
def checkparams_braidword(func: 'func') -> 'func': def wrapper(*args, **kwargs): if len(args) > 1: initword = args[1] if not isinstance(initword, list): msg = 'BraidWord initword argument must be a list.' raise type_error(msg) elif 0 in initword: msg = 'Braid generators are indexed starting at one. No zero braid generators allowed.' raise value_error(msg) else: return func(*args, **kwargs) else: initword = kwargs[list(kwargs.keys())[0]] if not isinstance(initword, list): msg = 'initword argument must be a list.' raise type_error(msg) elif 0 in initword: msg = 'Braid generators are indexed starting at one. No zero braid generators allowed.' raise value_error(msg) else: return func(*args, **kwargs) return wrapper
class Nameservice: def __init__(self, name): self.name = name self.namenodes = [] self.journalnodes = [] self.resourcemanagers = [] # self.zookeepers = [] self.hostnames = {} self.HAenable = False def __repr__(self): return str(self) def __str__(self): return "<name: %s, namenodes: %s>" % (self.name, self.namenodes) def addNode(self, type, node): if type == "namenode": self.namenodes.append(node) elif type == "journalnode": self.journalnodes.append(node) elif type == "resourcemanager": self.resourcemanagers.append(node) # elif type == "zookeeper": # self.zookeepers.append(node) def getNamenodesID(self): str = "" for namenode in self.namenodes[:-1]: str += namenode.id + "," else: str += self.namenodes[-1].id return str def getJournalnodesHost(self): str = "qjournal://" for journalnode in self.journalnodes[:-1]: str += journalnode.hostname + ":8485;" else: str += self.journalnodes[-1].hostname + ":8485/" + self.name return str # def getZookeepersHost(self): # str = "" # for zookeeper in self.zookeepers[:-1]: # str += zookeeper.hostname + ":2181," # else: # str += self.zookeepers[-1].hostname + ":2181" # return str def setHostnames(self): for namenode in self.namenodes: if namenode.ip in self.hostnames: self.hostnames[namenode.ip].append(namenode.hostname) else: self.hostnames[namenode.ip] = [] self.hostnames[namenode.ip].append(namenode.hostname) for journalnode in self.journalnodes: if journalnode.ip in self.hostnames: self.hostnames[journalnode.ip].append(journalnode.hostname) else: self.hostnames[journalnode.ip] = [] self.hostnames[journalnode.ip].append(journalnode.hostname) # for zookeeper in self.zookeepers: # if zookeeper.ip in self.hostnames: # self.hostnames[zookeeper.ip].append(zookeeper.hostname) # else: # self.hostnames[zookeeper.ip] = [] # self.hostnames[zookeeper.ip].append(zookeeper.hostname) for resourcemanager in self.resourcemanagers: if resourcemanager.ip in self.hostnames: self.hostnames[resourcemanager.ip].append(resourcemanager.hostname) else: self.hostnames[resourcemanager.ip] = [] self.hostnames[resourcemanager.ip].append(resourcemanager.hostname) def setHAenable(self): if len(self.namenodes) == 0: raise Exception("The number of namenodes in one cluster is 0!") elif len(self.namenodes) == 1: self.HAenable = False elif len(self.namenodes) == 2: self.HAenable = True elif len(self.namenodes) > 3: raise Exception("The number of namenodes in one cluster is more 2!") def validate(self): self.illegal = False all = self.namenodes + self.journalnodes + self.resourcemanagers self.illegal = reduce(lambda x, y : x and y, map(lambda x : x.illegal, all), True) if self.HAenable and (len(self.journalnodes) == 0): self.illegal = False elif not self.HAenable and (len(self.journalnodes) > 0): self.illegal = False if self.illegal == False: raise Exception('''ConfigureError: Your configuration is illegal. NOTE: If HA is enable ''' + '''(contains Two namenode in a nameservice), your have to provide ZK and journalnode.''') # if __name__ == "__main__": # from node import * # test = Nameservice("test") # test.addNode("namenode", Node(1, "192.168.1.31", 1, "namenode")) # test.addNode("namenode", Node(1, "192.168.1.31", 1, "namenode")) # test.addNode("journalnode", Node(1, "192.168.1.31", 1, "journalnode")) # # test.addNode("zookeeper", Node(1, "192.168.1.31", 1, "zookeeper")) # test.setHAenable() # test.validate() # print 1 + 2 # print test.HAenable # print test.illegal
class Nameservice: def __init__(self, name): self.name = name self.namenodes = [] self.journalnodes = [] self.resourcemanagers = [] self.hostnames = {} self.HAenable = False def __repr__(self): return str(self) def __str__(self): return '<name: %s, namenodes: %s>' % (self.name, self.namenodes) def add_node(self, type, node): if type == 'namenode': self.namenodes.append(node) elif type == 'journalnode': self.journalnodes.append(node) elif type == 'resourcemanager': self.resourcemanagers.append(node) def get_namenodes_id(self): str = '' for namenode in self.namenodes[:-1]: str += namenode.id + ',' else: str += self.namenodes[-1].id return str def get_journalnodes_host(self): str = 'qjournal://' for journalnode in self.journalnodes[:-1]: str += journalnode.hostname + ':8485;' else: str += self.journalnodes[-1].hostname + ':8485/' + self.name return str def set_hostnames(self): for namenode in self.namenodes: if namenode.ip in self.hostnames: self.hostnames[namenode.ip].append(namenode.hostname) else: self.hostnames[namenode.ip] = [] self.hostnames[namenode.ip].append(namenode.hostname) for journalnode in self.journalnodes: if journalnode.ip in self.hostnames: self.hostnames[journalnode.ip].append(journalnode.hostname) else: self.hostnames[journalnode.ip] = [] self.hostnames[journalnode.ip].append(journalnode.hostname) for resourcemanager in self.resourcemanagers: if resourcemanager.ip in self.hostnames: self.hostnames[resourcemanager.ip].append(resourcemanager.hostname) else: self.hostnames[resourcemanager.ip] = [] self.hostnames[resourcemanager.ip].append(resourcemanager.hostname) def set_h_aenable(self): if len(self.namenodes) == 0: raise exception('The number of namenodes in one cluster is 0!') elif len(self.namenodes) == 1: self.HAenable = False elif len(self.namenodes) == 2: self.HAenable = True elif len(self.namenodes) > 3: raise exception('The number of namenodes in one cluster is more 2!') def validate(self): self.illegal = False all = self.namenodes + self.journalnodes + self.resourcemanagers self.illegal = reduce(lambda x, y: x and y, map(lambda x: x.illegal, all), True) if self.HAenable and len(self.journalnodes) == 0: self.illegal = False elif not self.HAenable and len(self.journalnodes) > 0: self.illegal = False if self.illegal == False: raise exception('ConfigureError: Your configuration is illegal. NOTE: If HA is enable ' + '(contains Two namenode in a nameservice), your have to provide ZK and journalnode.')
############################### ##MUST CHANGE THIS VARIABLE## ############################################################################################# ## small format = sf large format = wf engraving = en uv printing = uv #### ## envelope = env dyesub = ds vinyl = vin digital = dig #### ## inventory = inven outsourced = out #### ############################################################################################# type = 'sf' ##<-- change this## ########################## #####OTHER VARIABLES###### ##give the ink item the current value of "Is your project Color or Black & White?" i = lookup('is_your_prack__white4030') env['ink'] = i paper = lookup('what_kind_d_you_like3565') ##global variables pc_array = { #LETTER 'ltr':{ 'color':{ 4000:{'desc':'T1.5','pc':'1044','price':0.056}, 2000:{'desc':'T1.4','pc':'1043','price':0.060}, 1000:{'desc':'T1.3','pc':'1042','price':0.070}, 500: {'desc':'T1.2','pc':'1041','price':0.080}, 0: {'desc':'T1.1','pc':'1040','price':0.120} }, 'bw':{ 2000:{'desc':'T2.4','pc':'1075','price':0.060}, 1000:{'desc':'T2.3','pc':'1074','price':0.070}, 500 :{'desc':'T2.2','pc':'1073','price':0.080}, 0: {'desc':'T2.1','pc':'1072','price':0.120} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #LEGAL 'lgl':{ 'color':{ 4000:{'desc':'T3.5','pc':'1052','price':0.065}, 2000:{'desc':'T3.4','pc':'1051','price':0.070}, 1000:{'desc':'T3.3','pc':'1050','price':0.080}, 500: {'desc':'T3.2','pc':'1049','price':0.090}, 0: {'desc':'T3.1','pc':'1048','price':0.130} }, 'bw':{ 2000:{'desc':'T4.4','pc':'1075','price':0.010}, 1000:{'desc':'T4.3','pc':'1074','price':0.015}, 500 :{'desc':'T4.2','pc':'1073','price':0.020}, 0: {'desc':'T4.1','pc':'1072','price':0.030} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #TABLOID 'tab':{ 'color':{ 4000:{'desc':'T5.5','pc':'1060','price':0.075}, 2000:{'desc':'T5.4','pc':'1059','price':0.080}, 1000:{'desc':'T5.3','pc':'1058','price':0.090}, 500: {'desc':'T5.2','pc':'1057','price':0.100}, 0: {'desc':'T5.1','pc':'1056','price':0.140} }, 'bw':{ 2000:{'desc':'T6.4','pc':'1091','price':0.010}, 1000:{'desc':'T6.3','pc':'1090','price':0.015}, 500 :{'desc':'T6.2','pc':'1089','price':0.020}, 0: {'desc':'T6.1','pc':'1088','price':0.040} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #12x18 or 13x19 'ex':{ 'color':{ 4000:{'desc':'T7.5','pc':'1068','price':0.075}, 2000:{'desc':'T7.4','pc':'1067','price':0.080}, 1000:{'desc':'T7.3','pc':'1066','price':0.090}, 500: {'desc':'T7.2','pc':'1065','price':0.100}, 0: {'desc':'T7.1','pc':'1064','price':0.140} }, 'bw':{ 2000:{'desc':'T8.4','pc':'1099','price':0.010}, 1000:{'desc':'T8.3','pc':'1098','price':0.020}, 500 :{'desc':'T8.2','pc':'1097','price':0.030}, 0: {'desc':'T8.1','pc':'1096','price':0.050} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #WIDE FORMAT 'wf':{ 'color':{ 2: {'desc':'T9.2','pc':'1031','price':0.350}, 1: {'desc':'T9.1','pc':'1030','price':0.700} }, 'bw':{ 2 :{'desc':'T10.2','pc':'1021','price':0.130}, 1: {'desc':'T10.1','pc':'1020','price':0.130} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #UV 'uv':{ 'color':{ 2: {'desc':'T11.2','pc':'4401','price':0.200}, 1: {'desc':'T11.1','pc':'4400','price':0.100} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #DYE SUB 'ds':{ 'color':{ 3: {'desc':'T12.3','pc':'4902','price':1.000}, 2: {'desc':'T12.2','pc':'4901','price':0.750}, 1: {'desc':'T12.1','pc':'4900','price':0.500} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } }, #ENVELOPES 'env':{ 'color':{ 2: {'desc':'T13.2','pc':'4024','price':0.033}, 1: {'desc':'T13.1','pc':'4016','price':0.055} }, 'bw':{ 2 :{'desc':'T13.2','pc':'4018','price':0.019}, 1: {'desc':'T13.1','pc':'4017','price':0.030} }, 'none':{ 0: {'desc':'catchall','pc':'','price':0.2} } } } clicks = 0 cost = 0 descript = '' sides = lookup('ink') num_pages = float(pretty(lookup('num_pages'))) # modulus (%) is used to find if there's a blank page in the file by finding out if it's an odd number of pages), and to remove that from the click count if sides == "4/4": if num_pages%2 != 0: clicks = float(press_sheets()*2-qty) cb = "color" else: clicks = float(press_sheets()*2) cb = "color" elif sides == "1/1": if num_pages%2 != 0: clicks = float(press_sheets()*2-qty) cb = "bw" else: clicks = float(press_sheets()*2) cb = "bw" elif sides == "4/0": clicks = float(press_sheets()) cb = "color" elif sides == "1/0": clicks = float(press_sheets()) cb = "bw" elif sides == '0/0': clicks = float(press_sheets()) cb = "none" paper_size_x = env['snap']['paper']['what_kind_d_you_like3565']['width_inches'] paper_size_y = env['snap']['paper']['what_kind_d_you_like3565']['height_inches'] xp = paper_size_x yp = paper_size_y print_size = lookup('size') px = size_left(print_size) py = size_right(print_size) ########################## ## Small Format OPTIONS ## if type == 'sf': ##Find pricing teir for arrays if cb == 'color': if clicks >= 4000: active_teir = 4000 elif clicks >= 2000: active_teir = 2000 elif clicks >= 1000: active_teir = 1000 elif clicks >= 500: active_teir = 500 else: active_teir = 0 elif cb == 'bw': if clicks >= 2000: active_teir = 2000 elif clicks >= 1000: active_teir = 1000 elif clicks >= 500: active_teir = 500 else: active_teir = 0 elif cb == 'none': active_teir = 0 ##BUILD COST AND DESCRIPTION if xp == 8.5 and yp == 11 or xp == 11 and yp == 8.5: descript = pc_array['ltr'][cb][active_teir]['desc'] prod = pc_array['ltr'][cb][active_teir]['pc'] cost = pc_array['ltr'][cb][active_teir]['price'] elif xp == 8.5 and yp == 14 or xp == 14 and yp == 8.5: descript = pc_array['lgl'][cb][active_teir]['desc'] prod = pc_array['lgl'][cb][active_teir]['pc'] cost = pc_array['lgl'][cb][active_teir]['price'] elif xp == 11 and yp == 17 or xp == 17 and yp == 11: descript = pc_array['tab'][cb][active_teir]['desc'] prod = pc_array['tab'][cb][active_teir]['pc'] cost = pc_array['tab'][cb][active_teir]['price'] elif xp == 12 and yp == 18 or xp == 18 and yp == 12 or xp == 13 and yp == 19 or xp == 19 and yp == 13: descript = pc_array['ex'][cb][active_teir]['desc'] prod = pc_array['ex'][cb][active_teir]['pc'] cost = pc_array['ex'][cb][active_teir]['price'] elif xp > 13 and yp > 19 or xp > 19 and yp > 13: if qty > 1: sqft = ((px * py) / 144) * num_pages first_set = sqft * pc_array[type][cb][1]['price'] consec_set = ((qty - 1) * sqft) * pc_array[type][cb][2]['price'] cost = first_set + consec_set prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(' sqft:' + sqft) elif qty == 1: sqft = ((px * py) / 144) * num_pages cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqft:' + sqft) else: cost = 0 prod = '999' descript = "n/a" ######################### ## Wide Format OPTIONS ## elif type == "wf": if qty > 1: sqft = ((px * py) / 144) * num_pages first_set = sqft * pc_array[type][cb][1]['price'] consec_set = ((qty - 1) * sqft) * pc_array[type][cb][2]['price'] cost = first_set + consec_set prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(' sqft:' + sqft) elif qty == 1: sqft = ((px * py) / 144) * num_pages cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqft:' + sqft) else: cost = 0 prod = '999' descript = "n/a" ################ ## UV OPTIONS ## elif type == "uv": if int(paper) >= 4200 and int(paper) <= 4225: if qty > 1: sqin = ((px * py) * num_pages)*qty cost = qty * -0.50 prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) else: sqin = ((px * py) * num_pages)*qty cost = 0 prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) else: sqin = ((px * py) * num_pages)*qty cost = sqin * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) ###################### ## Envelope OPTIONS ## elif type == "env": if qty > 500: cost = qty * pc_array[type][cb][2]['price'] prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] else: cost = qty * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] #################### ## DyeSub OPTIONS ## elif type == "ds": sqft = (((px * py) / 144) * num_pages)*qty if sqft < 216: cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(" sqft:" + sqft) elif sqft < 144: cost = sqft * pc_array[type][cb][2]['price'] prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(" sqft:" + sqft) elif sqft < 72: cost = sqft * pc_array[type][cb][3]['price'] prod = pc_array[type][cb][3]['pc'] descript = pc_array[type][cb][3]['desc'] + str(" sqft:" + sqft) else: cost = 0 prod = '999' descript = str('none ') + str(" sqft:" + sqft) ###################################### ##FINAL PRINT OF DESCRIPTION AND PRICE ##THIS WORKS FOR EVERY PRODUCT TYPE ABOVE desc = descript + str(' ') + prod price = clicks * cost
type = 'sf' i = lookup('is_your_prack__white4030') env['ink'] = i paper = lookup('what_kind_d_you_like3565') pc_array = {'ltr': {'color': {4000: {'desc': 'T1.5', 'pc': '1044', 'price': 0.056}, 2000: {'desc': 'T1.4', 'pc': '1043', 'price': 0.06}, 1000: {'desc': 'T1.3', 'pc': '1042', 'price': 0.07}, 500: {'desc': 'T1.2', 'pc': '1041', 'price': 0.08}, 0: {'desc': 'T1.1', 'pc': '1040', 'price': 0.12}}, 'bw': {2000: {'desc': 'T2.4', 'pc': '1075', 'price': 0.06}, 1000: {'desc': 'T2.3', 'pc': '1074', 'price': 0.07}, 500: {'desc': 'T2.2', 'pc': '1073', 'price': 0.08}, 0: {'desc': 'T2.1', 'pc': '1072', 'price': 0.12}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'lgl': {'color': {4000: {'desc': 'T3.5', 'pc': '1052', 'price': 0.065}, 2000: {'desc': 'T3.4', 'pc': '1051', 'price': 0.07}, 1000: {'desc': 'T3.3', 'pc': '1050', 'price': 0.08}, 500: {'desc': 'T3.2', 'pc': '1049', 'price': 0.09}, 0: {'desc': 'T3.1', 'pc': '1048', 'price': 0.13}}, 'bw': {2000: {'desc': 'T4.4', 'pc': '1075', 'price': 0.01}, 1000: {'desc': 'T4.3', 'pc': '1074', 'price': 0.015}, 500: {'desc': 'T4.2', 'pc': '1073', 'price': 0.02}, 0: {'desc': 'T4.1', 'pc': '1072', 'price': 0.03}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'tab': {'color': {4000: {'desc': 'T5.5', 'pc': '1060', 'price': 0.075}, 2000: {'desc': 'T5.4', 'pc': '1059', 'price': 0.08}, 1000: {'desc': 'T5.3', 'pc': '1058', 'price': 0.09}, 500: {'desc': 'T5.2', 'pc': '1057', 'price': 0.1}, 0: {'desc': 'T5.1', 'pc': '1056', 'price': 0.14}}, 'bw': {2000: {'desc': 'T6.4', 'pc': '1091', 'price': 0.01}, 1000: {'desc': 'T6.3', 'pc': '1090', 'price': 0.015}, 500: {'desc': 'T6.2', 'pc': '1089', 'price': 0.02}, 0: {'desc': 'T6.1', 'pc': '1088', 'price': 0.04}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'ex': {'color': {4000: {'desc': 'T7.5', 'pc': '1068', 'price': 0.075}, 2000: {'desc': 'T7.4', 'pc': '1067', 'price': 0.08}, 1000: {'desc': 'T7.3', 'pc': '1066', 'price': 0.09}, 500: {'desc': 'T7.2', 'pc': '1065', 'price': 0.1}, 0: {'desc': 'T7.1', 'pc': '1064', 'price': 0.14}}, 'bw': {2000: {'desc': 'T8.4', 'pc': '1099', 'price': 0.01}, 1000: {'desc': 'T8.3', 'pc': '1098', 'price': 0.02}, 500: {'desc': 'T8.2', 'pc': '1097', 'price': 0.03}, 0: {'desc': 'T8.1', 'pc': '1096', 'price': 0.05}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'wf': {'color': {2: {'desc': 'T9.2', 'pc': '1031', 'price': 0.35}, 1: {'desc': 'T9.1', 'pc': '1030', 'price': 0.7}}, 'bw': {2: {'desc': 'T10.2', 'pc': '1021', 'price': 0.13}, 1: {'desc': 'T10.1', 'pc': '1020', 'price': 0.13}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'uv': {'color': {2: {'desc': 'T11.2', 'pc': '4401', 'price': 0.2}, 1: {'desc': 'T11.1', 'pc': '4400', 'price': 0.1}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'ds': {'color': {3: {'desc': 'T12.3', 'pc': '4902', 'price': 1.0}, 2: {'desc': 'T12.2', 'pc': '4901', 'price': 0.75}, 1: {'desc': 'T12.1', 'pc': '4900', 'price': 0.5}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}, 'env': {'color': {2: {'desc': 'T13.2', 'pc': '4024', 'price': 0.033}, 1: {'desc': 'T13.1', 'pc': '4016', 'price': 0.055}}, 'bw': {2: {'desc': 'T13.2', 'pc': '4018', 'price': 0.019}, 1: {'desc': 'T13.1', 'pc': '4017', 'price': 0.03}}, 'none': {0: {'desc': 'catchall', 'pc': '', 'price': 0.2}}}} clicks = 0 cost = 0 descript = '' sides = lookup('ink') num_pages = float(pretty(lookup('num_pages'))) if sides == '4/4': if num_pages % 2 != 0: clicks = float(press_sheets() * 2 - qty) cb = 'color' else: clicks = float(press_sheets() * 2) cb = 'color' elif sides == '1/1': if num_pages % 2 != 0: clicks = float(press_sheets() * 2 - qty) cb = 'bw' else: clicks = float(press_sheets() * 2) cb = 'bw' elif sides == '4/0': clicks = float(press_sheets()) cb = 'color' elif sides == '1/0': clicks = float(press_sheets()) cb = 'bw' elif sides == '0/0': clicks = float(press_sheets()) cb = 'none' paper_size_x = env['snap']['paper']['what_kind_d_you_like3565']['width_inches'] paper_size_y = env['snap']['paper']['what_kind_d_you_like3565']['height_inches'] xp = paper_size_x yp = paper_size_y print_size = lookup('size') px = size_left(print_size) py = size_right(print_size) if type == 'sf': if cb == 'color': if clicks >= 4000: active_teir = 4000 elif clicks >= 2000: active_teir = 2000 elif clicks >= 1000: active_teir = 1000 elif clicks >= 500: active_teir = 500 else: active_teir = 0 elif cb == 'bw': if clicks >= 2000: active_teir = 2000 elif clicks >= 1000: active_teir = 1000 elif clicks >= 500: active_teir = 500 else: active_teir = 0 elif cb == 'none': active_teir = 0 if xp == 8.5 and yp == 11 or (xp == 11 and yp == 8.5): descript = pc_array['ltr'][cb][active_teir]['desc'] prod = pc_array['ltr'][cb][active_teir]['pc'] cost = pc_array['ltr'][cb][active_teir]['price'] elif xp == 8.5 and yp == 14 or (xp == 14 and yp == 8.5): descript = pc_array['lgl'][cb][active_teir]['desc'] prod = pc_array['lgl'][cb][active_teir]['pc'] cost = pc_array['lgl'][cb][active_teir]['price'] elif xp == 11 and yp == 17 or (xp == 17 and yp == 11): descript = pc_array['tab'][cb][active_teir]['desc'] prod = pc_array['tab'][cb][active_teir]['pc'] cost = pc_array['tab'][cb][active_teir]['price'] elif xp == 12 and yp == 18 or (xp == 18 and yp == 12) or (xp == 13 and yp == 19) or (xp == 19 and yp == 13): descript = pc_array['ex'][cb][active_teir]['desc'] prod = pc_array['ex'][cb][active_teir]['pc'] cost = pc_array['ex'][cb][active_teir]['price'] elif xp > 13 and yp > 19 or (xp > 19 and yp > 13): if qty > 1: sqft = px * py / 144 * num_pages first_set = sqft * pc_array[type][cb][1]['price'] consec_set = (qty - 1) * sqft * pc_array[type][cb][2]['price'] cost = first_set + consec_set prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(' sqft:' + sqft) elif qty == 1: sqft = px * py / 144 * num_pages cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqft:' + sqft) else: cost = 0 prod = '999' descript = 'n/a' elif type == 'wf': if qty > 1: sqft = px * py / 144 * num_pages first_set = sqft * pc_array[type][cb][1]['price'] consec_set = (qty - 1) * sqft * pc_array[type][cb][2]['price'] cost = first_set + consec_set prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(' sqft:' + sqft) elif qty == 1: sqft = px * py / 144 * num_pages cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqft:' + sqft) else: cost = 0 prod = '999' descript = 'n/a' elif type == 'uv': if int(paper) >= 4200 and int(paper) <= 4225: if qty > 1: sqin = px * py * num_pages * qty cost = qty * -0.5 prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) else: sqin = px * py * num_pages * qty cost = 0 prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) else: sqin = px * py * num_pages * qty cost = sqin * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqin:' + sqin) elif type == 'env': if qty > 500: cost = qty * pc_array[type][cb][2]['price'] prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] else: cost = qty * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] elif type == 'ds': sqft = px * py / 144 * num_pages * qty if sqft < 216: cost = sqft * pc_array[type][cb][1]['price'] prod = pc_array[type][cb][1]['pc'] descript = pc_array[type][cb][1]['desc'] + str(' sqft:' + sqft) elif sqft < 144: cost = sqft * pc_array[type][cb][2]['price'] prod = pc_array[type][cb][2]['pc'] descript = pc_array[type][cb][2]['desc'] + str(' sqft:' + sqft) elif sqft < 72: cost = sqft * pc_array[type][cb][3]['price'] prod = pc_array[type][cb][3]['pc'] descript = pc_array[type][cb][3]['desc'] + str(' sqft:' + sqft) else: cost = 0 prod = '999' descript = str('none ') + str(' sqft:' + sqft) desc = descript + str(' ') + prod price = clicks * cost
driver = webdriver.Chrome(executable_path="./chromedriver.exe") driver.get("http://www.baidu.com") searchInput = driver.find_element_by_id('kw') searchInput.send_keys("helloworld") driver.quit()
driver = webdriver.Chrome(executable_path='./chromedriver.exe') driver.get('http://www.baidu.com') search_input = driver.find_element_by_id('kw') searchInput.send_keys('helloworld') driver.quit()
#program to add the digits of a positive integer repeatedly until the result has a single digit. def add_digits(num): return (num - 1) % 9 + 1 if num > 0 else 0 print(add_digits(48)) print(add_digits(59))
def add_digits(num): return (num - 1) % 9 + 1 if num > 0 else 0 print(add_digits(48)) print(add_digits(59))
class WorldInfo: def __init__(self, arg): self.name = arg['name'] self.info = None self.mappings = None self.interact = None
class Worldinfo: def __init__(self, arg): self.name = arg['name'] self.info = None self.mappings = None self.interact = None
S = { 'b' : 'boxes?q=' } D = { 'bI' : 'boxId', 'bN' : 'boxName', 'iMB' : 'isMasterBox', 'cI' : 'categoryId', 'cN' : 'categoryName', 'cFN' : 'categoryFriendlyName', 'sCI' : 'superCatId', 'sCN' : 'superCatName', 'sCFN' : 'superCatFriendlyName', 'cB' : 'cannotBuy', 'iNB' : 'isNewBox', 'sP' : 'sellPrice', 'cP' : 'cashPrice', 'eP' : 'exchangePrice', 'bR' : 'boxRating', 'oOS' : 'outOfStock', 'oOES' : 'outOfEcomStock' }
s = {'b': 'boxes?q='} d = {'bI': 'boxId', 'bN': 'boxName', 'iMB': 'isMasterBox', 'cI': 'categoryId', 'cN': 'categoryName', 'cFN': 'categoryFriendlyName', 'sCI': 'superCatId', 'sCN': 'superCatName', 'sCFN': 'superCatFriendlyName', 'cB': 'cannotBuy', 'iNB': 'isNewBox', 'sP': 'sellPrice', 'cP': 'cashPrice', 'eP': 'exchangePrice', 'bR': 'boxRating', 'oOS': 'outOfStock', 'oOES': 'outOfEcomStock'}
{ 'targets': [ { 'target_name': '<(module_name)', 'sources': [ 'src/node_libcurl.cc', 'src/Easy.cc', 'src/Share.cc', 'src/Multi.cc', 'src/Curl.cc', 'src/CurlHttpPost.cc' ], 'include_dirs' : [ "<!(node -e \"require('nan')\")" ], 'conditions': [ ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { # 4506 and 4838 -> about v8 inline function and narrowing # 4996 -> Declared wrongly Nan::Callback::Call 'DisableSpecificWarnings': ['4506', '4838', '4996'] } }, 'configurations' : { 'Release': { 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': '1', 'Optimization': 2, # /O2 safe optimization 'FavorSizeOrSpeed': 1, # /Ot, favour speed over size 'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible 'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG 'OmitFramePointers': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'WarnAsError': 'true' } } }, 'Debug': { 'msvs_settings': { 'VCCLCompilerTool': { 'WarnAsError': 'false' } } } }, 'dependencies': [ '<!@(node "<(module_root_dir)/tools/retrieve-win-deps.js")' ], 'defines' : [ 'CURL_STATICLIB' ] }, { # OS != "win" 'cflags_cc' : [ '-std=c++11', '-O2', '-Wno-narrowing', '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)', ], # enable exceptions, remove level 3 optimization 'cflags_cc!': [ '-fno-exceptions', '-O3' ], 'xcode_settings': { 'OTHER_CPLUSPLUSFLAGS':[ '-std=c++11','-stdlib=libc++', '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)', ], 'OTHER_CFLAGS':[ '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)' ], 'OTHER_LDFLAGS':[ '-Wl,-bind_at_load', '-stdlib=libc++' ], 'GCC_ENABLE_CPP_RTTI': 'YES', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'MACOSX_DEPLOYMENT_TARGET':'10.8', 'CLANG_CXX_LIBRARY': 'libc++', 'CLANG_CXX_LANGUAGE_STANDARD':'c++11', 'OTHER_LDFLAGS': ['-stdlib=libc++'], 'WARNING_CFLAGS':[ '-Wno-c++11-narrowing', '-Wno-constant-conversion' ] }, 'include_dirs' : [ '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags | sed s/-I//g)' ], 'libraries': [ '<!@(node "<(module_root_dir)/tools/curl-config.js" --libs)' ] }] ] }, { 'target_name': 'action_after_build', 'type': 'none', 'dependencies': [ '<(module_name)' ], 'copies': [ { 'files': [ '<(PRODUCT_DIR)/<(module_name).node' ], 'destination': '<(module_path)' } ] } ] }
{'targets': [{'target_name': '<(module_name)', 'sources': ['src/node_libcurl.cc', 'src/Easy.cc', 'src/Share.cc', 'src/Multi.cc', 'src/Curl.cc', 'src/CurlHttpPost.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'DisableSpecificWarnings': ['4506', '4838', '4996']}}, 'configurations': {'Release': {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': '1', 'Optimization': 2, 'FavorSizeOrSpeed': 1, 'InlineFunctionExpansion': 2, 'WholeProgramOptimization': 'true', 'OmitFramePointers': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'WarnAsError': 'true'}}}, 'Debug': {'msvs_settings': {'VCCLCompilerTool': {'WarnAsError': 'false'}}}}, 'dependencies': ['<!@(node "<(module_root_dir)/tools/retrieve-win-deps.js")'], 'defines': ['CURL_STATICLIB']}, {'cflags_cc': ['-std=c++11', '-O2', '-Wno-narrowing', '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)'], 'cflags_cc!': ['-fno-exceptions', '-O3'], 'xcode_settings': {'OTHER_CPLUSPLUSFLAGS': ['-std=c++11', '-stdlib=libc++', '<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)'], 'OTHER_CFLAGS': ['<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags)'], 'OTHER_LDFLAGS': ['-Wl,-bind_at_load', '-stdlib=libc++'], 'GCC_ENABLE_CPP_RTTI': 'YES', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'MACOSX_DEPLOYMENT_TARGET': '10.8', 'CLANG_CXX_LIBRARY': 'libc++', 'CLANG_CXX_LANGUAGE_STANDARD': 'c++11', 'OTHER_LDFLAGS': ['-stdlib=libc++'], 'WARNING_CFLAGS': ['-Wno-c++11-narrowing', '-Wno-constant-conversion']}, 'include_dirs': ['<!@(node "<(module_root_dir)/tools/curl-config.js" --cflags | sed s/-I//g)'], 'libraries': ['<!@(node "<(module_root_dir)/tools/curl-config.js" --libs)']}]]}, {'target_name': 'action_after_build', 'type': 'none', 'dependencies': ['<(module_name)'], 'copies': [{'files': ['<(PRODUCT_DIR)/<(module_name).node'], 'destination': '<(module_path)'}]}]}
#!/usr/bin/python # substrings2.py a = "I saw a wolf in the forest. A lone wolf." print (a.index("wolf")) print (a.rindex("wolf")) try: print (a.rindex("fox")) except ValueError as e: print ("Could not find substring")
a = 'I saw a wolf in the forest. A lone wolf.' print(a.index('wolf')) print(a.rindex('wolf')) try: print(a.rindex('fox')) except ValueError as e: print('Could not find substring')
operacao = str(input()) soma = media = contador = 0 matriz = [[], [], [], [], [], [], [], [], [], [], [], []] for linha in range(0, 12): for coluna in range(0, 12): n = float(input()) matriz[linha].append(n) for linha in range(0, 12): for coluna in range(0, 12): if coluna > 11 - linha: soma += matriz[coluna][linha] contador += 1 if operacao in "S": print(f"{soma:.1f}") else: print(f"{soma / contador:.1f}")
operacao = str(input()) soma = media = contador = 0 matriz = [[], [], [], [], [], [], [], [], [], [], [], []] for linha in range(0, 12): for coluna in range(0, 12): n = float(input()) matriz[linha].append(n) for linha in range(0, 12): for coluna in range(0, 12): if coluna > 11 - linha: soma += matriz[coluna][linha] contador += 1 if operacao in 'S': print(f'{soma:.1f}') else: print(f'{soma / contador:.1f}')
class InvalidNibbles(Exception): pass class InvalidNode(Exception): pass class ValidationError(Exception): pass class BadTrieProof(Exception): pass class NodeOverrideError(Exception): pass class InvalidKeyError(Exception): pass class SyncRequestAlreadyProcessed(Exception): pass
class Invalidnibbles(Exception): pass class Invalidnode(Exception): pass class Validationerror(Exception): pass class Badtrieproof(Exception): pass class Nodeoverrideerror(Exception): pass class Invalidkeyerror(Exception): pass class Syncrequestalreadyprocessed(Exception): pass
class fifth(): def showclass(self): self.name="hira" print(self.name) class ninth(fifth): def showclass(self): self.name="khira" print(self.name) print("after reset") super().showclass() st1=fifth() st2=ninth() st2.showclass()
class Fifth: def showclass(self): self.name = 'hira' print(self.name) class Ninth(fifth): def showclass(self): self.name = 'khira' print(self.name) print('after reset') super().showclass() st1 = fifth() st2 = ninth() st2.showclass()
#=========================filter=========================== # def isodd(x): # return x%2==0 # for x in filter(isodd, range(10)): # print(x) #===============practice================ #1. find the even number from 1 - 20 by using filter even=[x for x in filter(lambda x: x%2==0, range(1,21))] print (even) #2. find the prime number from 1-100 by using filter def isprime(x): if x<=1: return False for k in range(2,x): if x%k==0: return False return True prime=list(filter(isprime, range(100))) print(prime) #=========================sorted=========================== # L=[5,-1,-4,0,3,1] # L2=sorted(L) # L3=sorted(L,reverse=True) # L4=sorted(L,key=abs) # print("L2: ", L2) # print("L3: ", L3) # print("L4: ", L4) #===============practice================ names=['Ethan', 'Phoebe', 'David','Kyle','Emily'] names2=sorted(names) names3=sorted(names,key=len) print(names3)
even = [x for x in filter(lambda x: x % 2 == 0, range(1, 21))] print(even) def isprime(x): if x <= 1: return False for k in range(2, x): if x % k == 0: return False return True prime = list(filter(isprime, range(100))) print(prime) names = ['Ethan', 'Phoebe', 'David', 'Kyle', 'Emily'] names2 = sorted(names) names3 = sorted(names, key=len) print(names3)
def truncate_fields(obj): for key, val in obj.iteritems(): if isinstance(val, dict): obj[key] = truncate_fields(val) elif isinstance(val, (list, tuple, )): idx = -1 for subval in val: idx += 1 obj[key][idx] = truncate_fields(subval) elif isinstance(val, (str, unicode)) and key not in ['content', 'text']: obj[key] = val[:225] return obj
def truncate_fields(obj): for (key, val) in obj.iteritems(): if isinstance(val, dict): obj[key] = truncate_fields(val) elif isinstance(val, (list, tuple)): idx = -1 for subval in val: idx += 1 obj[key][idx] = truncate_fields(subval) elif isinstance(val, (str, unicode)) and key not in ['content', 'text']: obj[key] = val[:225] return obj
class Maze: class Node: def __init__(self, position): self.Position = position self.Neighbours = [None, None, None, None] #self.Weights = [0, 0, 0, 0] def __init__(self, im): width = im.width height = im.height data = list(im.getdata(0)) self.start = None self.end = None # Top row buffer topnodes = [None] * width count = 0 # Start row for x in range (1, width - 1): if data[x] > 0: self.start = Maze.Node((0,x)) topnodes[x] = self.start count += 1 break for y in range (1, height - 1): #print ("row", str(y)) # Uncomment this line to keep a track of row progress rowoffset = y * width rowaboveoffset = rowoffset - width rowbelowoffset = rowoffset + width # Initialise previous, current and next values prv = False cur = False nxt = data[rowoffset + 1] > 0 leftnode = None for x in range (1, width - 1): # Move prev, current and next onwards. This way we read from the image once per pixel, marginal optimisation prv = cur cur = nxt nxt = data[rowoffset + x + 1] > 0 n = None if cur == False: # ON WALL - No action continue if prv == True: if nxt == True: # PATH PATH PATH # Create node only if paths above or below if data[rowaboveoffset + x] > 0 or data[rowbelowoffset + x] > 0: n = Maze.Node((y,x)) leftnode.Neighbours[1] = n n.Neighbours[3] = leftnode leftnode = n else: # PATH PATH WALL # Create path at end of corridor n = Maze.Node((y,x)) leftnode.Neighbours[1] = n n.Neighbours[3] = leftnode leftnode = None else: if nxt == True: # WALL PATH PATH # Create path at start of corridor n = Maze.Node((y,x)) leftnode = n else: # WALL PATH WALL # Create node only if in dead end if (data[rowaboveoffset + x] == 0) or (data[rowbelowoffset + x] == 0): #print ("Create Node in dead end") n = Maze.Node((y,x)) # If node isn't none, we can assume we can connect N-S somewhere if n != None: # Clear above, connect to waiting top node if (data[rowaboveoffset + x] > 0): t = topnodes[x] t.Neighbours[2] = n n.Neighbours[0] = t # If clear below, put this new node in the top row for the next connection if (data[rowbelowoffset + x] > 0): topnodes[x] = n else: topnodes[x] = None count += 1 # End row rowoffset = (height - 1) * width for x in range (1, width - 1): if data[rowoffset + x] > 0: self.end = Maze.Node((height - 1,x)) t = topnodes[x] t.Neighbours[2] = self.end self.end.Neighbours[0] = t count += 1 break self.count = count self.width = width self.height = height
class Maze: class Node: def __init__(self, position): self.Position = position self.Neighbours = [None, None, None, None] def __init__(self, im): width = im.width height = im.height data = list(im.getdata(0)) self.start = None self.end = None topnodes = [None] * width count = 0 for x in range(1, width - 1): if data[x] > 0: self.start = Maze.Node((0, x)) topnodes[x] = self.start count += 1 break for y in range(1, height - 1): rowoffset = y * width rowaboveoffset = rowoffset - width rowbelowoffset = rowoffset + width prv = False cur = False nxt = data[rowoffset + 1] > 0 leftnode = None for x in range(1, width - 1): prv = cur cur = nxt nxt = data[rowoffset + x + 1] > 0 n = None if cur == False: continue if prv == True: if nxt == True: if data[rowaboveoffset + x] > 0 or data[rowbelowoffset + x] > 0: n = Maze.Node((y, x)) leftnode.Neighbours[1] = n n.Neighbours[3] = leftnode leftnode = n else: n = Maze.Node((y, x)) leftnode.Neighbours[1] = n n.Neighbours[3] = leftnode leftnode = None elif nxt == True: n = Maze.Node((y, x)) leftnode = n elif data[rowaboveoffset + x] == 0 or data[rowbelowoffset + x] == 0: n = Maze.Node((y, x)) if n != None: if data[rowaboveoffset + x] > 0: t = topnodes[x] t.Neighbours[2] = n n.Neighbours[0] = t if data[rowbelowoffset + x] > 0: topnodes[x] = n else: topnodes[x] = None count += 1 rowoffset = (height - 1) * width for x in range(1, width - 1): if data[rowoffset + x] > 0: self.end = Maze.Node((height - 1, x)) t = topnodes[x] t.Neighbours[2] = self.end self.end.Neighbours[0] = t count += 1 break self.count = count self.width = width self.height = height
''' There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 ''' def BinarySearch(nums, target): if not nums: return -1 n = len(nums) l, r = 0, n-1 while l <= r: mid = (l+r)//2 if nums[mid] == target: return mid elif nums[mid] < nums[r]: if nums[mid] <= target <= nums[r]: l = mid+1 else: r = mid-1 else: if nums[l] <= target < nums[mid]: r = mid-1 else: l = mid+1 return -1
""" There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ def binary_search(nums, target): if not nums: return -1 n = len(nums) (l, r) = (0, n - 1) while l <= r: mid = (l + r) // 2 if nums[mid] == target: return mid elif nums[mid] < nums[r]: if nums[mid] <= target <= nums[r]: l = mid + 1 else: r = mid - 1 elif nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 return -1
def test_h1_css(self): self.browser.get('http://localhost:8000') h1 = self.browser.find_element_by_tag_name("h1") print (h1.value_of_css_property("color")) self.assertEqual(h1.value_of_css_property("color"), "rgb(255, 192, 203)")
def test_h1_css(self): self.browser.get('http://localhost:8000') h1 = self.browser.find_element_by_tag_name('h1') print(h1.value_of_css_property('color')) self.assertEqual(h1.value_of_css_property('color'), 'rgb(255, 192, 203)')
def fibonacci(sequence_length): "Return the Fibonacci sequence of length *sequence_length*" sequence = [0,1] if sequence_length < 1: print("Fibonacci sequence only defined for length 1 or greater") return elif sequence_length >=3: for i in range(2,sequence_length): sequence=sequence+[sequence[i-1]+sequence[i-2]] return sequence def factorial(n): "Return the factorial of number *n*" num = 1 while n >= 1: num = num * n n = n - 1 return num
def fibonacci(sequence_length): """Return the Fibonacci sequence of length *sequence_length*""" sequence = [0, 1] if sequence_length < 1: print('Fibonacci sequence only defined for length 1 or greater') return elif sequence_length >= 3: for i in range(2, sequence_length): sequence = sequence + [sequence[i - 1] + sequence[i - 2]] return sequence def factorial(n): """Return the factorial of number *n*""" num = 1 while n >= 1: num = num * n n = n - 1 return num
# This file is generated by sync-deps, do not edit! load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def default_github_callback(name, repository, commit, sha256): repo_name = repository.split("/")[-1] _maybe( http_archive, name = name, sha256 = sha256, strip_prefix = "%s-%s" % (repo_name, commit), urls = ["https://github.com/%s/archive/%s.zip" % (repository, commit)], ) def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def default_github_callback(name, repository, commit, sha256): repo_name = repository.split('/')[-1] _maybe(http_archive, name=name, sha256=sha256, strip_prefix='%s-%s' % (repo_name, commit), urls=['https://github.com/%s/archive/%s.zip' % (repository, commit)]) def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name=name, **kwargs)
a=input("Enter the string:") a=list(a) count=0 for i in a: count+=1 print("The length is:",count)
a = input('Enter the string:') a = list(a) count = 0 for i in a: count += 1 print('The length is:', count)
''' Deleting specific records By using a where() clause, you can target the delete statement to remove only certain records. For example, Jason deleted all columns from the employees table that had id 3 with the following delete statement: delete(employees).where(employees.columns.id == 3) Here you'll delete ALL rows which have 'M' in the sex column and 36 in the age column. We have included code at the start which computes the total number of these rows. It is important to make sure that this is the number of rows that you actually delete. INSTRUCTIONS 0XP INSTRUCTIONS 0XP Build a delete statement to remove data from the census table. Save it as stmt_del. Append a where clause to stmt_del that contains an and_ to filter for rows which have 'M' in the sex column AND 36 in the age column. Execute the delete statement. Hit 'Submit Answer' to print the rowcount of the results, as well as to_delete, which returns the number of rows that should be deleted. These should match and this is an important sanity check! ''' # Build a statement to count records using the sex column for Men (M) age 36: stmt stmt = select([func.count(census.columns.sex)]).where( and_(census.columns.sex == 'M', census.columns.age == 36) ) # Execute the select statement and use the scalar() fetch method to save the record count to_delete = connection.execute(stmt).scalar() # Build a statement to delete records for Men (M) age 36: stmt stmt_del = delete(census) # Append a where clause to target man age 36 stmt_del = stmt_del.where( and_(census.columns.sex == 'M', census.columns.age == 36) ) # Execute the statement: results results = connection.execute(stmt_del) # Print affected rowcount and to_delete record count, make sure they match print(results.rowcount, to_delete)
""" Deleting specific records By using a where() clause, you can target the delete statement to remove only certain records. For example, Jason deleted all columns from the employees table that had id 3 with the following delete statement: delete(employees).where(employees.columns.id == 3) Here you'll delete ALL rows which have 'M' in the sex column and 36 in the age column. We have included code at the start which computes the total number of these rows. It is important to make sure that this is the number of rows that you actually delete. INSTRUCTIONS 0XP INSTRUCTIONS 0XP Build a delete statement to remove data from the census table. Save it as stmt_del. Append a where clause to stmt_del that contains an and_ to filter for rows which have 'M' in the sex column AND 36 in the age column. Execute the delete statement. Hit 'Submit Answer' to print the rowcount of the results, as well as to_delete, which returns the number of rows that should be deleted. These should match and this is an important sanity check! """ stmt = select([func.count(census.columns.sex)]).where(and_(census.columns.sex == 'M', census.columns.age == 36)) to_delete = connection.execute(stmt).scalar() stmt_del = delete(census) stmt_del = stmt_del.where(and_(census.columns.sex == 'M', census.columns.age == 36)) results = connection.execute(stmt_del) print(results.rowcount, to_delete)
# # PySNMP MIB module TPLINK-pppoeConfig-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-pppoeConfig-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:18:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, NotificationType, ObjectIdentity, iso, MibIdentifier, Gauge32, Counter32, Bits, ModuleIdentity, Counter64, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "NotificationType", "ObjectIdentity", "iso", "MibIdentifier", "Gauge32", "Counter32", "Bits", "ModuleIdentity", "Counter64", "TimeTicks", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt") tplinkPPPoEConfigMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 57)) tplinkPPPoEConfigMIB.setRevisions(('2012-12-17 10:50',)) if mibBuilder.loadTexts: tplinkPPPoEConfigMIB.setLastUpdated('201212171050Z') if mibBuilder.loadTexts: tplinkPPPoEConfigMIB.setOrganization('TPLINK') tplinkPPPoEConfigMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1)) tplinkPPPoEConfigNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 2)) tpPppoeIdInsertionGlobalConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 1)) tpPppoeIdInsertionGlobalEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tpPppoeIdInsertionGlobalEnable.setStatus('current') tpPppoeIdInsertionPortConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2)) tpPppoeIdInsertionPortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1), ) if mibBuilder.loadTexts: tpPppoeIdInsertionPortConfigTable.setStatus('current') tpPppoeIdInsertionPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: tpPppoeIdInsertionPortConfigEntry.setStatus('current') tpPppoeIdInsertionPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPppoeIdInsertionPortIndex.setStatus('current') tpPppoeCircuitIdPortConfigEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigEnable.setStatus('current') tpPppoeCircuitIdPortConfigIdType = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("switchIp", 0), ("switchMac", 1), ("switchUdf", 2), ("switchUdfOnly", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigIdType.setStatus('current') tpPppoeCircuitIdPortConfigUdfValue = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 40))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigUdfValue.setStatus('current') tpPppoeRemoteIdPortConfigEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tpPppoeRemoteIdPortConfigEnable.setStatus('current') tpPppoeRemoteIdPortConfigValue = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 40))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPppoeRemoteIdPortConfigValue.setStatus('current') mibBuilder.exportSymbols("TPLINK-pppoeConfig-MIB", tpPppoeIdInsertionGlobalEnable=tpPppoeIdInsertionGlobalEnable, tpPppoeRemoteIdPortConfigValue=tpPppoeRemoteIdPortConfigValue, tpPppoeRemoteIdPortConfigEnable=tpPppoeRemoteIdPortConfigEnable, PYSNMP_MODULE_ID=tplinkPPPoEConfigMIB, tpPppoeCircuitIdPortConfigUdfValue=tpPppoeCircuitIdPortConfigUdfValue, tpPppoeIdInsertionPortConfig=tpPppoeIdInsertionPortConfig, tpPppoeCircuitIdPortConfigEnable=tpPppoeCircuitIdPortConfigEnable, tpPppoeCircuitIdPortConfigIdType=tpPppoeCircuitIdPortConfigIdType, tpPppoeIdInsertionPortIndex=tpPppoeIdInsertionPortIndex, tpPppoeIdInsertionPortConfigTable=tpPppoeIdInsertionPortConfigTable, tplinkPPPoEConfigNotifications=tplinkPPPoEConfigNotifications, tplinkPPPoEConfigMIBObjects=tplinkPPPoEConfigMIBObjects, tpPppoeIdInsertionPortConfigEntry=tpPppoeIdInsertionPortConfigEntry, tplinkPPPoEConfigMIB=tplinkPPPoEConfigMIB, tpPppoeIdInsertionGlobalConfig=tpPppoeIdInsertionGlobalConfig)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, notification_type, object_identity, iso, mib_identifier, gauge32, counter32, bits, module_identity, counter64, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'NotificationType', 'ObjectIdentity', 'iso', 'MibIdentifier', 'Gauge32', 'Counter32', 'Bits', 'ModuleIdentity', 'Counter64', 'TimeTicks', 'Integer32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (tplink_mgmt,) = mibBuilder.importSymbols('TPLINK-MIB', 'tplinkMgmt') tplink_pp_po_e_config_mib = module_identity((1, 3, 6, 1, 4, 1, 11863, 6, 57)) tplinkPPPoEConfigMIB.setRevisions(('2012-12-17 10:50',)) if mibBuilder.loadTexts: tplinkPPPoEConfigMIB.setLastUpdated('201212171050Z') if mibBuilder.loadTexts: tplinkPPPoEConfigMIB.setOrganization('TPLINK') tplink_pp_po_e_config_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1)) tplink_pp_po_e_config_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 2)) tp_pppoe_id_insertion_global_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 1)) tp_pppoe_id_insertion_global_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: tpPppoeIdInsertionGlobalEnable.setStatus('current') tp_pppoe_id_insertion_port_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2)) tp_pppoe_id_insertion_port_config_table = mib_table((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1)) if mibBuilder.loadTexts: tpPppoeIdInsertionPortConfigTable.setStatus('current') tp_pppoe_id_insertion_port_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: tpPppoeIdInsertionPortConfigEntry.setStatus('current') tp_pppoe_id_insertion_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: tpPppoeIdInsertionPortIndex.setStatus('current') tp_pppoe_circuit_id_port_config_enable = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigEnable.setStatus('current') tp_pppoe_circuit_id_port_config_id_type = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('switchIp', 0), ('switchMac', 1), ('switchUdf', 2), ('switchUdfOnly', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigIdType.setStatus('current') tp_pppoe_circuit_id_port_config_udf_value = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(0, 40))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPppoeCircuitIdPortConfigUdfValue.setStatus('current') tp_pppoe_remote_id_port_config_enable = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: tpPppoeRemoteIdPortConfigEnable.setStatus('current') tp_pppoe_remote_id_port_config_value = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 57, 1, 2, 1, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 40))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPppoeRemoteIdPortConfigValue.setStatus('current') mibBuilder.exportSymbols('TPLINK-pppoeConfig-MIB', tpPppoeIdInsertionGlobalEnable=tpPppoeIdInsertionGlobalEnable, tpPppoeRemoteIdPortConfigValue=tpPppoeRemoteIdPortConfigValue, tpPppoeRemoteIdPortConfigEnable=tpPppoeRemoteIdPortConfigEnable, PYSNMP_MODULE_ID=tplinkPPPoEConfigMIB, tpPppoeCircuitIdPortConfigUdfValue=tpPppoeCircuitIdPortConfigUdfValue, tpPppoeIdInsertionPortConfig=tpPppoeIdInsertionPortConfig, tpPppoeCircuitIdPortConfigEnable=tpPppoeCircuitIdPortConfigEnable, tpPppoeCircuitIdPortConfigIdType=tpPppoeCircuitIdPortConfigIdType, tpPppoeIdInsertionPortIndex=tpPppoeIdInsertionPortIndex, tpPppoeIdInsertionPortConfigTable=tpPppoeIdInsertionPortConfigTable, tplinkPPPoEConfigNotifications=tplinkPPPoEConfigNotifications, tplinkPPPoEConfigMIBObjects=tplinkPPPoEConfigMIBObjects, tpPppoeIdInsertionPortConfigEntry=tpPppoeIdInsertionPortConfigEntry, tplinkPPPoEConfigMIB=tplinkPPPoEConfigMIB, tpPppoeIdInsertionGlobalConfig=tpPppoeIdInsertionGlobalConfig)
#!/usr/bin/python def log(self,string): print(str(self.__class__.__name__)+": "+str(string))
def log(self, string): print(str(self.__class__.__name__) + ': ' + str(string))
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Blender_01_ape.py" OUTPUT_DIR = "output/deepim/lmCropBlenderSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmCropBlender_SO/duck" DATASETS = dict(TRAIN=("lm_blender_duck_train",), TEST=("lm_crop_duck_test",)) # bbnc9 # iter0 # objects duck Avg(1) # ad_2 0.00 0.00 # ad_5 0.00 0.00 # ad_10 0.40 0.40 # rete_2 0.80 0.80 # rete_5 11.16 11.16 # rete_10 25.90 25.90 # re_2 3.59 3.59 # re_5 17.13 17.13 # re_10 32.67 32.67 # te_2 0.80 0.80 # te_5 15.54 15.54 # te_10 28.69 28.69 # proj_2 0.80 0.80 # proj_5 24.30 24.30 # proj_10 43.82 43.82 # re 39.39 39.39 # te 0.24 0.24 # iter4 # objects duck Avg(1) # ad_2 3.19 3.19 # ad_5 13.55 13.55 # ad_10 30.28 30.28 # rete_2 20.32 20.32 # rete_5 53.78 53.78 # rete_10 65.34 65.34 # re_2 21.12 21.12 # re_5 56.18 56.18 # re_10 65.34 65.34 # te_2 52.99 52.99 # te_5 62.15 62.15 # te_10 70.92 70.92 # proj_2 49.80 49.80 # proj_5 65.34 65.34 # proj_10 71.71 71.71 # re 32.32 32.32 # te 0.10 0.10
_base_ = './FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Blender_01_ape.py' output_dir = 'output/deepim/lmCropBlenderSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmCropBlender_SO/duck' datasets = dict(TRAIN=('lm_blender_duck_train',), TEST=('lm_crop_duck_test',))
infile='VisDrone2019-DET-val/val.txt' outfile='visdrone_val.txt' with open(outfile,'w') as w: with open(infile,'r') as r: filelist=r.readlines() for line in filelist: new_line=line.split('.')[0] w.write(new_line+'\n')
infile = 'VisDrone2019-DET-val/val.txt' outfile = 'visdrone_val.txt' with open(outfile, 'w') as w: with open(infile, 'r') as r: filelist = r.readlines() for line in filelist: new_line = line.split('.')[0] w.write(new_line + '\n')
class AssemblySimulatorVMConfigException(Exception): def __str__(self): return "[ERROR] Error: AssemblySimulatorConfigError, Response: {0}".format(super().__str__())
class Assemblysimulatorvmconfigexception(Exception): def __str__(self): return '[ERROR] Error: AssemblySimulatorConfigError, Response: {0}'.format(super().__str__())
def write_name_delbertina(input_turtle): # d input_turtle.right(90) input_turtle.forward(50) input_turtle.left(90) input_turtle.pendown() input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(50) input_turtle.left(180) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) # e input_turtle.left(90) input_turtle.pendown() input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(10) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) # l input_turtle.pendown() input_turtle.left(90) input_turtle.forward(40) input_turtle.left(180) input_turtle.forward(40) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) # b input_turtle.pendown() input_turtle.left(90) input_turtle.forward(50) input_turtle.left(180) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(180) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) # e input_turtle.left(90) input_turtle.pendown() input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(10) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) # r input_turtle.pendown() input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.right(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(10) # t input_turtle.pendown() input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) # i input_turtle.pendown() input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.forward(10) input_turtle.left(180) input_turtle.penup() input_turtle.forward(20) input_turtle.pendown() input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(10) input_turtle.penup() input_turtle.forward(10) # n input_turtle.pendown() input_turtle.left(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.penup() input_turtle.forward(10) # a input_turtle.pendown() input_turtle.left(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(30)
def write_name_delbertina(input_turtle): input_turtle.right(90) input_turtle.forward(50) input_turtle.left(90) input_turtle.pendown() input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(50) input_turtle.left(180) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) input_turtle.left(90) input_turtle.pendown() input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(10) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(40) input_turtle.left(180) input_turtle.forward(40) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(50) input_turtle.left(180) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(180) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) input_turtle.left(90) input_turtle.pendown() input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(10) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.right(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(180) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(20) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.forward(10) input_turtle.left(180) input_turtle.penup() input_turtle.forward(20) input_turtle.pendown() input_turtle.forward(20) input_turtle.left(90) input_turtle.forward(10) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(20) input_turtle.left(90) input_turtle.penup() input_turtle.forward(10) input_turtle.pendown() input_turtle.left(90) input_turtle.forward(20) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(90) input_turtle.forward(10) input_turtle.left(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.right(90) input_turtle.forward(30) input_turtle.left(180) input_turtle.forward(30)
my_list=[22,333,412] sum =0 for number in my_list: sum += number print(sum)
my_list = [22, 333, 412] sum = 0 for number in my_list: sum += number print(sum)
#To accept 2 integers and display the largest among them a=int(input("Enter Number:")) b=int(input("Enter Number:")) if a>b: print (a,"is greater") elif a<b: print (b,"is greater") else: print ("Both Are Same Number")
a = int(input('Enter Number:')) b = int(input('Enter Number:')) if a > b: print(a, 'is greater') elif a < b: print(b, 'is greater') else: print('Both Are Same Number')
# == , != (Int, float, str, bool) x,y=6,7 p=6 print(x == y) #False print(p == x) #True print(p == 6.0) #True print('Hello' == 'Hello') #True #Chaining print(10 == 20 == 6 == 3) #False print(1 == 1 == 1 < 2) #True print(1 !=2 < 3 > 1) #True
(x, y) = (6, 7) p = 6 print(x == y) print(p == x) print(p == 6.0) print('Hello' == 'Hello') print(10 == 20 == 6 == 3) print(1 == 1 == 1 < 2) print(1 != 2 < 3 > 1)
bool1 = [[i*j for i in range(5)] for j in range(5)] print(bool1) for g in range(0,len(bool1[0])): i = 0 for j in range(g,len(bool1[0])): print(bool1[i][j]) i += 1
bool1 = [[i * j for i in range(5)] for j in range(5)] print(bool1) for g in range(0, len(bool1[0])): i = 0 for j in range(g, len(bool1[0])): print(bool1[i][j]) i += 1
def check(expected, obtained): try: a = float(expected) b = float(obtained) except ValueError: return False return abs(a - b) <= 1e-3
def check(expected, obtained): try: a = float(expected) b = float(obtained) except ValueError: return False return abs(a - b) <= 0.001
_base_ = '../yolox/yolox_l_8x8_300e_coco.py' model = dict( bbox_head=dict(num_classes=1) ) dataset_type = 'BasketballDetection' # data_root = '/mnt/nfs-storage/yujiannan/data/bas_data/train_data/' data_root = '/home/senseport0/data/train_data/' data = dict( samples_per_gpu=4, workers_per_gpu=1, train=dict( dataset=dict( type=dataset_type, ann_file=data_root + "train_21.3.10_train.json" or "train_21.8.16_train.json", img_prefix=data_root)), val=dict( type=dataset_type, img_prefix=data_root, ann_file=data_root + "train_21.3.10_val.json" or "val_21.8.16.json"), test=dict( type=dataset_type, img_prefix=data_root, ann_file=data_root + "train_21.3.10_val.json" or "val_21.8.16.json")) optimizer = dict(type='SGD', lr=2e-5, momentum=0.9, weight_decay=5e-4) evaluation = dict(interval=1, metric=['mAP']) checkpoint_config = dict(interval=1)
_base_ = '../yolox/yolox_l_8x8_300e_coco.py' model = dict(bbox_head=dict(num_classes=1)) dataset_type = 'BasketballDetection' data_root = '/home/senseport0/data/train_data/' data = dict(samples_per_gpu=4, workers_per_gpu=1, train=dict(dataset=dict(type=dataset_type, ann_file=data_root + 'train_21.3.10_train.json' or 'train_21.8.16_train.json', img_prefix=data_root)), val=dict(type=dataset_type, img_prefix=data_root, ann_file=data_root + 'train_21.3.10_val.json' or 'val_21.8.16.json'), test=dict(type=dataset_type, img_prefix=data_root, ann_file=data_root + 'train_21.3.10_val.json' or 'val_21.8.16.json')) optimizer = dict(type='SGD', lr=2e-05, momentum=0.9, weight_decay=0.0005) evaluation = dict(interval=1, metric=['mAP']) checkpoint_config = dict(interval=1)
# Python Program to print Unique Prime Factors of a Number Number = int(input(" Please Enter any Number: ")) i = 1 my=[] while(i <= Number): count = 0 if(Number % i == 0): j = 1 while(j <= i): if(i % j == 0): count = count + 1 j = j + 1 if (count == 2): my.append(i) i = i + 1 my=list(dict.fromkeys(my)) print(my)
number = int(input(' Please Enter any Number: ')) i = 1 my = [] while i <= Number: count = 0 if Number % i == 0: j = 1 while j <= i: if i % j == 0: count = count + 1 j = j + 1 if count == 2: my.append(i) i = i + 1 my = list(dict.fromkeys(my)) print(my)