content stringlengths 7 1.05M |
|---|
"""
There are some spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter, and hence the x-coordinates of start and end of the diameter suffice. The start is always smaller than the end.
An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps traveling up infinitely.
Given an array points where points[i] = [xstart, xend], return the minimum number of arrows that must be shot to burst all balloons.
Example 1:
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
Example 2:
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Example 3:
Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Example 4:
Input: points = [[1,2]]
Output: 1
Example 5:
Input: points = [[2,3],[2,3]]
Output: 1
Constraints:
0 <= points.length <= 104
points.length == 2
-231 <= xstart < xend <= 231 - 1
"""
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda x:(x[1],x[0]))
prev, ret = None, 0
for p in points:
if prev is None:
prev = p[1]
ret += 1
continue
if prev < p[0]:
prev = p[1]
ret += 1
return ret
|
# 分身合球,分身吃球
server_default_config = dict(
team_num=2,
player_num_per_team=2,
map_width=300,
map_height=300,
match_time=10,
state_tick_per_second=10, # frame
action_tick_per_second=5, # frame
collision_detection_type='precision',
save_video=False,
save_quality='high', # ['high', 'low']
save_path='',
save_bin=False, # save bin to go-explore
load_bin=False,
load_bin_path='',
load_bin_frame_num = 'all',
jump_to_frame_file = '',
manager_settings=dict(
# food setting
food_manager=dict(
num_init=180, # initial number
num_min=180, # Minimum number
num_max=225, # Maximum number
refresh_time=2, # Time interval (seconds) for refreshing food in the map
refresh_num=0, # The number of refreshed foods in the map each time
ball_settings=dict( # The specific parameter description can be viewed in the ball module
radius_min=2,
radius_max=2,
),
),
# thorns setting
thorns_manager=dict(
num_init=1, # initial number
num_min=1, # Minimum number
num_max=2, # Maximum number
refresh_time=6, # Time interval (seconds) for refreshing thorns in the map
refresh_num=0, # The number of refreshed thorns in the map each time
ball_settings=dict( # The specific parameter description can be viewed in the ball module
radius_min=12,
radius_max=20,
vel_max=100,
eat_spore_vel_init=10,
eat_spore_vel_zero_time=1,
)
),
# player setting
player_manager=dict(
ball_settings=dict( # The specific parameter description can be viewed in the ball module
acc_max=100,
vel_max=25,
radius_min=3,
radius_max=300,
radius_init=3,
part_num_max=16,
on_thorns_part_num=10,
on_thorns_part_radius_max=20,
split_radius_min=10,
eject_radius_min=10,
recombine_age=20,
split_vel_init=30,
split_vel_zero_time=1,
stop_zero_time=1,
size_decay_rate=0.00005,
given_acc_weight=10,
)
),
# spore setting
spore_manager=dict(
ball_settings=dict( # The specific parameter description can be viewed in the ball module
radius_min=3,
radius_max=3,
vel_init=250,
vel_zero_time=0.3,
spore_radius_init=20,
)
)
),
custom_init=dict(
food=[], # only position and radius
thorns=[[300, 300, 16]], # only position and radius
spore=[], # only position and radius
clone=[[80, 100, 16, '0', '0'], [130, 100, 10, '1', '0'],
[130, 130, 12, '2', '1'], [300, 300, 3, '3', '1']],
),
obs_settings=dict(
with_spatial=True,
with_speed=False,
with_all_vision=False,
),
)
|
def do(self):
self.components.Open.label="Open"
self.components.Delete.label="Delete"
self.components.Duplicate.label="Duplicate"
self.components.Run.label="Run"
self.components.Files.text="Files"
self.components.Call.label="Call"
|
#!/usr/bin/env python3
# Copyright 2019, Alex Wiens <awiens@mail.upb.de>, Achim Lösch <achim.loesch@upb.de>
# SPDX-License-Identifier: BSD-2-Clause
foo = {\
"heat":[256,512,1024,2048,4096,8192,16384],\
"correlation":[256,512,1024,2048,4096,8192,16384],\
"bfs":[128,256,512,1024,2048,4096,8192,16384],\
"markov":[128,256,512,1024,2048,4096],\
"gaussblur":[256,512,1024,2048,4096,8192,16384]}
i = 0
for t in foo:
for s in foo[t]:
e = '"type":"TASKDEF","id":{0:d},"name":"{1:s}","size":{2:d},"checkpoints":256,"dependencies":[2],"resources":[]'.format(i, t, s)
i += 1
print("{",e,"},")
|
# 3rd question
# 12 se 421 takkk k sare no. ka sum print kre.
# akshra=12
# sum=0
# while akshra<=421:
# sum=sum+akshra
# print(s)
# akshra=akshra+1
# 4th question
# 30 se 420 se vo no. print kro jo 8 se devied ho
# var=30
# while var<=420:
# if var%8==0:
# print(var)
# var+=1
# var1=1
# sum=0
# while var1<=11:
# n=int(input("enter no."))
# if n%5==0:
# n=n+var1
# print(n)
# var1=var1+1
# 6TH QUESTION
#
# 7TH ,AND , 8TH QUESTION
# GUESSING GAME BNAAOOOO
# var1=int(input("enter the no."))
# var2=int(input("enter no."))
# while var1!=0:
# num=var1*var2
# print(num)
# num=num+1
n = 6
s = 0
i = 1
while i <= n:
s = s + i
i = i + 1
print (s)
|
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module contains Access Control Role names related to TaskGroupTask model."""
ASSIGNEE_NAME = "Task Assignees"
SECONDARY_ASSIGNEE_NAME = "Task Secondary Assignees"
|
# Project Euler Problem 5
######################################
# Find smallest pos number that is
# evenly divisible by all numbers from
# 1 to 20
######################################
#essentially getting the lcm of several numbers
# formula for lcm is lcm(a,b) = a*b / gcd(a,b)
def gcd(a, b):
assert type(a) is int, "arg1 non int"
assert type(b) is int, "arg2 non int"
#just do Euclidean algorithm
if a < b:
while a:
b, a = a, b%a
return b
else:
while b:
a, b = b, a%b
return a
def gcd_test():
print(gcd(1, 1))
print(gcd(5, 35))
print(gcd(21, 56))
print(gcd(27, 9))
return
def lcm(a, b):
return a*b//gcd(a,b)
def mult_lcm(num_list):
#initialize prev
prev = 1
for i in range(0, len(num_list) - 1):
if i == 0:
a = num_list[0]
b = num_list[i+1]
a = lcm(a, b)
return a
def main():
print(mult_lcm(range(1, 21)))
return
#test
main()
|
print('hello world')
print("hello world")
print("hello \nworld")
print("hello \tworld")
print('length=',len('hello')) # len returns the length of the string
mystring="python" # assigning value python to variable mystring
print(mystring) # it returns python
# Indexing
print('the element at Index[0]=',mystring[0]) # it returns 'p' because P is at 0
print('the element at Index[3]=',mystring[3]) # it returns 'h'
# Slicing
print('the elements starting at Index[0] and it goes upto Index[4]',mystring[0:4])
# it returns 'pyth'In slicing it goes upto but not include
print('start at Index[3] and goes upto Index[5]',mystring[3:5]) # it returns 'ho'
print(mystring[::2]) # it returns 'pto' |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
if a + 0.5 - b > 0:
print(1)
else:
print(0)
if __name__ == '__main__':
main()
|
'''
Faça um algoritmo que leia o preço de um produto e mostre seu
novo preço, com 5% de desconto.
'''
preco = float(input('Digite o preço do produto: R$ '))
novoPreco = preco*0.95
print(f'O preço com 5% de desconto é R${novoPreco:.2f}') |
# Дано предложение. Определить количество букв н, предшествующих первой запятой
# предложения. Рассмотреть два случая: известно, что запятые в предложении есть;
# запятых в предложении может не быть.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
n = input("Предложение - ")
commas = n.count(',')
if commas > 0:
commaindex = n.find(',')
ncount = n.count('н')
print(ncount)
else:
print("Букв н нет")
|
"""This file is imported in both train.py and predict.py
to find the models path.
"""
# root directory to save models
## for running locally
MODELS_DIR = "models"
## for remote deploy
# MODELS_DIR = "/volumes/data"
|
values = input("Please fill value:")
result = []
for value in values :
if str(value).isdigit() :
dec = int(value)
if dec % 2 != 0 :
result.append(dec)
print(result)
print(len(result)) |
class ClientException(Exception):
"""The base exception for everything to do with clients."""
message = None
def __init__(self, status_code=None, message=None):
self.status_code = status_code
if not message:
if self.message:
message = self.message
else:
message = self.__class__.__name__
super(Exception, self).__init__(message)
|
n = [int,int]; resultado = 0;
for i in range(len(n)):
n[i] = int(input("Insira o N%i: " % int(i+1)))
dsr = n[0]; dnd = n[1];
while dnd <= dsr:
dsr -= dnd
resultado += 1
print(str(n[0]) + " / " + str(n[1]) + " = " + str(resultado))
if dsr != 0:
print(str(dsr) + " é o resto dessa operação.") |
#Fácil 5- Faça um programa para a leitura de duas notas parciais de um aluno.A mensagem “Aprovado”, se a média alcançada for maior ou igual a sete;A mensagem “Aprovado com Distinção”, se a média for igual a dez;A mensagem “Reprovado” se a média for menor de do que sete;
nome=input('Digite o nome do aluno: ')
nota_1bi=float(input('Digite a nota do aluno no primeiro bimestre: '))
nota_2bi=float(input('Digite a nota do aluno no segundo semestre: '))
media=(nota_1bi+nota_2bi)/2
if media >= 7 and media<10:
print('Aprovado com distinção')
elif media==10:
print('Você é pica menor')
else:
print('Ramelou na missão: REPROVADO') |
class Instrument:
def __init__(self,
exchange_name,
instmt_name,
instmt_code,
**param):
self.exchange_name = exchange_name
self.instmt_name = instmt_name
self.instmt_code = instmt_code
self.instmt_snapshot_table_name = ''
def get_exchange_name(self):
return self.exchange_name
def get_instmt_name(self):
return self.instmt_name
def get_instmt_code(self):
return self.instmt_code
def get_instmt_snapshot_table_name(self):
return self.instmt_snapshot_table_name
def set_instmt_snapshot_table_name(self, instmt_snapshot_table_name):
self.instmt_snapshot_table_name = instmt_snapshot_table_name |
class NoProjectYaml(Exception):
pass
class NoDockerfile(Exception):
pass
class CheckCallFailed(Exception):
pass
class WaitLinkFailed(Exception):
pass
|
class Role:
def __init__(self, data):
self.data = data
@property
def id(self):
return self.data["id"]
@property
def name(self):
return self.data["name"]
@classmethod
def from_dict(cls, data):
return cls(data)
|
__author__ = "Abdul Dakkak"
__email__ = "dakkak@illinois.edu"
__license__ = "Apache 2.0"
__version__ = "0.2.4"
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
"""
An enumeration type that lists the render modes supported by FreeType 2. Each
mode corresponds to a specific type of scanline conversion performed on the
outline.
FT_PIXEL_MODE_NONE
Value 0 is reserved.
FT_PIXEL_MODE_MONO
A monochrome bitmap, using 1 bit per pixel. Note that pixels are stored in
most-significant order (MSB), which means that the left-most pixel in a byte
has value 128.
FT_PIXEL_MODE_GRAY
An 8-bit bitmap, generally used to represent anti-aliased glyph images. Each
pixel is stored in one byte. Note that the number of 'gray' levels is stored
in the 'num_grays' field of the FT_Bitmap structure (it generally is 256).
FT_PIXEL_MODE_GRAY2
A 2-bit per pixel bitmap, used to represent embedded anti-aliased bitmaps in
font files according to the OpenType specification. We haven't found a single
font using this format, however.
FT_PIXEL_MODE_GRAY4
A 4-bit per pixel bitmap, representing embedded anti-aliased bitmaps in font
files according to the OpenType specification. We haven't found a single font
using this format, however.
FT_PIXEL_MODE_LCD
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on LCD displays; the bitmap is three times wider than the original
glyph image. See also FT_RENDER_MODE_LCD.
FT_PIXEL_MODE_LCD_V
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on rotated LCD displays; the bitmap is three times taller than the
original glyph image. See also FT_RENDER_MODE_LCD_V.
"""
FT_PIXEL_MODES = {'FT_PIXEL_MODE_NONE' : 0,
'FT_PIXEL_MODE_MONO' : 1,
'FT_PIXEL_MODE_GRAY' : 2,
'FT_PIXEL_MODE_GRAY2': 3,
'FT_PIXEL_MODE_GRAY4': 4,
'FT_PIXEL_MODE_LCD' : 5,
'FT_PIXEL_MODE_LCD_V': 6,
'FT_PIXEL_MODE_MAX' : 7}
globals().update(FT_PIXEL_MODES)
ft_pixel_mode_none = FT_PIXEL_MODE_NONE
ft_pixel_mode_mono = FT_PIXEL_MODE_MONO
ft_pixel_mode_grays = FT_PIXEL_MODE_GRAY
ft_pixel_mode_pal2 = FT_PIXEL_MODE_GRAY2
ft_pixel_mode_pal4 = FT_PIXEL_MODE_GRAY4
|
def sum(arr):
if len(arr) == 0:
return 0
return arr[0] + sum(arr[1:])
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8]
print('Test arr: %s' % arr)
print('sum = %s' % sum(arr)) |
#!/usr/bin/env python3
file = 'input.txt'
with open(file) as f:
input = f.read().splitlines()
def more_ones(list, truth):
data = []
for i in range(0, len(list[0])):
more_ones = sum([1 for x in list if x[i] == '1']) >= sum([1 for x in list if x[i] == '0'])
if more_ones:
if truth:
data.append(1)
else:
data.append(0)
else:
if truth:
data.append(0)
else:
data.append(1)
return data
def search_lists(input, truth):
numbers = input.copy()
for i in range(0, len(input[0])):
count = 0
for line in numbers:
if line[i] == str(more_ones(numbers, truth)[i]):
count += 1
if count == len(numbers) / 2:
char = (1 if truth else 0)
else:
char = more_ones(numbers, truth)[i]
for line in list(numbers):
if line[i] != str(char):
numbers.remove(line)
if len(numbers) == 1:
return numbers[0]
print(int(search_lists(input, True), 2) * int(search_lists(input, False), 2)) |
class Config(object):
MONGO_URI = 'mongodb://172.17.0.2:27017/bibtexreader'
MONGO_HOST = 'mongodb://172.17.0.2:27017'
DB_NAME = 'bibtexreader'
BIB_DIR = 'bibtexfiles' |
DATABASES = {
'default': {
'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3',
}
}
SECRET_KEY = 'secret'
INSTALLED_APPS = (
'django_nose',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = (
'stopwatch',
'--verbosity=2',
'--nologcapture',
'--with-doctest',
'--with-coverage',
'--cover-package=stopwatch',
'--cover-erase',
)
|
def dfs(self):
"""
Computes the initial source vertices for each connected component
and the parents for each vertex as determined through depth-first-search
:return: initial source vertices for each connected component, parents for each vertex
:rtype: set, dict
"""
parents = {}
components = set()
to_visit = []
for vertex in self.get_vertex():
if vertex not in parents:
components.add(vertex)
else:
continue
to_visit.append(vertex)
while to_visit:
v = to_visit.pop()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.append(neighbor)
return components, parents
def bfs(self):
"""
Computes the the parents for each vertex as determined through breadth-first search
:return: parents for each vertex
:rtype: dict
"""
parents = {}
to_visit = queue.Queue()
for vertex in self.get_vertex():
to_visit.put(vertex)
while not to_visit.empty():
v = to_visit.get()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.put(neighbor)
return parents
|
__author__ = "Brett Fitzpatrick"
__version__ = "0.1"
__license__ = "MIT"
__status__ = "Development"
|
input = """
a v b.
a :- b.
b :- a.
"""
output = """
{a, b}
"""
|
_base_ = './hv_pointpillars_fpn_nus.py'
# model settings (based on nuScenes model settings)
# Voxel size for voxel encoder
# Usually voxel size is changed consistently with the point cloud range
# If point cloud range is modified, do remember to change all related
# keys in the config.
model = dict(
pts_voxel_layer=dict(
max_num_points=20,
point_cloud_range=[-100, -100, -5, 100, 100, 3],
max_voxels=(60000, 60000)),
pts_voxel_encoder=dict(
feat_channels=[64], point_cloud_range=[-100, -100, -5, 100, 100, 3]),
pts_middle_encoder=dict(output_shape=[800, 800]),
pts_bbox_head=dict(
num_classes=9,
anchor_generator=dict(
ranges=[[-100, -100, -1.8, 100, 100, -1.8]], custom_values=[]),
bbox_coder=dict(type='DeltaXYZWLHRBBoxCoder', code_size=7)))
# model training settings (based on nuScenes model settings)
train_cfg = dict(pts=dict(code_weight=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))
|
"""__init__.py - Various utilities to use throughout the system."""
def serialize_sqla(data):
"""Serialiation function to serialize any dicts or lists containing
sqlalchemy objects. This is needed for conversion to JSON format."""
# If has to_dict this is asumed working and it is used.
if hasattr(data, 'to_dict'):
return data.to_dict()
if hasattr(data, '__dict__'):
return data.__dict__
# DateTime objects should be returned as isoformat.
if hasattr(data, 'isoformat'):
return str(data.isoformat())
# Items in lists are iterated over and get serialized separetly.
if isinstance(data, (list, tuple, set)):
return [serialize_sqla(item) for item in data]
# Dictionaries get iterated over.
if isinstance(data, dict):
result = {}
for key, value in data.items():
result[key] = serialize_sqla(value)
return result
# Just hope it works.
return data
def row2dict(row):
if(not row):
return None
d = {}
for column in row.__table__.columns:
d[column.name] = getattr(row, column.name)
return d
|
"""
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 5: Processing Input and Output
Exercise:
1.
a) Ask for user input of an item, the number being purchased,
and the cost of the item. Then prit out the total and
thnak the user for shopping with you. Output should
look like this:
Give me your name, please: [Name]
How many widgets are you buying? [#]
How much do they cost, per item? [#.##]
Your total is $[#.##]
Thanks for shopping with us today [Name] !
"""
#Hour 5: Processing Input and Output
name = str(input("Give me your name, please: "))
num = float(input("How many widgets are you buying? "))
cost_per_item = float(input("How much do they cost, per item? "))
print ("Your total is $" + str(num * cost_per_item))
print ("Thanks for shopping with us today " + name + "!")
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../build/win_precompile.gypi',
],
'targets': [
{
'target_name': 'check_sdk_patch',
'type': 'none',
'variables': {
'check_sdk_script': 'util/check_sdk_patch.py',
'output_path': '<(INTERMEDIATE_DIR)/check_sdk_patch',
},
'actions': [
{
'action_name': 'check_sdk_patch_action',
'inputs': [
'<(check_sdk_script)',
],
'outputs': [
# This keeps the ninja build happy and provides a slightly helpful
# error messge if the sdk is missing.
'<(output_path)'
],
'action': ['python',
'<(check_sdk_script)',
'<(windows_sdk_path)',
'<(output_path)',
],
},
],
},
{
'target_name': 'win8_util',
'type': 'static_library',
'dependencies': [
'../base/base.gyp:base',
],
'sources': [
'util/win8_util.cc',
'util/win8_util.h',
],
},
{
'target_name': 'test_support_win8',
'type': 'static_library',
'dependencies': [
'../base/base.gyp:base',
'test_registrar_constants',
],
'sources': [
'test/metro_registration_helper.cc',
'test/metro_registration_helper.h',
'test/open_with_dialog_async.cc',
'test/open_with_dialog_async.h',
'test/open_with_dialog_controller.cc',
'test/open_with_dialog_controller.h',
'test/ui_automation_client.cc',
'test/ui_automation_client.h',
],
# TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
'msvs_disabled_warnings': [ 4267, ],
},
{
'target_name': 'test_registrar_constants',
'type': 'static_library',
'include_dirs': [
'..',
],
'sources': [
'test/test_registrar_constants.cc',
'test/test_registrar_constants.h',
],
},
],
}
|
class Solution:
def maxSlidingWindow(self, nums, k):
deq, n, ans = deque([0]), len(nums), []
for i in range (n):
while deq and deq[0] <= i - k:
deq.popleft()
while deq and nums[i] >= nums[deq[-1]] :
deq.pop()
deq.append(i)
ans.append(nums[deq[0]])
return ans[k-1:]
|
TEXT_BLACK = "\033[0;30;40m"
TEXT_RED = "\033[1;31;40m"
TEXT_GREEN = "\033[1;32;40m"
TEXT_YELLOW = "\033[1;33;40m"
TEXT_WHITE = "\033[1;37;40m"
TEXT_BLUE = "\033[1;34;40m"
TEXT_RESET = "\033[0;0m"
def get_color(ctype):
if ctype == 'yellow':
color = TEXT_YELLOW
elif ctype == 'green':
color = TEXT_GREEN
elif ctype == 'white':
color = TEXT_WHITE
elif ctype == 'black':
color = TEXT_BLACK
elif ctype == 'blue':
color = TEXT_BLUE
elif ctype == 'red':
color = TEXT_RED
return color
def print_emph(msg):
bar = "# # # # # # # # # # # # # # # # # # # #"
print("{}{}".format(TEXT_WHITE, bar))
print("# {}".format(msg))
print("{}{}".format(bar, TEXT_RESET))
pass
def print_highlight(msg, ctype='yellow'):
color = get_color(ctype)
print("{}{}{}".format(color, msg, TEXT_RESET))
def test():
print("\033[0;37;40m Normal text\n")
print("\033[2;37;40m Underlined text\033[0;37;40m \n")
print("\033[1;37;40m Bright Colour\033[0;37;40m \n")
print("\033[3;37;40m Negative Colour\033[0;37;40m \n")
print("\033[5;37;40m Negative Colour\033[0;37;40m\n")
print("\033[1;37;40m \033[2;37:40m TextColour BlackBackground TextColour GreyBackground WhiteText ColouredBackground\033[0;37;40m\n")
print("\033[1;30;40m Dark Gray \033[0m 1;30;40m \033[0;30;47m Black \033[0m 0;30;47m \033[0;37;41m Black \033[0m 0;37;41m")
print("\033[1;31;40m Bright Red \033[0m 1;31;40m \033[0;31;47m Red \033[0m 0;31;47m \033[0;37;42m Black \033[0m 0;37;42m")
print("\033[1;32;40m Bright Green \033[0m 1;32;40m \033[0;32;47m Green \033[0m 0;32;47m \033[0;37;43m Black \033[0m 0;37;43m")
print("\033[1;33;40m Yellow \033[0m 1;33;40m \033[0;33;47m Brown \033[0m 0;33;47m \033[0;37;44m Black \033[0m 0;37;44m")
print("\033[1;34;40m Bright Blue \033[0m 1;34;40m \033[0;34;47m Blue \033[0m 0;34;47m \033[0;37;45m Black \033[0m 0;37;45m")
print("\033[1;35;40m Bright Magenta \033[0m 1;35;40m \033[0;35;47m Magenta \033[0m 0;35;47m \033[0;37;46m Black \033[0m 0;37;46m")
print("\033[1;36;40m Bright Cyan \033[0m 1;36;40m \033[0;36;47m Cyan \033[0m 0;36;47m \033[0;37;47m Black \033[0m 0;37;47m")
print("\033[1;37;40m White \033[0m 1;37;40m \033[0;37;40m Light Grey \033[0m 0;37;40m \033[0;37;48m Black \033[0m 0;37;48m")
|
##########################################################################
# pylogparser - Copyright (C) AGrigis, 2016
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
# Current version
version_major = 0
version_minor = 1
version_micro = 0
# Expected by setup.py: string of form "X.Y.Z"
__version__ = "{0}.{1}.{2}".format(version_major, version_minor, version_micro)
# Expected by setup.py: the status of the project
CLASSIFIERS = ["Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Environment :: X11 Applications :: Qt",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"]
# Project descriptions
description = """
[pylogparser] A Python project that provides common parser for log files.
It is also connected with ElasticSearch in order to centralize the data and
to provide a sophisticated RESTful API to request the data.
"""
long_description = """
[pylogparser] A Python project that provides common parser for log files.
It is also connected with ElasticSearch in order to centralize the data and
to provide a sophisticated RESTful API to request the data.
"""
# Main setup parameters
NAME = "pyLogParser"
ORGANISATION = "CEA"
MAINTAINER = "Antoine Grigis"
MAINTAINER_EMAIL = "antoine.grigis@cea.fr"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
URL = "https://github.com/AGrigis/pylogparser"
DOWNLOAD_URL = "https://github.com/AGrigis/pylogparser"
LICENSE = "CeCILL-B"
CLASSIFIERS = CLASSIFIERS
AUTHOR = "pyLogParser developers"
AUTHOR_EMAIL = "antoine.grigis@cea.fr"
PLATFORMS = "OS Independent"
ISRELEASE = True
VERSION = __version__
PROVIDES = ["pylogparser"]
REQUIRES = [
"elasticsearch>=2.3.0",
"python-dateutil>=1.5"
]
EXTRA_REQUIRES = {}
|
# -*- coding: utf-8
class BaseObject:
"""
Base Unke object type
Represents a node in a document.
"""
def __init__(self, parent=None):
self.parent = parent
self.children = []
self.name = ''
self.properties = {}
@property
def props(self):
return self.properties
@property
def anonymous(self):
return self.name is None
@property
def siblings(self):
if self.parent:
return list(filter(lambda sibling: sibling is not self, self.parent.children))
else:
return []
def __repr__(self):
return 'Object({}, {})'.format(self.name, id(self))
class BoostedObject(BaseObject):
"""
Default Unke Object type with enhanced performance
Represents a node in a document
"""
# Making use of __slots__ to improve object creation performance
__slots__ = ('parent', 'children', 'name', 'properties')
def __init__(self):
BaseObject.__init__(self)
|
# pylint:enable=W04044
"""check unknown option
"""
__revision__ = 1
|
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
for i in range(len(arr) - 1, -1, -1):
if not arr[i]:
arr.insert(i + 1, 0)
arr.pop() |
class ClassPropertyDescriptor(object):
#def __init__(self, fget, fset=None):
def __init__(self, fget):
self.fget = fget
#self.fset = fset
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
"""
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
import ipdb;ipdb.set_trace()
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
"""
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return ClassPropertyDescriptor(func)
class CachedClassPropertyDescriptor(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
try:
return self.cached_data
except:
self.cached_data = self.fget.__get__(obj, klass)()
return self.cached_data
def cachedclassproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return CachedClassPropertyDescriptor(func)
"""
class Test(object):
@classproperty
def NAME1(cls):
print("CALL 'Test.NAME1'")
return cls._NAME1 if hasattr(cls,"_NAME1") else "Jack1"
@classproperty
def NAME2(cls):
print("CALL 'Test.NAME2'")
return cls._NAME2 if hasattr(cls,"_NAME2") else "Jack2"
@cachedclassproperty
def CACHED_NAME1(cls):
print("CALL 'Test.CACHED_NAME1'")
return cls._CACHED_NAME1 if hasattr(cls,"_CACHED_NAME1") else "Cached Jack1"
@cachedclassproperty
def CACHED_NAME2(cls):
print("CALL 'Test.CACHED_NAME2'")
return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Jack2"
@cachedclassproperty
def CACHED_NAME3(cls):
print("CALL 'Test.CACHED_NAME3'")
return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Jack3"
class Test1(Test):
@classproperty
def NAME2(cls):
print("CALL 'Test1.NAME2'")
return cls._NAME2 if hasattr(cls,"_NAME2") else "Tommy2"
@cachedclassproperty
def CACHED_NAME2(cls):
print("CALL 'Test1.CACHED_NAME2'")
return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Tommy2"
@classproperty
def CACHED_NAME3(cls):
print("CALL 'Test1.CACHED_NAME3'")
return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Tommy3"
The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.
Adding a metaclass definition solves this:
class ClassPropertyMetaClass(type):
def __setattr__(self, key, value):
if key in self.__dict__:
obj = self.__dict__.get(key)
if obj and type(obj) is ClassPropertyDescriptor:
return obj.__set__(self, value)
return super(ClassPropertyMetaClass, self).__setattr__(key, value)
# and update class define:
# class Bar(object):
# __metaclass__ = ClassPropertyMetaClass
# _bar = 1
# and update ClassPropertyDescriptor.__set__
# def __set__(self, obj, value):
# if not self.fset:
# raise AttributeError("can't set attribute")
# if inspect.isclass(obj):
# type_ = obj
# obj = None
# else:
# type_ = type(obj)
# return self.fset.__get__(obj, type_)(value)
"""
|
s = 1
for c in range(0, 5):
n = int(input('número: '))
s += n
print('O somatório foi de {}'.format(s))
|
#Escreva um programa que leia uma string e imprima quantas vezes cada caractere aparece nessa string
string = input('Digite uma string: ')
count = {}
for i in string:
count[i] = count.get(i,0) + 1
for chave, valor in count.items():
print(f'{chave}: {valor}x')
print() |
mitreid_config = {
"dbname": "example_db",
"user": "example_user",
"host": "example_address",
"password": "secret"
}
proxystats_config = {
"dbname": "example_db",
"user": "example_user",
"host": "example_address",
"password": "secret"
} |
aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = int(input(f'Media do {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['situaçao'] = 'APROVADO'
elif 5 <= aluno['media'] < 7:
aluno['situaçao'] = 'RECUPERAÇÃO'
else:
aluno['situaçao'] = 'REPROVADO'
for k, v in aluno.items():
print(f'{k} é {v}')
|
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/630/B
#直接乘有点太多?
#24个月double => 24*30*24*60*60=
#想多了,编程语言的power已经足够优化? 快速幂?
#https://codeforces.com/blog/entry/24160?locale=en
def f(l):
n,t = l #1e3-1e4; 2e9;
return n*(1.000000011**t)
l = list(map(int,input().split()))
print(f(l))
|
num = int(input('Digite um número como base para a PA:\n'))
raz = int(input('Digite a razão'))
c = 0
while c < 10:
print(num+(raz*c))
c += 1 |
print("Hello World")
a =5
b = 6
sum = a+b
print(sum)
print(sum -11)
|
# https://leetcode.com/problems/maximum-product-subarray/submissions/
"""
For cases like : [2,3,4] => Product is always going to increase since all nums are +ve
For cases like : [-2 , -3 , -4] => Product is always going to decrease since all nums are -ve
For cases like : [-2 , 3 , 4] => Product may increase or decrease bcoz of the sign
If we use one variable to store the max , we may end up getting a value lesser than expected due
to encountering of negative numbers and zeroes in between
So we use two variables to store the max and min product respectively
curr_max = max(nums[i] , curr_max * nums[i] , curr_min * nums[i])
curr_min = min(nums[i] , curr_max * nums[i] , curr_min * nums[i])
Note : For curr_min , we dont require the updated curr_max , hence to avoid the updated curr_max being
used , we store curr_max*nums[i] in a variable temp
temp = curr_max * nums[i]
So ,
curr_min = min(nums[i] , temp , curr_min * nums[i])
res = max(res , curr_max)
Dry run for 1st sample input:
For nums = [2,3,-2,4]
curr_max = 1
curr_min = 1
res = max([2,3,-2,4]) = 4
1. i = 0
curr_max = max(2 , 2*1 , 2*1) = 2
curr_min = min(2 , 2*1 , 2*1) = 2
res = 4
2. i = 1
curr_max = max(3 , 3*2 , 3*2) = 6
curr_min = min(3 , 3*2 , 3*2) = 3
res = 6
3. i = 2
curr_max = max(-2 , -2*6 , -2*3) = -2
curr_min = min(-2 , -2*6 , -2*3) = -12
res = 6
4. i = 3
curr_max = max(4 , 4*-2 , 4*-12) = 4
curr_min = min(4 , 4*-2 , 4*-12) = -48
res = 6
o/p : res = 6
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr_max = 1
curr_min = 1
res = max(nums)
for i in range(0 , len(nums)):
if(nums[i] == 0):
# Avoid zeroes
curr_max = 1
curr_min = 1
continue
# Computing temp to store the curr_max * nums[i] , so as to avoid using the updated value of curr_max while calculating curr_min
temp = curr_max * nums[i]
curr_max = max(curr_max * nums[i] , curr_min * nums[i] , nums[i])
curr_min = min(temp , curr_min * nums[i] , nums[i])
res = max(res , curr_max)
return res
"""
TC : O(n)
"""
|
# Welcome back, How did you do on your first quiz? If you got most of the
# questions right, great job. If not, no worries it's all part of elarning. We'll be here
# to help you check that you've really got your head around these concepts with
# regular quizzes like this. If you ever find a question tricky, go back and review the
# videos and then try the quiz again. You want to feel super comfortable with what
# you've learned before jumping into the next lesson. Remember, take your time. I
# will be here whenever you're ready to move on. Okay. Feeling good? Great. Let us
# dive in. In this course, we will use the Python programming language to
# demonstrate basic programming concepts and how to apply them to writing
# scripts. We have mentioned that there are a bunch of programming languages
# out there. So why pick Python? Well, we chose Python for a few reasons. First off,
# programming in Python usually feels similar to using a human language. This is
# because Python makes it easy to express what we want to do with syntax that's
# easy to read and write. Check out this example. There is a lot to unpack here so
# don't worry if you don't understand it right away, we'll get into the nitty-gritty
# details later in the course. But even if you've never seen a line of code before,
# you might be able to guess what this code does. It defines a list with names of
# friends and then creates a greeting for each name in the list. Now it is your turn
# to make friends with Python. Try it out and see what happens. Throughout this
# course, you will execute Python code using your web browser. We'll start with
# some small coding exercises using code blocks just like the one you
# experimented with. Later on as you develop your skills, you'll work on larger
# more complex coding exercises using other tools. Getting good at something
# Takes a whole lot of practice every example we share in this course on your
# own. If you do not have Python installed on your machine, no worries, you can
# still practice using an online Python interpreter. Check out the next reading for
# links to the most popular Python interpreters available online. Now I am sure you
# are wondering what the heck is a Python interpreter. In programming, an
# interpreter is the program that reads and executes code. Remember how we said
# a computer program is like a recipe with step-by-step instructions? Well, if your
# recipe is written in Python, the Python interpreter is the program that reads what
# is in the recipe and translates it into instructions for your computer to follow.
# Eventually, you'll want to install Python on your computer so you can run it locally
# and experiment with it as much as you like. We'll guide you through how to
# install Python in the upcoming course but you don't have to have it installed to
# get your first taste of Python. You can practice with the quizzes we provide and
# with the online interpreters and code pads that we'll give you links to in the next
# reading. We'll provide a whole bunch of exercises but feel free to come
# up with your own and share them in the discussion forums. Feel free to get
# creative. This is your change to show off your new skills.
friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print("Hi " + friend)
|
"""
Entradas
Edad1 --> int --> edad_uno
Edad2 --> int --> edad_dos
Edad3 --> int --> edad_tres
Salidas
Pormedio --> float --> prom
"""
edad_uno=int(input("Digite la edad uno: "))
edad_dos=int(input("Digite la edad dos: "))
edad_tres=int(input("Digite la edad tres: "))
#cajanegra
prom=(edad_uno+ edad_dos+edad_tres)/3
#Salidas
print("El promedio de edad es: "+str(prom))
|
def to_huf(amount: int) -> str:
"""
Amount converted to huf with decimal marks, otherwise return 0 ft
e.g. 1000 -> 1.000 ft
"""
if amount == "-":
return "-"
try:
decimal_marked = format(int(amount), ',d')
except ValueError:
return "0 ft"
return f"{decimal_marked.replace(',', '.')} ft"
|
class Shirt:
title = None
color = None
def setTitle(self, title):
self.title = title
def setColor(self, color):
self.color = color
def getTitle(self):
return self.title
def getColor(self):
return self.color
def calculatePrice(self):
return len(self.title) * len(self.color)
def printSpecifications(self):
print("Shirt title:", self.title)
print("Shirt color:", self.color)
print("Shirt price:", self.calculatePrice())
class NikeShirt(Shirt):
title = "Nike"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 10
class AdidasShirt(Shirt):
title = "Adidas"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 8
class EcoShirt(Shirt):
title = "Eco (100% cotton)"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 5
class ShirtFactory:
def getShirt(self, shirtName):
if "nike" in shirtName.lower():
return NikeShirt()
elif "adidas" in shirtName.lower():
return AdidasShirt()
elif "eco" in shirtName.lower():
return EcoShirt()
else:
print("Warning: Unecpected Shirt name", shirtName)
shirt = Shirt()
shirt.setTitle(shirtName)
return shirt
if __name__ == "__main__":
factory = ShirtFactory()
shirtName = input("Enter shirt name: ")
shirtColor = input("Enter shirt color: ")
shirt = factory.getShirt(shirtName)
shirt.setColor(shirtColor)
shirt.printSpecifications()
|
"""
Message templates to log when handling responses to requests that are SUCCESFUL.
Failed requests are logged using the error code contained in the response and its related message.
"""
resp_get_currency = '{currency}:\n' \
'\t{fullName}({id}):' \
'\tIs a cryptocurrency: {crypto}\n' \
'\tDeposits available: {payinEnabled}\n' \
'\tpayinPaymentId available: {payinPaymentId}\n' \
'\tRequired confirmations on deposit: {payinConfirmations}\n' \
'\tWithdrawals available: {payoutEnabled}\n' \
'\tpayoutIsPaymentId available: {payoutIsPaymentId}\n' \
'\tTransfers enabled: {transferEnabled}\n'
resp_get_currencies = '{fullname}({id}):' \
'\tIs a cryptocurrency: {crypto}\n' \
'\tDeposits available: {payinEnabled}\n' \
'\tpayinPaymentId available: {payinPaymentId}\n' \
'\tRequired confirmations on deposit: {payinConfirmations}\n' \
'\tWithdrawals available: {payoutEnabled}\n' \
'\tpayoutIsPaymentId available: {payoutIsPaymentId}\n' \
'\tTransfers enabled: {transferEnabled}\n'
resp_get_symbol = '{id}:\n' \
'\tBase currency: {baseCurrency}\n' \
'\tQuote currency: {quoteCurrency}\n' \
'\tMinimum quantity increment: {quantityIncrement}\n' \
'\tTick size: {tickSize}\n' \
'\tMaker fee: {takeLiquidityRate}\n' \
'\tTaker fee: {provideLiquidityRate}\n' \
'\tFee currency: {feeCurrency}\n'
resp_get_symbols = '{id}:\n' \
'\tBase currency: {baseCurrency}\n' \
'\tQuote currency: {quoteCurrency}\n' \
'\tMinimum quantity increment: {quantityIncrement}\n' \
'\tTick size: {tickSize}\n' \
'\tMaker fee: {takeLiquidityRate}\n' \
'\tTaker fee: {provideLiquidityRate}\n' \
'\tFee currency: {feeCurrency}\n'
resp_get_trades = 'Trade ID ({id}):' \
'\tPrice: {price}\n' \
'\tSize: {quantity}\n' \
'\tSide: {side}\n' \
'\tTimestamp: {timestamp}\n'
order_report_template = 'Trade ID ({id}): \tStatus: {status}\n' \
'Order type: {type}' \
'\t\tPrice: {price}' \
'\t\tSize: {quantity}\n' \
'Side: {side}\t' \
'\t\tCumulative size: {cumQuantity}' \
'\t\t\tTime in Force: {timeInForce}\n' \
'Created at: {createdAt}' \
'\t\t\t\t\tUpdated at: {updatedAt}\n' \
'Client Order ID: {clientOrderId}' \
'\t\t\t\tReport type: {reportType}'
original_request_clOrdID = 'Original Request Client Order ID: {originalRequestClientOrderId}'
resp_get_active_orders = order_report_template + original_request_clOrdID + '\n'
resp_get_trading_balance = 'Wallet: {currency}' \
'\t\tAvailable: {available}' \
'\t\tReserved: {reserved}\n'
resp_place_order = 'Successfully placed a new order via websocket!\n' + order_report_template + '\n'
resp_cancel_order = 'Successfully cancelled an order via websocket!\n' + order_report_template+ '\n'
resp_cancel_replace_order = 'Successfully replaced an order via websocket!\n' + order_report_template + original_request_clOrdID + '\n'
resp_subscribe_ticker = 'Succesfully subscribed to {symbol} ticker data!'
resp_subscribe_book = 'Succesfully subscribed to {symbol} order book data!'
resp_subscribe_trades = 'Succesfully subscribed to {symbol} trade data!'
resp_subscribe_candles = 'Succesfully subscribed to {symbol} candle data!'
resp_subscribe_reports = 'Succesfully subscribed to account reports!'
resp_login = 'Successfully logged in!'
response_types = {'getCurrency': resp_get_currency, 'getCurrencies': resp_get_currencies,
'getSymbol': resp_get_symbol, 'getSymbols': resp_get_symbols,
'getTrades': resp_get_trades,
'getOrders': resp_get_active_orders,
'getTradingBalance': resp_get_trading_balance,
'subscribeTicker': resp_subscribe_ticker,
'subscribeOrderbook': resp_subscribe_book,
'subscribeTrades': resp_subscribe_trades,
'subscribeCandles': resp_subscribe_candles,
'subscribeReports': resp_subscribe_reports,
'newOrder': resp_place_order, 'cancelOrder': resp_cancel_order,
'cancelReplaceOrder': resp_cancel_replace_order,
'login' : resp_login}
|
# Python3 program to solve N Queen Problem using backtracking
# N = Number of Queens to be placed (in this case, N = 4)
global N
N = 4
# a function to print the board with the solution
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j], end = " ")
print()
# A function to check if a Queen can be placed on board[row][col].
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
# base case: If all Queens are placed then return true
if col >= N:
return True
# Consider this column and try placing this Queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this Queen in board[i][col]
board[i][col] = 1
# recur to place rest of the Queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing Queen in board[i][col] doesn't lead to a solution, then remove Queen from board[i][col]
board[i][col] = 0
# if the Queen can not be placed in any row in this column col then return false
return False
# This function solves the N Queen problem using Backtracking.
# It returns false if Queens cannot be placed, otherwise return true.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# Driver Code
solveNQ()
# Output (with N = 4) -
# 0 0 1 0
# 1 0 0 0
# 0 0 0 1
# 0 1 0 0
# Time Complexity = O(n^n), where N is the number of Queens.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/5/21 9:25
# @Author : wildkid1024
# @Site :
# @File : extra_params.py
# @Software: PyCharm
in_size = 28 * 28
layer_size = 256
layer_num = 3
out_size = 10
batch_size = 32
learning_rate = 1e-2
num_epoches = 32
# 统计计算误差的图片个数
statistic_num = 50
dataset_root = './data-set/'
model_path = 'pretrained-model/mlp-mnist-pretrain2.pkl'
# 注入时的测试次数和数量
test_num = 256
inject_times = 10
|
update_user_permissions_response = {
'user': 'enterprise_search',
'permissions': ['permission2']
}
|
# CPU: 0.05 s
n = int(input())
if n % 2 == 0:
print((n // 2 + 1) ** 2)
else:
print((n // 2 + 1) * (n // 2 + 2))
|
li= list(map(int,input().split(" ")))
a=li[0]
b=li[1]
c=li[2]
d=li[3]
flag=0
if(a==(b+c+d)):
flag=1
elif(b==(a+c+d)):
flag=1
elif(c==(a+b+d)):
flag=1
elif(d == (a+b+c)):
flag=1
elif((a+b) == (c+d)):
flag=1
elif((a+c) == (b+d)):
flag=1
elif((a+d) == (b+c)):
flag=1
if(flag ==1):
print("Yes")
else:
print("No") |
# Generated by [Toolkit-Py](https://github.com/fujiawei-dev/toolkit-py) Generator
# Created at 2022-02-06 10:58:35.566935, Version 0.2.9
__version__ = '0.0.5'
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
if not head:
return None
return self.foo(head, None)
def foo(self, head, tail):
if not head or head == tail:
return None
fast = slow = head
while fast.next is not tail and fast.next.next is not tail: #快慢指针找到中点
slow = slow.next
fast = fast.next.next
cur = TreeNode(slow.val)
cur.left = self.foo(head, slow)
cur.right = self.foo(slow.next, tail)
return cur
|
def get_expenses_from_input(input_location):
f = open(input_location, 'r')
expenses = f.read().split('\n')
f.close()
expenses_list_number = []
for expense in expenses:
expenses_list_number.append(int(expense))
expenses_list_number.sort()
return expenses_list_number
def get_three_expenses_which_sum_2020(expenses):
counter = 0
for i,_ in enumerate(expenses):
for j,__ in enumerate(expenses):
for k,___ in enumerate(expenses):
counter += 1
if(expenses[i] + expenses[j] + expenses[k] > 2020):
break
if(expenses[i] + expenses[j] + expenses[k] == 2020):
print(f"Number of comparisons: {counter}")
return (expenses[i], expenses[j], expenses[k])
return "Error"
expenses = get_expenses_from_input('../input.txt')
value1, value2, value3 = get_three_expenses_which_sum_2020(expenses)
print(f"value1={value1}, value2={value2}, value3={value3}")
result = value1 * value2 * value3
print(f"value1 x value2 x value3 = {result}") |
#!/usr/bin/python
class LSRConfig:
# Downstream on demand, unsolicited downstream, or default
# Label distribution protocol
# Label retention mode
LABEL_RETENTION = False
# re-use labels at peers (aka "per interface" scope)
# only applicable for peers that come into different local interfaces
PER_INTERFACE_LABEL_SCOPE = False
# ordered vs. independent LSP control
|
#Speichern eines Textes
try: #1
daten=open("Daten\daten1.txt","w") #2
text=input("Bitte geben Sie Ihren Namen ein: ")
daten.write(text) #3
daten.flush() #Zwischenspeicherung der Datei ohne sie zu schließen!
daten.close() # Schließen und speichern der Datei
except:
print("Kann Datei nicht öffnen.")
#1 "Try and excet" -Funktion, um Laufzeitfehler zu vermeiden,
#1 falls Fehler im Pfad oder Ähnliches.
#2 Generierung eines neuen file-Objektes mit dem Namen "daten"
#2 und Verknüpfung mit der externen Datei über den relativen Pfad verknüpft.
#3 Der String "text" wird in die Datei geschrieben und
#3 vorher vorhandener Text gelöscht.
|
tree_map = """.......#................#......
...#.#.....#.##.....#..#.......
..#..#.#......#.#.#............
....#...#...##.....#..#.....#..
....#.......#.##......#...#..#.
...............#.#.#.....#..#..
...##...#...#..##.###...##.....
##..#.#...##.....#.#..........#
.#....#..#..#......#....#....#.
...........................#...
..........#.......#..#.....#.#.
..#.......###..#.#.......#.#...
....#..#....#....#..........#..
..##..#.......#.#...#..........
.....#.......#.....#....#......
..........##..#................
....##.#..###...#..##.....#.#..
..#..#.#.#...#......#...#.....#
....#.#....#...####.##.........
..#.........##...##.#..#..#....
.#......#...#..#..##.#.........
.#....#.......#..##..##..#.#.#.
...........#....#......#.......
..#....#....#...............#..
..#.....#....###.##.....#.#..#.
#..........#.#......#.#....#...
....###...#.#.....#....#.####.#
........#......#...#...#..##..#
...##..............##.#.......#
#..........#...........#.#....#
#...#....#..####..#............
###....#........#..............
...#.##....................#.##
...#..#.....#.....##...#....#..
.......###.#...#.........#.....
.#..#.....#.#..#.....#.........
#................#.............
...#......#.#.....##.#.#....#..
...#..#.#..#.....#...#....#....
.......#......#........#.....#.
.#.##..##.....#.#......#.#.#...
#...............#.....#....#...
.....#...........#..##.........
.....#..#........##..#..#.....#
..###.#.#.......#.#...........#
##....##....#.#....##...#.##.##
..................##.#.#.....#.
.#...........###...#...........
.#.#....#......#....###.#......
.......#.##...#...#..#.#.......
..#.....#.#....#..#............
.....#..#..#....#..#.........#.
..##.#......#.....#...#.#..#.#.
.........#......#....##.......#
#........#..#.#......#...#.#..#
...#....#.#..#....##.......###.
..#...#......#.##..........#...
........#..#..#...#.......#....
.##.#..#...#..#........#.#.####
#..#..#..........#....##...#...
....#...#........##........#...
.#......#.......#..#..#........
#...#.#......#....#............
#........#..##.#...##..........
...#..##.....#......##.#..#.#..
.#.#.....#.....#.####.#..##....
..........###....#.##...#......
.......#.......#..#.#.#.##.#..#
..#.#....#......#.#...#.......#
.#...#....#......#...#.........
.#....#..#....#.##.#....#..##..
...#..#.#..................#...
.##..#.............##.........#
...#.#.#................#.....#
...###..###..................#.
........##.##..#.#...#.....#...
.##...##...#...#....#...#......
#..#....#..#..#.#....#..####...
.#...............##....##.#....
#..#................#...#..#...
.#....#.....#..#.#........#....
...............##.#..##..##....
.#......#........#....#.#...#.#
.#.....#...##.#........#.##.#.#
..###............#..#.#....#...
..#.....#.........#....#..#.#..
.##.....#.#..........#.#....##.
...#...#....#..#......#.#.#..#.
#.....#...#....##...#.......##.
.......#.#.........##..........
............##.#.##...#.......#
.....#........##...#........#..
.#........#.#.#.#....#.........
#....#..#....#.#..#...#.#......
....##...........#...#...##.#.#
......#...##.###.....#.........
............#..##....##......#.
......##....#...#.#....#......#
#..#..#..#.#.#.........#...##.#
...#.........#...#.........##.#
#.#.....#.......#.##..#..#.....
##................#......#....#
....#..#.......#....##.....#...
.....#..#...#...#......#.#....#
..#....#.....#.........#.....#.
..#..#..........#.....#........
.......#..##.#......#.#........
.............##.....#....#.....
...#....#..#.#.#...............
........#....##..#...#........#
..##...............#.....#....#
........##.#.##.#......#..#....
..#.##.......#..........##..#..
.#..............#.#.##.........
.#.......#....#....#.#.#.......
.#.##.......#....#......###.#..
.......#...#............##.....
........#.#..........##..#.....
...###..#......#.....##..#..#..
...........##......#....#......
..............#....#..#..#.#..#
....#...#......#.##...#........
.#.............#..#......###.#.
#...#..#.#..............##..#.#
....................#.........#
..##..#......#.###.....#...#.#.
.#....#.#........#...#........#
..#....#.....#..............#..
##..........#..#..#...#........
...........#..##...#.......#...
........##.............#.......
#....#........#..#.#.###..#....
...........##..........##......
#......#.....##.#.##......##...
..#......#.........#.......#..#
......#.#....##..##.#...#.#...#
......#..................##....
...#....#.#...#.#.......##.....
#.#...##...##........#...##....
..#.......#.#.#...#............
.......#......#..#...#.........
#...#..#...........##..........
......#....#.........#.#....#..
#......#........#...#..##....#.
.....#.......##..#.#......#..#.
...........#......#...#......#.
#.#.##.....#....#.....##......#
.....##..#.#.#.###........#.#..
...#...#.#......#......#.......
......###....#..##...#.#.##....
#.....#.....#..................
...#...#......#...............#
..#............##..#.....#.....
.#....#...#...#...#...#..#.....
.##......#.........#.###.#.....
#.#.##.......##...#........##.#
.##.#.#......#.....#...#.....#.
....####.##.......#..##..##.#..
#.#.......#..##....###..#...#..
..#..#....#...#.#.#.#...#......
##.........#.##................
........#.....................#
..#...........#..#..##.#..#.#..
#...#...................#.###..
##..#............#.........#..#
...............##...#...##....#
#.#.....#..#.......#......#....
.#...#......#............#.....
#.......#...#..#....#.......#..
...#....#.##.#....#....#.#.....
...#..#..............#..#.#..#.
.........#.....#.#...#..#....#.
..#..#..#...##.....##.#.....#..
.#.#..........#........#.......
...............#........#.#.#..
.#......#.....#..............#.
........#.#..............#.#...
.......#.#....#..#.#.#..#.#.##.
...##..#...#.#..#...........#..
#...###.#.....#..#........#....
.#...##...##...##.#.....###....
.........#......#.#..##.#.#....
#....#.#..#...#.#.#....#..#..#.
.#.#...#......###.....#........
#.....#.#.......#..#.#...#.....
.................#.#....#..##..
#...........#....###..#......#.
##.#..#....#.#.#.#.............
#.....#..#...#........#........
..#..#......#..#.##.#..........
...#....#..#..........#.#.##.##
#........#...#.......#..##.#...
.#.#..#....#.#....#......#.....
##.......##.#........#...#..##.
##.##.....#.......#####.#....#.
..#..###.#.#..#....###..#.##..#
#.........#.............#.#...#
..#...##.#..................#..
.....#.#....#.#..#.#........#.#
......#.......#.#..##.#.#..#...
..#......#.#..##......#..#....#
..##..#..#.##.#..#....#...##...
###....#...##....##.........#..
#........##.........#......#..#
...#.........#......#.##.......
.....#.#.#....#......#.........
..#...........#....#......#.#..
##........#...##.....######....
....#..#..##.......#..#..#.....
..#....#..##....#......##....#.
...##....#........##......#....
.#.#...###...#......#..........
#....#..#.##.........#...#.....
......#..#.........#.##.....#..
...#............##....#......#.
...#.....##.....#........#.#..#
......#.#..#......#.....#..##..
#.#.........##..........#......
..###.....#..#....##..........#
.............##..#....#..##....
....#.#....##..#......#...#....
....###.....#..#.......#.......
............#..#...............
......#........#..#......#.....
.#........#.......#.##.......#.
..#.........#..#.#.....##....#.
...#.......#.......#.......##.#
#......##.#.....#......##.#..#.
#..........#.................#.
....#..##...........#.....#.#..
#.###...#............#.#....#.#
....#......#.#..###....##..#...
....#...#..........##..........
..#.#............#...#...###...
......#...#......#..#.#........
.#.......#..#...........##...#.
##...#...##....##.#..#..#.#....
.......#........#............##
.#......#...#.#................
#.#........#.#....#..#.##......
.......#.#...#....##.......##..
........#.#.#.........##..##...
..##...............#.#.###.#...
......#.#....#..#......##.....#
###.........#.....#.#.....##...
.#.#....#.....#.#.##..#.......#
..#..#.#......#...##..##.#..#..
...#........#..#....#..........
#...#.#...#..##....##..........
.........#........#.##....#..#.
..#...#.#.......##..........##.
###...........##.#......#.#..#.
...#....#...#..#..#......#.....
.....##.......###.#....###..##.
...#...#..........#.#......#...
....#.....##...##..#.#........#
.....#...#..#.....##...##....#.
................##.#.##....##.#
.#..#..#....#.....#....#..#...#
.....###.....#.................
#...#..##..#.........#.........
.....#..#................#.....
.#..#...#......#..#............
...#...#.#....#....##...#...##.
..........#....#.#..#.#.....#..
....#...###.##...#..#..#......#
#...#.......#..........#..#....
.#............#..##.......#...#
....#..#...#............#..#.#.
.#....#.......#..#.#......#....
...#...#............#...#.....#
....#.#.#..##.#.....#...#.#....
......#.#.#......#..#...#.....#
......##.....#.............#...
..#...#..#.#....#..............
.#.#..#....#.#..##....###.##...
..#...........#....#.###.#....#
.....#.........#.#.............
...#.#.....#......###......##..
...#...#.....#.................
...#..#...##.....##.........#..
..#...#..#..##..#...#........#.
##..#.#.##.#....#...........#..
.......#....##....#...##..#..#.
#.......##.#...##...##..#.....#
....#.#...............#......#.
....#.#...#.....#....#......#..
.#.........#.#....###........#.
.#.#.....#.....#.#.#....#.#....
............#...........#.#..##
#...#......#..#......#.#.......
...#.#.#.....#..#...#..##......
...#.#..#...#....#.........#.#.
........#..#......##.....#...#.
...#..#..............#..#......
.........#.......#...#......#..
.#......#.....#.....#......#...
......#.......#....#...#.#.....
.#.....#.##..#........#...#....
#.....##..##....#.#.......#..#.
.#..#...#..#.......#...........
..#..#...#.....##....#.....#...
#.#..............#....#..#.....
.........##...#......#.##...##.
.###...#.#...#.....#.........#.
.....#..........##...#..#....##
.#..#......#....##.#...#.......
.............###.#.#..#.#.#...#
.......#...##..#..#.....###....
##.......#...........#....#.#..
##......#...#.#................
.#.####..##.#...............#..
..#...#.#.#..#...#........#...#
.##..##.##.....#.......#..#.#..
...................#......#.#..
#.##..#..........#.............
##..#......#....#.#............
.#........#.....##...#.........
.##....#..#..##..........#...#.
#..........##........#..#..#.#.
####.###.#.....#....#..#.#....#
..#...#...#.#.......#....#...#.
......##.###..##.#.###......#.#"""
position = 0
trees = 0
for line in tree_map.split("\n"):
if line[position % len(line)] == "#":
trees += 1
position += 3
print(trees)
|
# data for single play
num_rows = 23
num_columns = 10
block_size = 60
screen_width = block_size * 40
screen_length = block_size * 22
field_width = block_size * 10
field_length = block_size * 20
field_x = block_size * 7
field_y = block_size * 1
hold_ratio = 0.8
hold_block_size = block_size * hold_ratio
hold_width = hold_block_size * 5
hold_length = hold_block_size * 5
hold_x = block_size * 1
hold_y = block_size * 8
hold_text_x = block_size * 1
hold_text_y = block_size * 7
score_width = block_size * 5
score_length = block_size * 1
score_x = block_size * 1
score_y = block_size * 17
score_text_x = block_size * 1
score_text_y = block_size * 16
nexts_ratio = 0.7
nexts_block_size = block_size * nexts_ratio
nexts_width = nexts_block_size * 5
nexts_length = nexts_block_size * 5
nexts_text_x = field_x + field_width + block_size * 2
nexts_text_y = block_size * 1
nexts_x = [field_x + field_width + block_size * 2] * 5
nexts_y = [nexts_text_y + block_size + i * (nexts_length + 10) for i in range(5)]
op_field_x = nexts_x[0] + nexts_width + 80
op_field_y = field_y
op_field_width = field_width
op_field_length = field_length
fire_x = field_x + field_width + 30
fire_y = field_y
fire_width = block_size
fire_length = field_length
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLOR_BG = (43, 43, 43)
COLOR_I = (38, 203, 226)
COLOR_J = (0, 0, 200)
COLOR_L = (221, 109, 23)
COLOR_O = (243, 250, 0)
COLOR_S = (114, 238, 0)
COLOR_T = (140, 3, 140)
COLOR_Z = (250, 0, 0)
# color for fires
COLOR_F = (65, 85, 86)
COLORS = [COLOR_BG, COLOR_I, COLOR_J, COLOR_L, COLOR_O, COLOR_S, COLOR_T, COLOR_Z, COLOR_F]
# data for main menu
# title should be the center of the screen
title_name = 'Tetris'
title_size = [800, 300]
title_from_top = 100
title_center = [screen_width / 2, title_from_top + title_size[1] / 2]
title_x = title_center[0] - title_size[0] / 2
title_y = title_from_top
options_margin = 80 # margin between options
# single play option layout data
sp_size = [800, 160]
sp_center = [
screen_width / 2,
title_y + title_size[1] + options_margin + sp_size[1] / 2
]
sp_x = sp_center[0] - sp_size[0] / 2
sp_y = sp_center[1] - sp_size[1] / 2
sp_color = (38, 17, 115)
#online play option layout data
op_size = [800, 160]
op_center = [
screen_width / 2,
sp_y + sp_size[1] + options_margin + op_size[1] / 2
]
op_x = op_center[0] - op_size[0] / 2
op_y = op_center[1] - op_size[1] / 2
op_color = (100, 0, 0)
# challenge AI option layout data
ca_size = [800, 160]
ca_center = [
screen_width / 2,
op_y + op_size[1] + options_margin + ca_size[1] / 2
]
ca_x = ca_center[0] - ca_size[0] / 2
ca_y = ca_center[1] - ca_size[1] / 2
ca_color = (0, 102, 0)
# p: pause layout while playing
pause_option_x = 50
pause_option_y = 50
pause_option_size = [300, 50]
# pause layout
# pause background
pause_size = [800, 400]
pause_center = [screen_width / 2, screen_length /2]
pause_x = pause_center[0] - pause_size[0] / 2
pause_y = pause_center[1] - pause_size[1] / 2
pause_color = (0, 0, 150)
# pause resume button
pause_resume_from_top = 30
pause_resume_size = [600, 150]
pause_resume_center = [pause_center[0], pause_y + pause_resume_from_top + pause_resume_size[1] / 2]
pause_resume_x = pause_resume_center[0] - pause_resume_size[0] / 2
pause_resume_y = pause_y + pause_resume_from_top
# pause back-to-menu button
pause_to_menu_from_bottom = 30
pause_to_menu_size = [600, 150]
pause_to_menu_center = [pause_center[0], pause_y + pause_size[1] - pause_to_menu_from_bottom - pause_to_menu_size[1] / 2]
pause_to_menu_x = pause_to_menu_center[0] - pause_to_menu_size[0] / 2
pause_to_menu_y = pause_to_menu_center[1] - pause_to_menu_size[1] / 2 |
# This file will be patched by setup.py
# The __version__ should be set to the branch name
# Leave __baseline__ set to unknown to enable setting commit-hash
# (e.g. "develop" or "1.2.x")
# You MUST use double quotes (so " and not ')
__version__ = "3.2.0-develop"
__baseline__ = "unknown"
|
def hideUnits(units):
for i in range(len(units)):
hero.command(units[i], "move", {x: 34, y: 10 + i * 12})
peasants = hero.findFriends()
types = peasants[0].buildOrder.split(",")
for i in range(len(peasants)):
hero.command(peasants[i], "buildXY", types[i], 16, 10 + i * 12)
while True:
if hero.findNearestEnemy():
hideUnits(peasants)
break
while True:
enemy = hero.findNearestEnemy()
if enemy and hero.distanceTo(enemy) < 45:
hero.attack(enemy)
|
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
unique = set(nums)
ans = []
for i in range(1, len(nums) + 1):
if not i in unique:
ans.append(i)
return ans |
# https://www.codingame.com/training/easy/the-dart-101
TARGET_SCORE = 101
def simulate(shoots):
rounds, throws, misses, score = 1, 0, 0, 0
prev_round_score = 0
prev_shot = ''
for shot in shoots.split():
throws += 1
if 'X' in shot:
misses += 1
score -= 20
if prev_shot == 'X': score -= 10
if misses == 3: score = 0
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
else:
if '*' in shot:
a, b = map(int, shot.split('*'))
points = a * b
else:
points = int(shot)
if score + points == TARGET_SCORE:
return rounds
elif score + points > TARGET_SCORE:
throws = 3
score = prev_round_score
else:
score += points
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
return -1
def solution():
num_players = int(input())
player_names = [input() for _ in range(num_players)]
shortest_rounds = float('inf')
winner = ''
for i in range(num_players):
shoots = input()
rounds = simulate(shoots)
if rounds != -1 and rounds < shortest_rounds:
shortest_rounds = rounds
winner = player_names[i]
print(winner)
solution()
|
file = open("sentencesINA.txt","r")
file_lines = file.readlines()
file.close()
good_sentences = set([])
sentences = set([])
count = 0
big_sen_count = 0
good_sen_count = 0
good_value_count = 0
error = 0
for line in file_lines:
first_split = line.find("|| (('")
sentence = line[0:first_split]
split = line[first_split+3:].split("||")
label = split[0]
type = split[1]
website = split[2]
first = label.find("'")
second = label.find("'",first+1)
language = label[first:second+1]
first = label.find("[")
second = label.find("]")
value = label[first+1:second]
try:
if len(sentence) <= 500:
big_sen_count = big_sen_count + 1
if float(value) >= 0.9:
good_value_count = good_value_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
good_sen_count = good_sen_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
if sentence not in sentences:
good_sentences.add(line)
sentences.add(sentence)
else:
count = count + 1
else:
count = count + 1
except:
print(line)
error = error + 1
print("Sentences deleated:", count)
print("Unique Sentences:", len(good_sentences))
print("Small Sentences:", big_sen_count)
print("Value Sentences:", good_value_count)
print("Good Sentences:", good_sen_count)
print("Error:", error)
file = open("INAGoodSentences.txt","w")
file.writelines(good_sentences)
|
# Neat trick to make simple namespaces:
# http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
class Namespace(dict):
def __init__(self, *args, **kwargs):
super(Namespace, self).__init__(*args, **kwargs)
self.__dict__ = self
|
def question(n, pn):
_ = int(n)
expn = list(map(int, pn.split()))
p = 1
for pi in expn:
# 加算した場合(p << pi)と加算しなかった場合pの両方のビットを立る
p = (p << pi) | p
# 最終的にビットが立っている個数を数える
return f"{bin(p).count('1')}"
|
#
# @lc app=leetcode id=1448 lang=python3
#
# [1448] Count Good Nodes in Binary Tree
#
# https://leetcode.com/problems/count-good-nodes-in-binary-tree/description/
#
# algorithms
# Medium (72.08%)
# Likes: 1462
# Dislikes: 52
# Total Accepted: 102.9K
# Total Submissions: 141.1K
# Testcase Example: '[3,1,4,3,null,1,5]'
#
# Given a binary tree root, a node X in the tree is named good if in the path
# from root to X there are no nodes with a value greater than X.
#
# Return the number of good nodes in the binary tree.
#
#
# Example 1:
#
#
#
#
# Input: root = [3,1,4,3,null,1,5]
# Output: 4
# Explanation: Nodes in blue are good.
# Root Node (3) is always a good node.
# Node 4 -> (3,4) is the maximum value in the path starting from the root.
# Node 5 -> (3,4,5) is the maximum value in the path
# Node 3 -> (3,1,3) is the maximum value in the path.
#
# Example 2:
#
#
#
#
# Input: root = [3,3,null,4,2]
# Output: 3
# Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
#
# Example 3:
#
#
# Input: root = [1]
# Output: 1
# Explanation: Root is considered as good.
#
#
# Constraints:
#
#
# The number of nodes in the binary tree is in the range [1, 10^5].
# Each node's value is between [-10^4, 10^4].
#
#
# @lc code=start
# 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 goodNodes(self, root: TreeNode) -> int:
self.count = 0
if not root:
return self.count
self.count += 1
self.dfs(root, root.val)
return self.count
def dfs(self, root, curr_max):
if root.left:
self.dfs(root.left, max(curr_max, root.left.val))
if curr_max <= root.left.val:
self.count += 1
if root.right:
self.dfs(root.right, max(curr_max, root.right.val))
if curr_max <= root.right.val:
self.count += 1
# @lc code=end
|
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# 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.
#
# -*- coding: utf-8 -*-
"""
PyCOMPSs API - COMMONS - ERROR MESSAGES
=======================================
This file defines the public PyCOMPSs error messages displayed
by the api.
"""
def not_in_pycompss(decorator_name):
"""
Retrieves the "not in PyCOMPSs scope" error message.
:param decorator_name: Decorator name which requires the message.
:return: String - Not in PyCOMPSs error message.
"""
return "The " + decorator_name + \
" decorator only works within PyCOMPSs framework."
def cast_env_to_int_error(what):
"""
Retrieves the "can not cast from environment variable to integer" error
message.
:param what: Environment variable name.
:return: String - Can not cast from environment variable to integer.
"""
return "ERROR: " + what + " value cannot be cast from ENV variable to int"
def cast_string_to_int_error(what):
"""
Retrieves the "can not cast from string to integer" error message.
:param what: Environment variable name.
:return: String - Can not cast from string to integer.
"""
return "ERROR: " + what + " value cannot be cast from string to int"
def wrong_value(value_name, decorator_name):
"""
Retrieves the "wrong value at decorator" error message.
:param value_name: Wrong value's name
:param decorator_name: Decorator name which requires the message.
:return: String - Wrong value at decorator message.
"""
return "ERROR: Wrong " + value_name + \
" value at " + decorator_name + \
" decorator."
|
class boyce(object):
def bmMatch(self, pattern):
#algoritma didapatkan dari slide pa munir
last=[]
last = self.buildLast(pattern)
n = len(self.text)
m = len(pattern)
i = m-1
if (i > n-1):
return -1 #kalo ga ketemu file bersangkutan
j = m-1;
if (pattern[j] == self.text[i]):
if (j == 0):
return i # match
else: # looking-glass technique
i-=1
j-=1
else: # character jump technique
lo = last[ord(self.text[i])]
i = i + m - min(j, 1+lo)
j = m - 1
while (i <= n-1):
if (pattern[j] == self.text[i]):
if (j == 0):
return i # match
else: # looking-glass technique
i-=1
j-=1
else: # character jump technique
lo = last[ord(self.text[i])]
i = i + m - min(j, 1+lo)
j = m - 1
return -1 # no match
def buildLast(self,pattern):
last = [-1 for i in range(128)]
for i in range(len(pattern)):
last[ord(pattern[i])] = i
return last
def convertText(self,name_file):
with open(name_file) as f:
lines=f.read().lower()
line=lines.split("\n")
self.text=""
for row in line:
self.text+=row |
'''Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro
de Futebol, na ordem de colocação. Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time da Chapecoense.'''
classifBrasileirao = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Atlético-PR', 'São Paulo', 'Internacional', 'Corinthians', 'Fortaleza', 'Goiás', 'Bahia', 'Vasco', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'CSA', 'Chapecoense', 'Avaí')
print(f'Lista de times do Brasileirão: {classifBrasileirao}')
print(f'Os 5 primeiros são: {classifBrasileirao[0:5]}')
print(f'Os 4 últimos são: {classifBrasileirao[-4:]}')
print(f'Times em ordem alfabética: {sorted(classifBrasileirao)}')
posicao = classifBrasileirao.index('Chapecoense') + 1
print(f'A Chapecoense está na {posicao}ª posição.') |
"""Event classes and event-processing mechanisms
This package defines a set of "local" event classes which are
to be used by client applications. These include keyboard,
keypress, mousebutton and mousemove events. The package also
defines a set of modules which translated from GUI events/
callbacks to the local event classes. Finally, the package
provides mix in functionality for contexts to provide event
handling callback registration.
""" |
def whataboutstarwars():
i01.disableRobotRandom(30)
# PlayNeopixelAnimation("Ironman", 255, 255, 255, 1)
sleep(3)
# StopNeopixelAnimation()
i01.disableRobotRandom(30)
x = (random.randint(1, 3))
if x == 1:
fullspeed()
i01.moveHead(130,149,87,80,100)
AudioPlayer.playFile(RuningFolder+'/system/sounds/R2D2.mp3')
#i01.mouth.speak("R2D2")
sleep(1)
i01.moveHead(155,31,87,80,100)
sleep(1)
i01.moveHead(130,31,87,80,100)
sleep(1)
i01.moveHead(90,90,87,80,100)
sleep(0.5)
i01.moveHead(90,90,87,80,0)
sleep(1)
relax()
if x == 2:
fullspeed()
#i01.mouth.speak("Hello sir, I am C3po unicyborg relations")
AudioPlayer.playFile(RuningFolder+'/system/sounds/Hello sir, I am C3po unicyborg relations.mp3')
i01.moveHead(138,80)
i01.moveArm("left",79,42,23,41)
i01.moveArm("right",71,40,14,39)
i01.moveHand("left",180,180,180,180,180,47)
i01.moveHand("right",99,130,152,154,145,180)
i01.moveTorso(90,90,90)
sleep(1)
i01.moveHead(116,80)
i01.moveArm("left",85,93,42,16)
i01.moveArm("right",87,93,37,18)
i01.moveHand("left",124,82,65,81,41,143)
i01.moveHand("right",59,53,89,61,36,21)
i01.moveTorso(90,90,90)
sleep(1)
relax()
if x == 3:
i01.setHandSpeed("left", 0.85, 0.85, 0.85, 0.85, 0.85, 1.0)
i01.setHandSpeed("right", 1.0, 0.85, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 0.90, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.90)
i01.setTorsoSpeed(1.0, 1.0, 1.0)
i01.moveHead(80,86)
i01.moveArm("left",5,94,30,10)
i01.moveArm("right",7,74,50,10)
i01.moveHand("left",180,180,180,180,180,90)
i01.moveHand("right",180,2,175,160,165,180)
i01.moveTorso(90,90,90)
#i01.mouth.speak("mmmmmmh, from the dark side you are")
AudioPlayer.playFile(RuningFolder+'/system/sounds/mmmmmmh, from the dark side you are.mp3')
sleep(4.5)
relax()
|
class_cpp_header = """\
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
{includes}
#include "{class_short_name}.cppwg.hpp"
namespace py = pybind11;
typedef {class_full_name} {class_short_name};{smart_ptr_handle}
"""
class_cpp_header_chaste = """\
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
{includes}
//#include "PythonObjectConverters.hpp"
#include "{class_short_name}.cppwg.hpp"
namespace py = pybind11;
//PYBIND11_CVECTOR_TYPECASTER2();
//PYBIND11_CVECTOR_TYPECASTER3();
typedef {class_full_name} {class_short_name};{smart_ptr_handle}
"""
class_hpp_header = """\
#ifndef {class_short_name}_hpp__pyplusplus_wrapper
#define {class_short_name}_hpp__pyplusplus_wrapper
namespace py = pybind11;
void register_{class_short_name}_class(py::module &m);
#endif // {class_short_name}_hpp__pyplusplus_wrapper
"""
class_virtual_override_header = """\
class {class_short_name}_Overloads : public {class_short_name}{{
public:
using {class_short_name}::{class_base_name};
"""
class_virtual_override_footer = "}\n"
class_definition = """\
void register_{short_name}_class(py::module &m){{
py::class_<{short_name} {overrides_string} {ptr_support} {bases} >(m, "{short_name}")
"""
method_virtual_override = """\
{return_type} {method_name}({arg_string}){const_adorn} override {{
PYBIND11_OVERLOAD{overload_adorn}(
{tidy_method_name},
{short_class_name},
{method_name},
{args_string});
}}
"""
smart_pointer_holder = "PYBIND11_DECLARE_HOLDER_TYPE(T, {}<T>)"
free_function = """\
m.def{def_adorn}("{function_name}", &{function_name}, {function_docs} {default_args});
"""
class_method = """\
.def{def_adorn}(
"{method_name}",
({return_type}({self_ptr})({arg_signature}){const_adorn}) &{class_short_name}::{method_name},
{method_docs} {default_args} {call_policy})
"""
template_collection = {
"class_cpp_header": class_cpp_header,
"free_function": free_function,
"class_hpp_header": class_hpp_header,
"class_method": class_method,
"class_definition": class_definition,
"class_virtual_override_header": class_virtual_override_header,
"class_virtual_override_footer": class_virtual_override_footer,
"smart_pointer_holder": smart_pointer_holder,
"method_virtual_override": method_virtual_override,
}
|
# BGR
Blue = (255, 0, 0)
Green = (0, 255, 0)
Red = (0, 0, 255)
Black = (0, 0, 0)
White = (255, 255, 255)
|
def solve_power_consumption():
"""Print the power consumption."""
with open('../data/day03.txt') as f:
lines = [line.strip() for line in f]
ones = [sum(bit == '1' for bit in column) for column in zip(*lines)]
gamma = ''.join('1' if n > len(lines) / 2 else '0' for n in ones)
epsilon = ''.join('1' if char == '0' else '0' for char in gamma)
print(int(gamma, 2) * int(epsilon, 2))
if __name__ == '__main__':
solve_power_consumption()
|
# #08 Anomalous Counter!
# @DSAghicha (Darshaan Aghicha)
def counter_value(timer: int) -> int:
if timer == 0:
return 0
counter_dial: int = 0
prev_dial: int = 0
cycle_dial: int = 0
counter = 0
while timer > counter_dial:
counter += 1
prev_dial = counter_dial
counter_dial = counter_dial + 3 * (2 ** cycle_dial)
cycle_dial += 1
return 3 * (2 ** (cycle_dial - 1)) - (timer - prev_dial) + 1
def main() -> None:
try:
time: int = int(input("Enter time: "))
value: int = counter_value(time)
print(f"Counter value = {value}")
except ValueError:
print("I expected a number!!\n\n")
main()
if __name__ == "__main__":
main()
|
__version__ = '0.1.3'
__title__ = 'dadjokes-cli'
__description__ = 'Dad Jokes on your Terminal'
__author__ = 'sangarshanan'
__author_email__= 'sangarshanan1998@gmail.com'
__url__ = 'https://github.com/Sangarshanan/dadjokes-cli' |
"""
misc/bi_tree.py
"""
class BiTree:
"""
Binary Indexed Tree is represented as an array.
Each node of the Binary Indexed Tree stores the sum of some elements of the
original array. The size of the Binary Indexed Tree is equal to the size of
the original input array, denoted as n. This class use a size of n+1 for
ease of implementation.
How does Binary Indexed Tree work?
The idea is based on the fact that all positive integers can be represented
as the sum of powers of 2. For example 19 can be represented as 16 + 2 + 1.
Every node of the BiTree stores the sum of n elements, n is a power of 2.
For example, in the first diagram above (the diagram for getSum()), the sum
of the first 12 elements can be obtained by the sum of the last 4 elements
(from 9 to 12) plus the sum of 8 elements (from 1 to 8). The number of set
bits in the binary representation of a number n is O(Logn). Therefore, we
traverse at-most O(Logn) nodes in both getSum() and update() operations.
The time complexity of the construction is O(nLogn) as it calls update()
for all n elements.
See
- https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
- https://blog.csdn.net/Yaokai_AssultMaster/article/details/79492190
"""
def __init__(self, array: list):
n = len(array)
# create and initialize BiTree data as all zeroes list
self.data = [0]*(n+1)
self.list = array
# store the actual values in BiTree
for i in range(n):
self.update(i, array[i])
pass
def get(self, index: int):
return self.list[index] # if index < len(self.list) and index >= 0 else None
def getsum(self, index: int):
"""
Returns sum of a sub array [0..index-1].
"""
sum = 0 # initialize result
# BiTree index is 1 more than the index in original list.
ndx = index + 1
# traverse ancestors of BiTree data[index]
while ndx > 0:
# add current element of BiTree to sum
sum += self.data[ndx]
# get index of parent node
ndx -= ndx & (-ndx)
return sum
def update(self, index: int, value: int):
"""
Updates a note in Binary Index Tree (BiTree) at given list index, which
will add given value to the data index position of BiTree and all of its
ancestors in tree.
"""
# BiTree index is 1 more than the index in original list.
ndx = index + 1
# traverse all ancestors and update the value
while ndx > 0:
# add value to current node of BiTree
self.data[ndx] += value
# get index of parent node
ndx -= ndx & (-ndx)
self.list[index] = value
|
# -*- coding: utf-8 -*-
class Header(object):
def __init__(self, name):
if (isinstance(name, Header)):
name = name.normalized
name = name.strip()
self.normalized = name.lower()
def __hash__(self):
return hash(self.normalized)
def __eq__(self, right):
assert isinstance(right, Header), 'Invalid Comparison'
return self.normalized == right.normalized
def __str__(self):
return self.normalized
ACCEPT = Header('a')
CONTENT_ENCODING = Header('e')
CONTENT_LENGTH = Header('l')
CONTENT_RANGE = Header('n')
CONTENT_TYPE = Header('c')
FROM = Header('f')
FROM_EX = Header('g')
FROM_RIGHTS = Header('h')
REFER_TO = Header('r')
REPLY_TO = Header('p')
SEQUENCE = Header('q')
STREAM = Header('m')
SUBJECT = Header('s')
TIMESTAMP = Header('z')
TO = Header('t')
TRACE = Header('i')
TRANSFER_ENCODING = Header('x')
VIA = Header('v')
COMPACT_HEADERS = dict([(Header(key), value) for key, value in list({
'Accept': ACCEPT,
'Content-Encoding': CONTENT_ENCODING,
'Content-Length': CONTENT_LENGTH,
'Content-Range': CONTENT_RANGE,
'Content-Type': CONTENT_TYPE,
'From': FROM,
'X-From-Game': FROM_EX,
'X-From-Rights': FROM_RIGHTS,
'Refer-To': REFER_TO,
'Reply-To': REPLY_TO,
'X-Sequence': SEQUENCE,
'Stream': STREAM,
'Subject': SUBJECT,
'Timestamp': TIMESTAMP,
'To': TO,
'X-Trace-ID': TRACE,
'Transfer-Encoding': TRANSFER_ENCODING,
'Via': VIA
}.items())])
MULTI_HEADERS = frozenset([Header(name) for name in [
ACCEPT, 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Allow', 'Cache-Control',
'Connection', CONTENT_ENCODING, 'Content-Language', 'Expect', 'If-Match', 'If-None-Match', 'Pragma',
'Proxy-Authenticate', 'Set-Cookie', 'TE', 'Trailer', TRANSFER_ENCODING, 'Upgrade', 'User-Agent', 'Vary', VIA,
'Warning', 'WWW-Authenticate', 'X-Forwarded-For'
]])
|
# -*- coding: utf-8 -*-
"""Top-level package for SlimStaty."""
__author__ = """Andy Mroczkowski"""
__email__ = 'a@mrox.co'
__version__ = '0.1.0'
|
#работаем с оператором условия
brand='Volvo'
engine_volume=1.6 #объем двигателя
horsepower=200 #лошадиные силы
sunroof=True #люк на крыше
# проверка условия
# if horsepower<80:print("No tax")
# else:print('Tax')
# tax=0
#
# if horsepower<80:
# tax=0
# elif horsepower<100:
# tax=1000
# elif horsepower<150:
# tax=10000
# else:
# tax=15000
# print(tax)
# if для присваивания
coolcar = 0
if sunroof == 1:
coolcar=1
else: coolcar=0
print(coolcar)
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and not popped:
return True
if len(pushed) != len(popped):
return False
popIdx = 0
count = 0
stack = []
for i in range(len(pushed)):
stack.append(pushed[i])
while len(stack) > 0 and stack[-1] == popped[popIdx]:
stack.pop()
popIdx += 1
return len(stack) == 0
|
"""
62. Unique Paths
Medium
7114
267
Add to List
Share
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Example 3:
Input: m = 7, n = 3
Output: 28
Example 4:
Input: m = 3, n = 3
Output: 6
Constraints:
1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 109.
"""
# approach: dynamic programming
# memory: O(m * n)
# runtime: O(m * n)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
lookup = [[1 for i in range(n)] for j in range(m)]
for row in range(m):
for col in range(n):
if row > 0 and col > 0: # add the top and left
lookup[row][col] = lookup[row - 1][col] + lookup[row][col - 1]
return lookup[-1][-1]
|
unsorted_list = [("w",23), (9,1), ("543",99), ("sena",18)]
print(sorted(unsorted_list, key=lambda x: x[1]))
list = [43, 743, 342, 8874, 49]
print(sorted(list, reverse=True)) |
# This is a handy reverses the endianess of a given binary string in HEX
input = "020000000001017c037e163f8dfee4632a8cf6c87187d3cb61224e6dae8f4b0ed0fae3a38008570000000017160014c5729e3aaacb6a160fa79949a8d7f1e5cd1fbc51feffffff0288102c040000000017a914ed649576ad657747835d116611981c90113c074387005a62020000000017a914e62a29e7d756eb30c453ae022f315619fe8ddfbb8702483045022100b40db3a574a7254d60f8e64335d9bab60ff986ad7fe1c0ad06dcfc4ba896e16002201bbf15e25b0334817baa34fd02ebe90c94af2d65226c9302a60a96e8357c0da50121034f889691dacb4b7152f42f566095a8c2cec6482d2fc0a16f87f59691e7e37824df000000"
def test():
assert reverse("") == ""
assert reverse("F") == "F"
assert reverse("FF") == "FF"
assert reverse("00FF") == "FF00"
assert reverse("AA00FF") == "FF00AA"
assert reverse("AB01EF") == "EF01AB"
assert reverse("b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f1963") == "63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"
def reverse(input):
res = "".join(reversed([input[i:i+2] for i in range(0, len(input), 2)]))
return res
if __name__ == "__main__":
test()
print(reverse(input))
|
# startswith
# endswith
inp = "ajay kumar"
out = inp.startswith("aj")
print(out)
out = inp.startswith("jay")
print(out)
# inp1 = "print('a')"
inp1 = "# isdecimal -> given a string, check if it is decimal"
out = inp1.startswith("#")
print(out) |
class Queue(object):
"""
Implment Queue using List
"""
def __init__(self):
self._list = []
def enqueue(self, value):
self._list.append(value)
def dequeue(self):
try:
value = self._list[0]
del self._list[0]
return value
except IndexError:
print("is empty")
def size(self):
return len(self._list)
def top(self):
if self.size() is 0:
return 0
return self._list[-1]
class Stack(object):
def __init__(self):
self.queue = Queue()
self.emptyQueue = Queue()
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.queue.enqueue(x)
def pop(self):
"""
Put values of `queue` untail last one.
"""
if self.queue.size() is 0:
print("is empty")
return
while(self.queue.size() is not 1):
self.emptyQueue.enqueue(self.queue.dequeue())
value = self.queue.dequeue()
self.queue, self.emptyQueue = self.emptyQueue, self.queue
return value
def top(self):
"""
:rtype: int
"""
return self.queue.top()
def empty(self):
"""
:rtype: bool
"""
return self.queue.size() is 0
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 15:44:41 2019
@author: f.divruno
"""
ms = 1e-3
us = 1e-6
MHz = 1e6
GHz = 1e9
km = 1e3
minute = 60
hr = 60*minute
km_h = km/hr
k_bolt = 1.38e-23
def Apply_DISH(Telescope_list,Band='B1',scaling = 'Correlator_opimized', atten = 0):
"""
scaling:
Correlator_optimized scales the input signals so tht the noise (without RFI) scales to 0.335*Stdv(noise) = 1 level of ADC.
Linearity_optimized scales the input signals so that the RMS power (noise + RFI) scales to the full scale of the ADC (minimum clipping)
Defined_Gain scales the input signal by a defined atten, parameter atten needs to be provided
Band: 'B1' 'B2' 'B3' 'B4' 'B5a' 'B5b'
"""
# SampleRate = Telescope_list[0].SampleRate
# Duration = Telescope_list[0].Duration
for i in range(len(Telescope_list)):
#filter and scales the signals according to the Band and optimiztion selected, attenuation can be provided.
Telescope_list[i].Apply_analog_chain(Band,scaling,atten=0,f_offset=0)
# The signal inputing to the ADC is in the variable Receiver.ADC_input
# digitize the signals.
Telescope_list[i].Apply_ADC(nBits=12)
# The output signal is stored in Receiver.ADC_output
#TO-DO: frequency offset scheme.
Telescope_list[i].Apply_antSampleRate()
return Telescope_list
|
for _ in range(int(input())):
a,b,c=map(int,input().split())
ans=a+c-b-b
ans=abs(ans)
c1=ans%3
c2=ans%(-3)
c2=abs(c2)
if c1<c2:
print(c1)
else:
print(c2) |
"""Config for the `config-f` setting in StyleGAN2."""
_base_ = ['./stylegan2_c2_ffhq_256_b4x8_800k.py']
model = dict(
disc_auxiliary_loss=dict(use_apex_amp=False),
gen_auxiliary_loss=dict(use_apex_amp=False),
)
total_iters = 800002
apex_amp = dict(mode='gan', init_args=dict(opt_level='O1', num_losses=2))
resume_from = None
|
r1 = float(input('Digite o valor do Primeiro Segmento: '))
r2 = float(input('Digite o valor do Segundo Segmento: '))
r3 = float(input('Digite o valor do Terceiro Segmento: '))
if r1 < r2+r3 and r2< r1+r3 and r3 < r1+r2:
print('Os segmnetos acima podem formar triângulo')
else:
print('Os segmnetos acima não podem formar triângulo') |
# Author: Mujib Ansari
# Date: Jan 23, 2021
# Problem Statement: WAP to check given number is palindorome or not
def check_palindorme(num):
temp = num
reverse = 0
while temp > 0:
lastDigit = temp % 10
reverse = (reverse * 10) + lastDigit
temp = temp // 10
return "Yes" if num == reverse else "No"
n = int(input("Enter a number : "))
print("Entered number : ", n)
print("Is palindrome or not : ", check_palindorme(n))
|
#
# PySNMP MIB module CXCFG-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXCFG-IP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:16:46 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, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
cxCfgIp, Alias, cxIcmp, cxCfgIpSap = mibBuilder.importSymbols("CXProduct-SMI", "cxCfgIp", "Alias", "cxIcmp", "cxCfgIpSap")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
TimeTicks, Gauge32, ObjectIdentity, iso, Integer32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, IpAddress, NotificationType, Counter64, Counter32, ModuleIdentity, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Gauge32", "ObjectIdentity", "iso", "Integer32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "IpAddress", "NotificationType", "Counter64", "Counter32", "ModuleIdentity", "Unsigned32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
cxCfgIpAddrTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1), )
if mibBuilder.loadTexts: cxCfgIpAddrTable.setStatus('mandatory')
cxCfgIpAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1), ).setIndexNames((0, "CXCFG-IP-MIB", "cxCfgIpAdEntAddr"))
if mibBuilder.loadTexts: cxCfgIpAddrEntry.setStatus('mandatory')
cxCfgIpAdEntAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpAdEntAddr.setStatus('mandatory')
cxCfgIpAdEntIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntIfIndex.setStatus('mandatory')
cxCfgIpAdEntNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntNetMask.setStatus('mandatory')
cxCfgIpAdEntBcastAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntBcastAddr.setStatus('mandatory')
cxCfgIpAdEntSubnetworkSAPAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 5), Alias()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntSubnetworkSAPAlias.setStatus('mandatory')
cxCfgIpAdEntRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntRowStatus.setStatus('mandatory')
cxCfgIpAdEntState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("on", 1), ("off", 2), ("onether", 3), ("ontoken", 4))).clone('on')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntState.setStatus('mandatory')
cxCfgIpAdEntPeerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 8), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntPeerAddr.setStatus('mandatory')
cxCfgIpAdEntRtProto = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("rip", 2), ("ospf", 3))).clone('rip')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntRtProto.setStatus('mandatory')
cxCfgIpAdEntMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(64, 4096)).clone(1600)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntMtu.setStatus('mandatory')
cxCfgIpAdEntReplyToRARP = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntReplyToRARP.setStatus('mandatory')
cxCfgIpAdEntSRSupport = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 15, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpAdEntSRSupport.setStatus('mandatory')
cxCfgIpPingTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1), )
if mibBuilder.loadTexts: cxCfgIpPingTable.setStatus('mandatory')
cxCfgIpPingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1), ).setIndexNames((0, "CXCFG-IP-MIB", "cxCfgIpPingDestAddr"))
if mibBuilder.loadTexts: cxCfgIpPingEntry.setStatus('mandatory')
cxCfgIpPingIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingIndex.setStatus('mandatory')
cxCfgIpPingDestAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingDestAddr.setStatus('mandatory')
cxCfgIpPingGapsInMs = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingGapsInMs.setStatus('mandatory')
cxCfgIpPingNbOfPings = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4000000)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingNbOfPings.setStatus('mandatory')
cxCfgIpPingDataSize = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300)).clone(64)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingDataSize.setStatus('mandatory')
cxCfgIpPingRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingRowStatus.setStatus('mandatory')
cxCfgIpPingTriggerSend = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipIdle", 1), ("ipSend", 2))).clone('ipIdle')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpPingTriggerSend.setStatus('mandatory')
cxCfgIpPingNbTx = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingNbTx.setStatus('mandatory')
cxCfgIpPingNbReplyRx = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingNbReplyRx.setStatus('mandatory')
cxCfgIpPingNbErrorRx = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingNbErrorRx.setStatus('mandatory')
cxCfgIpPingLastSeqNumRx = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingLastSeqNumRx.setStatus('mandatory')
cxCfgIpPingLastRoundTripInMs = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 24), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingLastRoundTripInMs.setStatus('mandatory')
cxCfgIpPingAvgRoundTripInMs = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 25), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingAvgRoundTripInMs.setStatus('mandatory')
cxCfgIpPingMinRoundTripInMs = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 26), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingMinRoundTripInMs.setStatus('mandatory')
cxCfgIpPingMaxRoundTripInMs = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 27), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingMaxRoundTripInMs.setStatus('mandatory')
cxCfgIpPingLastNumHopsTraveled = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 11, 1, 1, 28), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpPingLastNumHopsTraveled.setStatus('mandatory')
cxCfgIpRIP = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 16, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgIpRIP.setStatus('mandatory')
cxCfgRIPII = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 16, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cxCfgRIPII.setStatus('mandatory')
cxCfgIpMibLevel = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 16, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxCfgIpMibLevel.setStatus('mandatory')
mibBuilder.exportSymbols("CXCFG-IP-MIB", cxCfgIpPingDestAddr=cxCfgIpPingDestAddr, cxCfgIpPingTriggerSend=cxCfgIpPingTriggerSend, cxCfgIpPingLastSeqNumRx=cxCfgIpPingLastSeqNumRx, cxCfgIpPingAvgRoundTripInMs=cxCfgIpPingAvgRoundTripInMs, cxCfgIpAdEntRtProto=cxCfgIpAdEntRtProto, cxCfgIpAdEntNetMask=cxCfgIpAdEntNetMask, cxCfgIpPingNbTx=cxCfgIpPingNbTx, cxCfgIpAdEntMtu=cxCfgIpAdEntMtu, cxCfgIpPingIndex=cxCfgIpPingIndex, cxCfgIpAdEntReplyToRARP=cxCfgIpAdEntReplyToRARP, cxCfgIpAdEntBcastAddr=cxCfgIpAdEntBcastAddr, cxCfgIpPingNbOfPings=cxCfgIpPingNbOfPings, cxCfgIpPingMinRoundTripInMs=cxCfgIpPingMinRoundTripInMs, cxCfgIpPingLastNumHopsTraveled=cxCfgIpPingLastNumHopsTraveled, cxCfgIpPingMaxRoundTripInMs=cxCfgIpPingMaxRoundTripInMs, cxCfgIpAdEntSRSupport=cxCfgIpAdEntSRSupport, cxCfgIpPingLastRoundTripInMs=cxCfgIpPingLastRoundTripInMs, cxCfgRIPII=cxCfgRIPII, cxCfgIpAdEntSubnetworkSAPAlias=cxCfgIpAdEntSubnetworkSAPAlias, cxCfgIpAdEntRowStatus=cxCfgIpAdEntRowStatus, cxCfgIpMibLevel=cxCfgIpMibLevel, cxCfgIpPingTable=cxCfgIpPingTable, cxCfgIpAddrEntry=cxCfgIpAddrEntry, cxCfgIpPingNbReplyRx=cxCfgIpPingNbReplyRx, cxCfgIpAdEntIfIndex=cxCfgIpAdEntIfIndex, cxCfgIpAdEntState=cxCfgIpAdEntState, cxCfgIpAddrTable=cxCfgIpAddrTable, cxCfgIpPingDataSize=cxCfgIpPingDataSize, cxCfgIpPingRowStatus=cxCfgIpPingRowStatus, cxCfgIpPingGapsInMs=cxCfgIpPingGapsInMs, cxCfgIpRIP=cxCfgIpRIP, cxCfgIpPingNbErrorRx=cxCfgIpPingNbErrorRx, cxCfgIpAdEntPeerAddr=cxCfgIpAdEntPeerAddr, cxCfgIpAdEntAddr=cxCfgIpAdEntAddr, cxCfgIpPingEntry=cxCfgIpPingEntry)
|
class AttackGroup:
def __init__(self, botai, own, targets, iter):
self.botai = botai
self.own = own
self.targets = targets
self.iteration = iter
@property
def done(self):
return len(self.own) == 0 or len(self.targets) == 0
def actions(self, iter):
actions = []
target_units = self.botai.known_enemy_units.tags_in(self.targets)
if target_units.exists:
target = target_units.first
for unit in self.botai.units.tags_in(self.own):
actions.append(unit.attack(target))
else:
self.targets = set() #lost targets
return actions
def clear_tag(self, tag):
if tag in self.own:
self.own.remove(tag)
elif tag in self.targets:
self.targets.remove(tag)
|
def test_sm_create_contact_list(app):
i = "Перейти в списки компаний"
text = "список компаний %s"
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smParticipants)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smParticipants)
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки в контейнере
# если 0 - случайный выбор)
app.testHelperSMSearch.find_in_container_number(6, 0, 0)
app.testHelperSMSearch.press_search_button()
if app.testHelperSMSearch.check_results() == '0':
tr = 1
while app.testHelperSMSearch.check_results() == '0' and tr < 20:
app.session.open_SM_page(app.smParticipants)
app.testHelperSMSearch.find_in_container_number(6, 0, 0)
app.testHelperSMSearch.press_search_button()
tr = tr + 1
#app.testhelpersm.get_old_contact_list()
cd2 = app.current_date_time().strftime('%d.%m.%Y %H:%M')
app.testhelpersm.create_contact_list_10000(cd2, text)
#app.testhelpersm.create_purchases_company_list_50(cd2, text)
app.banner_link_button(30, i)
assert(app.testhelpersm.contact_or_purchases_list_is_present(cd2, text) == True)
#app.testhelpersm.get_link()
#def test_sm_delete_contact_list(app):
# app.session.ensure_login_sm(app.username, app.password)
# app.session.open_SM_page(app.smcompany_list)
# app.testhelpersm.delete_first_contact_list() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.