content
stringlengths
7
1.05M
with open("spiderman.txt") as song: print(song.read(2)) print(song.read(8)) print(song.read())
# -*- coding: utf-8 -*- # # Specifies the name of the last variable considered # before plotting # lastvar = "k" # # Specifies the columns to be plotted # and its label (in grace format) # col_contents = [(1, "\\f{Symbol} <r>"), (2, "\\f{Symbol} <dr>"), (3, "U\\sl")] # # Specifies the grace format of the x axis # xlabel = "\\f{Times-Italic}P"
print(open('teste_win1252.txt', errors='strict').read()) print(open('teste_win1252.txt', errors='replace').read()) print(open('teste_win1252.txt', errors='ignore').read()) print(open('teste_win1252.txt', errors='surrogateescape').read()) print(open('teste_win1252.txt', errors='backslashreplace').read())
# -------------- class_1 = ["Geoffrey Hinton", "Andrew Ng", "Sebastian Raschka", "Yoshua Bengio"] class_2 = ["Hilary Mason", "Carla Gentry", "Corinna Cortes"] new_class = class_1 + class_2 print(new_class) new_class.append("Peter Warden") print(new_class) new_class.remove("Carla Gentry") print(new_class) courses = {"Math" : 65, "English" : 70, "History" : 80, "French" : 70, "Science" : 60} total = 0 for i in courses: total += courses[i] print(total) percentage = total / len(courses) print(percentage) mathematics = {"Geoffrey Hinton" : 78, "Andrew Ng" : 95, "Sebastian Raschka" : 65, "Yoshua Benjio" : 50, "Hilary Manson" :70, "Corinna Cortes" : 66, "Peter Warden" : 75} topper = min(mathematics) print(topper) topper = topper.split() first_name = topper[0] last_name = topper[1] full_name = last_name + " " + first_name print(full_name) certificate_name = full_name.upper() print(certificate_name)
""" Regularization works by penalizing model complexity. If the initial model is not complex enough to correctly describe the data then no amount of regularization will help as the model needs to get more complex to improve, not less. """;
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" #print(full_name) #print(f"Hello, {full_name.title()}!") message = f"Hello, {full_name.title()}!" print(message) #print("\tPython") #print("Languages:\nPython\nC\nJavaScript") print("Languages:\n\tPython\n\tC\n\tJavaScript")
class FakeConfig(object): def __init__( self, src_dir=None, spec_dir=None, stylesheet_urls=None, script_urls=None, stop_spec_on_expectation_failure=False, stop_on_spec_failure=False, random=True ): self._src_dir = src_dir self._spec_dir = spec_dir self._stylesheet_urls = stylesheet_urls self._script_urls = script_urls self._stop_spec_on_expectation_failure = stop_spec_on_expectation_failure self._stop_on_spec_failure = stop_on_spec_failure self._random = random self.reload_call_count = 0 def src_dir(self): return self._src_dir def spec_dir(self): return self._spec_dir def stylesheet_urls(self): return self._stylesheet_urls def script_urls(self): return self._script_urls def stop_spec_on_expectation_failure(self): return self._stop_spec_on_expectation_failure def stop_on_spec_failure(self): return self._stop_on_spec_failure def random(self): return self._random def reload(self): self.reload_call_count += 1
class Timer: def __init__(self, bot, ring_every=1.0): self.bot = bot self.last_ring = 0.0 self.ring_every = ring_every @property def rings(self): if (self.bot.time - self.last_ring) >= self.ring_every: self.last_ring = self.bot.time return True else: return False
#!/usr/bin/python3 class ComplexThing: def __init__(self, name, data): self.name = name self.data = data def __str__(self): return self.name + ": " + str(self.data)
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> """ Dictionary storing numerical values. """ class NumberDict( dict ) : """ An instance of this class acts like an array of numbers with generalized (non-integer) indices. A value of zero is assumed for undefined entries. NumberDict instances support addition, and subtraction with other NumberDict instances, and multiplication and division by scalars. This class is used by the PhysicalUnit class to track units and their power. For example, for the unit 'm**2 / kg**3', the dictionary items are [('kg', -3), ('m', 2)]. """ def __getitem__( self, item ) : try: return( dict.__getitem__( self, item ) ) except KeyError: return( 0 ) def __coerce__( self, other ) : if( isinstance( other, dict ) ) : other = NumberDict( other ) other._removeUnneededDimensionlessUnit( ) return( self, other ) def __add__( self, other ) : sum_dict = NumberDict( ) for key in self : sum_dict[key] = self[key] for key in other : sum_dict[key] = sum_dict[key] + other[key] sum_dict._removeUnneededDimensionlessUnit( ) return( sum_dict ) def __sub__( self, other ) : sum_dict = NumberDict( ) for key in self : sum_dict[key] = self[key] for key in other : sum_dict[key] = sum_dict[key] - other[key] sum_dict._removeUnneededDimensionlessUnit( ) return( sum_dict ) def __mul__( self, other ) : new = NumberDict( ) for key in self : new[key] = other * self[key] new._removeUnneededDimensionlessUnit( ) return( new ) __rmul__ = __mul__ def __truediv__( self, other ) : new = NumberDict( ) for key in self : new[key] = self[key] / other new._removeUnneededDimensionlessUnit( ) return( new ) __div__ = __truediv__ def _removeUnneededDimensionlessUnit( self ) : """For internal use only.""" if( ( '' in self ) and ( len( self ) > 1 ) ) : del self['']
class Answer: def __init__(self, text, id): self.id = id self.text = text class Question: def __init__(self, id, text, answers, correct_id): self.id = id self.text = text self.answers = answers self.correct_id = correct_id class Quiz: def __init__(self, name, questions): self.name = name self.questions = questions quiz = Quiz( name="Самая первая викторина!", questions=[ Question( id=1, text="question 1", correct_id=1, answers=[ Answer(text="answer 1.1", id=1), Answer(text="answer 1.2", id=2), Answer(text="answer 1.3", id=3), Answer(text="answer 1.4", id=4), ], ), Question( id=2, text="question 2", correct_id=2, answers=[ Answer(text="answer 2.1", id=1), Answer(text="answer 2.2", id=2), Answer(text="answer 2.3", id=3), Answer(text="answer 2.4", id=4), ], ), Question( id=3, text="question 3", correct_id=3, answers=[ Answer(text="answer 3.1", id=1), Answer(text="answer 3.2", id=2), Answer(text="answer 3.3", id=3), Answer(text="answer 3.4", id=4), ], ), ], )
CATEGORIES = [ ('Arts & Entertainment', [ 'Books & Literature', 'Celebrity Fan/Gossip', 'Fine Art', 'Humor', 'Movies', 'Music', 'Television' ]), ('Automotive', [ 'Auto Parts', 'Auto Repair', 'Buying/Selling Cars', 'Car Culture', 'Certified Pre-Owned', 'Convertible', 'Coupe', 'Crossover', 'Diesel', 'Electric Vehicle', 'Hatchback', 'Hybrid', 'Luxury', 'MiniVan', 'Mororcycles', 'Off-Road Vehicles', 'Performance Vehicles', 'Pickup', 'Road-Side Assistance', 'Sedan', 'Trucks & Accessories', 'Vintage Cars', 'Wagon', ]), ('Business', [ 'Advertising', 'Agriculture', 'Biotech/Biomedical', 'Business Software', 'Construction', 'Forestry', 'Government', 'Green Solutions', 'Human Resources', 'Logistics', 'Marketing', 'Metals', ] ), ('Careers', [ 'Career Planning', 'College', 'Financial Aid', 'Job Fairs', 'Job Search', 'Resume Writing/Advice', 'Nursing', 'Scholarships', 'Telecommuting', 'U.S. Military', 'Career Advice', ]), ('Education', [ '7-12 Education', 'Adult Education', 'Art History', 'Colledge Administration', 'College Life', 'Distance Learning', 'English as a 2nd Language', 'Language Learning', 'Graduate School', 'Homeschooling', 'Homework/Study Tips', 'K-6 Educators', 'Private School', 'Special Education', 'Studying Business', ]), ('Family & Parenting', [ 'Adoption', 'Babies & Toddlers', 'Daycare/Pre School', 'Family Internet', 'Parenting - K-6 Kids', 'Parenting teens', 'Pregnancy', 'Special Needs Kids', 'Eldercare', ]), ('Health & Fitness', [ 'Exercise', 'A.D.D.', 'AIDS/HIV', 'Allergies', 'Alternative Medicine', 'Arthritis', 'Asthma', 'Autism/PDD', 'Bipolar Disorder', 'Brain Tumor', 'Cancer', 'Cholesterol', 'Chronic Fatigue Syndrome', 'Chronic Pain', 'Cold & Flu', 'Deafness', 'Dental Care', 'Depression', 'Dermatology', 'Diabetes', 'Epilepsy', 'GERD/Acid Reflux', 'Headaches/Migraines', 'Heart Disease', 'Herbs for Health', 'Holistic Healing', 'IBS/Crohn\'s Disease', 'Incest/Abuse Support', 'Incontinence', 'Infertility', 'Men\'s Health', 'Nutrition', 'Orthopedics', 'Panic/Anxiety Disorders', 'Pediatrics', 'Physical Therapy', 'Psychology/Psychiatry', 'Senor Health', 'Sexuality', 'Sleep Disorders', 'Smoking Cessation', 'Substance Abuse', 'Thyroid Disease', 'Weight Loss', 'Women\'s Health', ]), ('Food & Drink', [ 'American Cuisine', 'Barbecues & Grilling', 'Cajun/Creole', 'Chinese Cuisine', 'Cocktails/Beer', 'Coffee/Tea', 'Cuisine-Specific', 'Desserts & Baking', 'Dining Out', 'Food Allergies', 'French Cuisine', 'Health/Lowfat Cooking', 'Italian Cuisine', 'Japanese Cuisine', 'Mexican Cuisine', 'Vegan', 'Vegetarian', 'Wine', ]), ('Hobbies & Interests', [ 'Art/Technology', 'Arts & Crafts', 'Beadwork', 'Birdwatching', 'Board Games/Puzzles', 'Candle & Soap Making', 'Card Games', 'Chess', 'Cigars', 'Collecting', 'Comic Books', 'Drawing/Sketching', 'Freelance Writing', 'Genealogy', 'Getting Published', 'Guitar', 'Home Recording', 'Investors & Patents', 'Jewelry Making', 'Magic & Illusion', 'Needlework', 'Painting', 'Photography', 'Radio', 'Roleplaying Games', 'Sci-Fi & Fantasy', 'Scrapbooking', 'Screenwriting', 'Stamps & Coins', 'Video & Computer Games', 'Woodworking', ]), ('Home & Garden', [ 'Appliances', 'Entertaining', 'Environmental Safety', 'Gardening', 'Home Repair', 'Home Theater', 'Interior Decorating', 'Landscaping', 'Remodeling & Construction', ]), ('Law, Gov\'t & Politics', [ 'Immigration', 'Legal Issues', 'U.S. Government Resources', 'Politics', 'Commentary', ]), ('News', [ 'International News', 'National News', 'Local News', ]), ('Personal Finance', [ 'Beginning Investing', 'Credit/Debt & Loans', 'Financial News', 'Financial Planning', 'Hedge Fund', 'Insurance', 'Investing', 'Mutual Funds', 'Options', 'Retirement Planning', 'Stocks', 'Tax Planning', ]), ('Society', [ 'Dating', 'Divorce Support', 'Gay Life', 'Marriage', 'Senior Living', 'Teens', 'Weddings', 'Ethnic Specific', ]), ('Science', [ 'Astrology', 'Biology', 'Chemistry', 'Geology', 'Paranormal Phenomena', 'Physics', 'Space/Astronomy', 'Geography', 'Botany', 'Weather', ]), ('Pets', [ 'Aquariums', 'Birds', 'Cats', 'Dogs', 'Large Animals', 'Reptiles', 'Veterinary Medicine', ]), ('Sports', [ 'Auto Racing', 'Baseball', 'Bicycling', 'Bodybuilding', 'Boxing', 'Canoeing/Kayaking', 'Cheerleading', 'Climbing', 'Cricket', 'Figure Skating', 'Fly Fishing', 'Football', 'Freshwater Fishing', 'Game & Fish', 'Golf', 'Horse Racing', 'Horses', 'Hunting/Shooting', 'Inline Skating', 'Martial Arts', 'Mountain Biking', 'NASCAR Racing', 'Olympics', 'Paintball', 'Power & Motorcycles', 'Pro Basketball', 'Pro Ice Hockey', 'Rodeo', 'Rugby', 'Running/Jogging', 'Sailing', 'Saltwater Fishing', 'Scuba Diving', 'Skateboarding', 'Skiing', 'Snowboarding', 'Surfing/Bodyboarding', 'Swimming', 'Table Tennis/Ping-Pong', 'Tennis', 'Volleyball', 'Walking', 'Waterski/Wakeboard', 'World Soccer', ]), ('Style & Fashion', [ 'Beauty', 'Body Art', 'Fashion', 'Jewelry', 'Clothing', 'Accessories', ]), ('Technology & Computing', [ '3-D Graphics', 'Animation', 'Antivirus Software', 'C/C++', 'Cameras & Camcorders', 'Cell Phones', 'Computer Certification', 'Computer Networking', 'Computer Peripherals', 'Computer Reviews', 'Data Centers', 'Databases', 'Desktop Publishing', 'Desktop Video', 'Email', 'Graphics Software', 'Home Video/DVD', 'Internet Technology', 'Java', 'JavaScript', 'Mac Support', 'MP3/MIDI', 'Net Conferencing', 'Net for Beginners', 'Network Security', 'Palmtops/PDAs', 'PC Support', 'Portable', 'Entertainment', 'Shareware/Freeware', 'Unix', 'Visual Basic', 'Web Clip Art', 'Web Design/HTML', 'Web Search', 'Windows', ]), ('Travel', [ 'Adventure Travel', 'Africa', 'Air Travel', 'Australia & New Zealand', 'Bed & Breakfasts', 'Budget Travel', 'Business Travel', 'By US Locale', 'Camping', 'Canada', 'Caribbean', 'Cruises', 'Eastern Europe', 'Europe', 'France', 'Greece', 'Honeymoons/Getaways', 'Hotels', 'Italy', 'Japan', 'Mexico & Central America', 'National Parks', 'South America', 'Spas', 'Theme Parks', 'Traveling with Kids', 'United Kingdom', ]), ('Real Estate', [ 'Apartments', 'Architects', 'Buying/Selling Homes', ]), ('Shopping', [ 'Contests & Freebies', 'Couponing', 'Comparison', 'Engines', ]), ('Religion & Spirituality', [ 'Alternative Religions', 'Atheism/Agnosticism', 'Buddhism', 'Catholicism', 'Christianity', 'Hinduism', 'Islam', 'Judaism', 'Latter-Day Saints', 'Pagan/Wiccan', ]), ('Uncategorized', []), ('Non-Standard Content', [ 'Unmoderated UGC', 'Extreme Graphic/Explicit Violence', 'Pornography', 'Profane Content', 'Hate Content', 'Under Construction', 'Incentivized', ]), ('Illegal Content', [ 'Illegal Content', 'Warez', 'Spyware/Malware', 'Copyright Infringement', ]) ] def from_string(s): try: cat = s[3:] if s.startswith('IAB') else s if '-' in cat: tier1, tier2 = map(int, cat.split('-')) t1c = CATEGORIES[tier1 - 1][0] t2c = CATEGORIES[tier1 - 1][1][tier2 - 1] return '{}: {}'.format(t1c, t2c) else: return CATEGORIES[int(cat) - 1][0] except (ValueError, IndexError): return s
class VirusFoundException(Exception): """Exception raised for detecting a virus in a file upload""" pass class InvalidExtensionException(Exception): """Exception raised for an attachment with an invalid extension""" pass class InvalidFileTypeException(Exception): """Exception raised for an attachment of an invalid type""" pass class FileSizeException(Exception): """Exception raised for an attachment that is too large""" pass
print( "Welcome to the Shape Generator:" ) cont = True shape1 = 0 shape2 = 0 shape3 = 0 shape4 = 0 shape5 = 0 shape6 = 0 drawAnotherShape = False def menu(): print() print( "This program draw the following shapes:" ) print( f"{'1) Horizontal Line':>20s}" ) print( f"{'2) Vertical Line':>18s}" ) print( f"{'3) Rectangle':>14s}" ) print( f"{'4) Left slant right angle triangle':>36s}" ) print( f"{'5) Right slant right angle triangle':>37s}" ) print( f"{'6) Isosceles triangle':>23s}" ) def printShape1(length): print( f"Here is the horizontal line with length {length}:" ) for i in range( length ): print( "*", end="" ) print() def printShape2(length): print( f"Here is the vertical line with length {length}:" ) for i in range( length ): print( "*" ) def printShape3(length, width): print( f"Here is the rectangle with length {length} and width {width}:" ) for x in range( length ): for x in range ( width): print( "*",end="") print() def printShape4(height): print( f"Here is the left slant right angle triangle with height {height}:" ) for x in range( 1, height + 1 ): for y in range (x): print( "*", end="") print() def printShape5(height): print( f"Here is the right slant right angle triangle with height {height}:" ) for x in range( 1, height + 1 ): print( " " * (height - x), end=" " ) for y in range (x): print( "*", end="" ) print() def printShape6(height): print( f"Here is the isosceles triangle with height {height}:" ) for x in range( 1, height + 1 ): for y in range (height - x + 1): print( " " , end="" ) for z in range(x * 2 - 1): print( "*", end="") print() def inputLength(): length = int( input( "Enter the length of the shape (1-20): " ) ) while length < 1 or length > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) length = int( input( "Enter the length of the shape (1-20): " ) ) return length def inputWidth(): width = int( input( "Enter the width of the rectangle (1-20): " ) ) while width < 1 or width > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) width = int( input( "Enter the width of the rectangle (1-20): " ) ) return width def inputHeight(): height = int( input( "Enter the height of the shape triangle (1-20): " ) ) while height < 1 or height > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) height = int( input( "Enter the height of the shape (1-20): " ) ) return height def inputDrawAnotherShape(): drawAnotherShape = input( "Would you like to draw another shape (y/n)? " ) while drawAnotherShape != "Y" and drawAnotherShape != "y" and drawAnotherShape != "N" and drawAnotherShape != "n": print( "Error! Incorrect input. Please enter 'y','Y','n' or 'N' to continue." ) drawAnotherShape = input( "Would you like to draw another shape (y/n)? " ) if drawAnotherShape == "Y" or drawAnotherShape == "y": cont = True else: cont = False return cont def goodbye(): print() print( "***************************************************************" ) print( "Here is a summary of the shapes that were drawn." ) print() print( f"Horizontal Line {shape1:45d}" ) print( f"Vertical Line {shape2:47d}" ) print( f"Rectangle {shape3:51d}" ) print( f"Left Slant Right Angle Triangle {shape4:29d}" ) print( f"Right Slant Right Angle Triangle {shape5:28d}" ) print( f"Isosceles Triangle {shape6:42d}" ) print() print( "Thank you for using the Shape Generator! Goodbye!" ) print( "***************************************************************" ) while cont == True: menu() shape = int( input( "Enter your choice (1-6): " ) ) while shape < 1 or shape > 6: print( "Invalid choice! Your choice must be between 1 and 6." ) shape = int( input( "Enter your choice (1-6): " ) ) if shape == 1: shape1 += 1 length = inputLength() printShape1( length ) elif shape == 2: shape2 += 1 length = inputLength() printShape2( length ) elif shape == 3: shape3 += 1 length = inputLength() width = inputWidth() printShape3( length, width ) elif shape == 4: shape4 += 1 height = inputHeight() printShape4( height ) elif shape == 5: shape5 += 1 height = inputHeight() printShape5( height ) elif shape == 6: shape6 += 1 height = inputHeight() printShape6( height ) cont = inputDrawAnotherShape() goodbye()
num = 45 # symVal = {1000:'M',900:'CM',500:'D',400:'CD',100:'C',90:'XC',50:'L',40:'XL',10:'X',9:'IX',5:'V',4:'IV',1:'I'} # romanNum = '' # i = 0 # while num > 0 : # curVal = list(symVal)[i] # for _ in range(num // curVal): # # if (divmod(num,4)[1] == 0 or divmod(num,9)[1] == 0): # romanNum += symVal[curVal] # num -= curVal # i += 1 # print(romanNum) class Solution(object): def __init__(self): self.roman = '' def intToRoman(self, num): self.num = num self.checkRoman(1000, 'M') self.checkRoman(500, 'D') self.checkRoman(100, 'C') self.checkRoman(50, 'L') self.checkRoman(10, 'X') self.checkRoman(5, 'V') self.checkRoman(1, 'I') return self.roman def checkRoman(self, value, strVal): numVal = self.num // value if (numVal > 0 and numVal < 4): for _ in range(0, numVal): self.roman += strVal self.num -= value * numVal if (value > 100 and self.num / (value - 100) > 0): self.roman += 'C' + strVal self.num -= (value - 100) if (value > 10 and self.num / (value - 10) > 0): self.roman += 'X' + strVal self.num -= (value - 10) if (value > 1 and self.num / (value - 1) > 0): self.roman += 'I' + strVal self.num -= value - 1 print(Solution().intToRoman(49))
# -*- coding: utf-8 -*- TO_EXCLUDE = [ "ACITAK", "ACITAK", "ADASUW", "AFEHOL", "AFENAA", "AFENAA", "AMUTEI", "AQUCOF", "AQUCOF", "AQUDAS", "AQUDAS", "ARADEE", "ATAGOQ", "ATAGOR", "ATAGOR", "BAXLA", "BAXLAP", "BAXLAP", "BICPOV", "BICPOV", "BIYWAK", "BIYWAK", "BIZLOO", "BUHVOP", "BUPVEP", "BUXZAX", "CAVWEC", "CIGXIA", "COFYOM", "COFYOM", "COFYOM", "COKNOH", "COKNOH01", "COXQOV", "COXQOV", "CUFMOG", "CUVJUA", "CUVJUA", "DIJYED", "DOVBIB", "EBUPUO", "EBUPUO", "EDIMOT", "EKIPAP01", "ENATUJ", "EQEHUE", "EQIZAF", "FAQLIV", "FEBZUH10", "FEKCEE", "FENXAY", "FIGTUL", "FIGTUL", "FIGZIG", "FIGZIG", "FIGZIG", "FIGZOM", "FIGZOM", "FIGZOM", "FIGZUS", "FIGZUS", "FINPUP01", "FIYGAY", "FODLAM02", "FUZBUX", "FUZBUX", "FUZBUX", "GASMUK", "GEVPOM", "GEVPOM", "GUVZEE", "GUVZII", "HAVHAG", "HAVHAG", "HAVHAQ", "HAVHAQ", "HAWVIN", "HAWVUZ", "HEQVUU", "HEQWAB", "HITQOR", "HITQOR", "HOJHUM", "HOMQEI", "IDIWIB", "IDIWOH", "IDIXID", "IDXID", "IJATUI", "IWIHON", "JAPYEH", "JAPYEH", "JAPYIL", "JAPYOR", "JAPYUX", "JAPZAE", "JAPZEI", "JAPZEI", "JAPZIM", "JAPZUY", "JAPZUY", "JEBWEV", "JIMNUR", "JIZJAF", "JIZJEJ", "JIZJIN", "JIZJOT", "JIZJUZ", "JUBQEE", "KAJZIH", "KAKTIA01", "KAKTIA01", "KAWCES", "KAWFUL", "KAWFUL", "KEPGES", "KEPGIW", "KEPGIW", "KEPGIW", "KERWIP", "KESSIM", "KESSIM", "KEXZUI", "KOCLEW", "KOGNIE", "KOGNIE", "KOVLOC", "KUTNUI", "KUTNUI", "LARRAA", "LARRAA", "LAVYIT", "LIDWAX", "LIDWAX", "MAHSUK", "MAHSUK01", "MAJLOZ", "MAPGUI", "MAVLED", "MELNEZ", "MELNEZ", "MIFQEZ", "MIFQOJ", "MIFQOJ", "MITFON", "MITSIS", "MOBBOU", "MOBBOU", "MOHQOQ", "MOHQOQ", "MOYZAC", "NAMTON", "NAMTON", "NAVRIO", "NECBUT", "NECBUT", "NECCUU", "NECCUU", "NENNOK", "NEZPOA", "NEZPUG", "NOJSUD", "NUHWUJ", "NUMLIQ", "NUZXAI", "NUZXAI", "OJANES", "OJANES", "OLIKUR", "ORIVUI", "PEFHIS", "PEHWEE", "PEPVEM", "PEPVEM", "PETWOC", "PETWUI", "PETXAP", "PIZHAJ", "PURVIH", "PURVIH", "QAMTEG", "QEJLID", # mixed valence not indicated "QIDFOB", "RAWFAZ", "REKPUV", "REKPUV", "RERROW", "RERROW", "REYDUX", "ROCKEZ", "ROCKEZ", "RUVHEX", "SATHUS", "SIBDUD", "SIBDUD", "SISMAL", "SISMAL", "SIYXIH", "SOKKAH", "SULPMS", "TAZGEG", "TAZGEG", "TAZGEG", "TCAZCO", "TCAZCO", "TCAZCO", "TEDDUC", "TEDDUC", "TEDDUC", "TEJFOG", "TEPWIX", "TEYLOB", "TICMEY", "TICMEY", "UDACEH", "UDOQAF", "UDOQAF", "UGARID", "UGARID", "VAYJOB", "VEYJOB", "VIGCET", "VOGBAU", "VOMMUH", "VUNQUS", "VUNQUS", "VUNQUS", "WAQFAY", "WAQKIK", "WAZKOZ", "WODZEX", "WOQKET", "WUDLIQ", "XAHREE", "XAHREE", "XAXPIX", "XEDJUN", "XEHVOW", "XEHVOW", "XOXTOW", "XOXTUC", "XUVDEZ", "YAKFIZ", "YAKFIZ", "YAMLOQ", "ZARBEZ", "ZASTUK", "ZASTUK", "ZEJWIX", "ZEJWOD", "ZEJXAQ", "ZEJXAQ", "ZEJXEU", "ZEQROE", "ZIFTIU", "ZITFIU", "ZITMUN", "RAXBAV", "BAYMOF", "GIMBIN", "KIKPOM", "VAHCEM", "ZUQVUC", "CAVXAB", "EBAGAR", "ACITAK", "ZUVVUH", "BERXAX", "BIWRUX", "ZICXOY", "XUDJUB", "ZASBEC", "PEXRIU", "TACJUE", "SOSVAX", "MATVEK", "YUSKIH", "SEBCUA", "NAYCIZ", "XAVJAF", "YAZPOG", "AQOPEB", "BAQMIR", "BIPLIX", "ZEGFOG", "KIFVOL", "CAGROT", "ROFDEV", "JIVWUH", "BIYWEO", "AKIYUO", "ROFCUK", "TIWPEU", "UFAXIJ", # Cr(III/V) disordered "YALPOR", # partially oxidized Fe and partially reduced Cu "FUGCUF", # Not so clear where the CSD got the Co(III) from "YIPDOR", # should have been excluded due to mixed valence "LOKJUR", # "do not allow distinguishing the Cu oxidation state." "TERBUQ", # mutlticonfigurational ground state "TAQDUN", "AMUTEI", "PEQXUF", "YEJJUT", "ROFDAR", "BARGAF", "FAXLOG", "ZIPFOT", "WALWEM", "UCIDEQ", "VIGQUA", "XAHREE", "WAZKOZ", "ZOCLAE", "EKINUH", "FELHUZ", "QICXEG", "WUBLEK", "ZERHAF", "FARROH", "ZEJXAQ", "UHOGUT", "XALXAJ", "SISMAL", "DEFCID", "YEGLAZ", "ZEJWIX", "CUNTOV", "FODLAM", "BAWGEO", "BUPHEA", "OLELAS", "DOCPOD", "WOKJOW", "WOQKET", "WOKJAI", "BEFZAP", "VUQWAG", "GATDAH", "TAQDUN", "WEZPEX", "LEKFEM", "BIJCUV", # highly covalent, Moessbauer is unclear "XALFUN", # from the paper Co(0) seems to be not that clea "FAGWOA", "TUQKUL", "YEXBOS", "XIHLIK", "KIWDOJ", "BALTUE", # Re(V/VII) resonance forms "BOJSUO", ]
# -*- coding: utf-8 -*- URL = '127.0.0.1' PORT = 27017 DATABASE = 'MyFunctions' COLLECTION = 'FunctionCheckers' FILE_PATH = '../examples/functions.py' CATCHER = 'result' IMPORT_POST = True STATIC_POST = True FUNC_POST = True
""" =========== Exercise 1 ============= Using a list, create a shopping list of 5 items. Then print the whole list, and then each item individually. """ shopping_list = [] # Fill in with some values print(shopping_list) # Print the whole list print() # Figure out how to print individual values """ =========== Exercise 2 ============= Find something that you can eat that has nutrition facts on the label. Fill in the dictionary below with the info on the label and try printing specific information. If you can't find anything nearby you can use this example: https://www.donhummertrucking.com/media/cms/Nutrition_Facts_388AE27A88B67.png """ # When ready to work on these exercises uncomment below code # nutrition_facts = {} # Fill in with the nutrition facts from the label # print(nutrition_facts) # Print all the nutrition facts # print(nutrition_facts["value"]) # Uncomment this line and pick a value to print individually """ =========== Exercise 3 ============= Python has a function built in to allow you to take input from the command line and store it. The function is called input() and it takes one argument, which is the string to display when asking the user for input. Here is an example: ``` >> name = input('What is your name?: ') >> print(name) ``` Using the information about type casting take an input from the command line (which is always a string), convert it to an int and then double it and print it. i.e. if the user provides 21 then the program should print 42 """ # When ready to work on these exercises uncomment below code # age = input('What is your age?: ') # print(age * 2) # Find a way to convert the age to an int and multiply by 2
#Parsing and Extracting data= "From Stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" atpos= data.find("@") print(atpos) atss= data.find(" ",atpos) #here it starts at 21 and then goes and find the next space print(atss) host= data[atpos+1: atss] #Now we are extracting the part that we are interested in print(host) #this prints uct.ac.za
"""Code to add interactive highlighting of series in matplotlib plots.""" class SelectorCursor(object): """An abstract cursor that may traverse a sequence of fixed length in any order, repeatedly, and which includes a None position. Executes a notifier when a position becomes selected or deselected. """ def __init__(self, num_elems, cb_activate, cb_deactivate): self.num_elems = num_elems """Length of sequence.""" self.cb_activate = cb_activate """A callback function to be called as f(i, active=True) when an index i is activated. """ self.cb_deactivate = cb_deactivate """Analogous to above, but with active=False.""" self.cursor = None """Valid cursor indices go from 0 to num_elems - 1. None is also a valid index. """ def goto(self, i): """Go to the new index. No effect if cursor is currently i.""" if i == self.cursor: return if self.cursor is not None: self.cb_deactivate(self.cursor, active=False) self.cursor = i if self.cursor is not None: self.cb_activate(self.cursor, active=True) def changeby(self, offset): """Skip to an offset of the current position.""" states = [None] + list(range(0, self.num_elems)) i = states.index(self.cursor) i = (i + offset) % len(states) self.goto(states[i]) def next(self): self.changeby(1) def bulknext(self): self.changeby(10) def prev(self): self.changeby(-1) def bulkprev(self): self.changeby(-10) class LineSelector: """Utility class for modifying matplotlib artists to highlight selected series. """ def __init__(self, axes_list): """Construct to select from among lines of the given axes.""" # Matplotlib artists that need to be updated. self.lines = [] self.leglines = [] self.legtexts = [] for axes in axes_list: new_lines = [line for line in axes.get_lines() if line.get_label() != '_nolegend_'] leg = axes.get_legend() if leg is not None: new_leglines = leg.get_lines() new_legtexts = leg.get_texts() else: new_leglines = [] new_legtexts = [] assert len(new_lines) == len(new_leglines) == len(new_legtexts) self.lines.extend(new_lines) self.leglines.extend(new_leglines) self.legtexts.extend(new_legtexts) self.cursor = SelectorCursor( len(self.lines), self.markLine, self.unmarkLine) def markLine(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(3) line.set_linewidth(3.0) legline.set_linewidth(3.0) legtext.set_color('blue') def unmarkLine(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(2) line.set_linewidth(1.0) legline.set_linewidth(1.0) legtext.set_color('black') def handler(self, event): k = event.key actionmap = { 'down': self.cursor.next, 'up': self.cursor.prev, 'pagedown': self.cursor.bulknext, 'pageup': self.cursor.bulkprev, } if k not in actionmap: return actionmap[k]() event.canvas.draw() def add_lineselector(figure): """Add a line selector for all axes of the given figure. Return the mpl connection id for disconnection later. """ lineselector = LineSelector(figure.get_axes()) # Workaround for weird Heisenbug. The handler isn't reliably called # when it's a bound method, but is called if I use a wrapper for # some reason. def wrapper(event): lineselector.handler(event) return figure.canvas.mpl_connect('key_press_event', wrapper)
# Solution def part1(data): stack = [] meta_sum = 0 gen = input_gen(data) for x in gen: if x != 0 or len(stack) % 2 == 1: stack.append(x) continue m = next(gen) while m > 0 or len(stack) > 0: for _ in range(m): meta_sum += next(gen) m = stack.pop() if len(stack) > 0 else 0 node = stack.pop() - 1 if len(stack) > 0 else 0 if node > 0: stack.append(node) stack.append(m) break return meta_sum def part2(data): gen = input_gen(data) children_count = next(gen) metadata_count = next(gen) root = Tree(None, children_count, metadata_count) current_node = root while True: children_count = next(gen) metadata_count = next(gen) new_node = Tree(current_node, children_count, metadata_count) current_node.children[current_node.index] = new_node current_node = new_node if children_count == 0: get_metadata(gen, current_node.metadata) while current_node.parent is not None: current_node = current_node.parent current_node.index += 1 if current_node.index < len(current_node.children): break get_metadata(gen, current_node.metadata) if current_node.parent is None and current_node.index == len(current_node.children): break return calculate_node_value(root) def input_gen(data): arr = data.split(' ') for x in arr: yield(int(x)) def get_metadata(gen, arr): for i in range(len(arr)): arr[i] = next(gen) def calculate_node_value(node): if len(node.metadata) == 0: return 0 if len(node.children) == 0: return sum(node.metadata) node_value = 0 for i in node.metadata: if i <= len(node.children): node_value += calculate_node_value(node.children[i - 1]) return node_value class Tree: def __init__(self, parent, children_count, metadata_count): self._parent = parent self._children = [None] * children_count self._metadata = [None] * metadata_count self._index = 0 @property def index(self): return self._index @index.setter def index(self, value): self._index = value @property def parent(self): return self._parent @property def children(self): return self._children @property def metadata(self): return self._metadata # Tests def test(expected, actual): assert expected == actual, 'Expected: %r, Actual: %r' % (expected, actual) test(138, part1('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) test(66, part2('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) # Solve real puzzle filename = 'data/day08.txt' data = [line.rstrip('\n') for line in open(filename, 'r')][0] print('Day 08, part 1: %r' % (part1(data))) print('Day 08, part 2: %r' % (part2(data)))
""" In this problem, we need a structure to store which character occurs how many times. It is best to use a dict object; but here we will use only lists. We will keep counts in a list of two element lists. For example: [["a",3],["b",5],["z",3]] """ def add_char(store,char): """add a character to the count store""" already_there = False for x in store: if x[0] == char: x[1] = x[1] + 1 already_there = True if not already_there: store.append([char,1]) def draw_histo(store): for x in store: print(x[0],x[1]*'*') input = input("Give me a string: ") count_store = [] for x in input: add_char(count_store,x) draw_histo(count_store)
## IMPORTANT: Must be loaded after `02-service-common.py ## announcement service service_env = dict() service_url = f'{hub_hostname}:{service_port}' if c.JupyterHub.internal_ssl: # if we are using end-to-end mTLS, then pass # certs to service and set scheme to `https` # TODO: Generate certs automatically PKI_STORE=c.JupyterHub.internal_certs_location service_env = { 'JUPYTERHUB_SSL_CERTFILE': f'{PKI_STORE}/hub-internal/hub-internal.crt', 'JUPYTERHUB_SSL_KEYFILE': f'{PKI_STORE}/hub-internal/hub-internal.key', 'JUPYTERHUB_SSL_CLIENT_CA': f'{PKI_STORE}/hub-ca_trust.crt', } service_url = f'https://{service_url}' else: # if not, set schema to `http` service_url = f'http://{service_url}' pass # NOTE: you must generate certs for services c.JupyterHub.services += [ { # Hub-wide announcments service 'name': 'announcement', 'url': service_url, 'command': [ sys.executable, '-m', 'jupyterhub_announcement', f'--AnnouncementService.fixed_message="Welcome to the {hub_id} JupyterHub server!"', f'--AnnouncementService.port={service_port}', f'--AnnouncementQueue.persist_path=announcements.json', f'--AnnouncementService.template_paths=["{hub_path}/share/jupyterhub/templates","{hub_path}/templates"]' ], 'environment': service_env } ] # increment service port service_port += 1
def test_binary_byte_str_code(fake): assert isinstance(fake.binary_byte_str(code=True), str) def test_decimal_byte_str_code(fake): assert isinstance(fake.decimal_byte_str(code=True), str) def test_binary_byte_str(fake): assert isinstance(fake.binary_byte_str(), str) def test_decimal_byte_str(fake): assert isinstance(fake.decimal_byte_str(), str) def test_nibble(fake): assert len(fake.nibble()) == 4 assert isinstance(fake.nibble(), str) def test_octet(fake): assert len(fake.octet()) == 8 assert isinstance(fake.octet(), str) def test_byte(fake): assert len(fake.byte()) == 8 assert isinstance(fake.byte(), str) def test_word(fake): assert len(fake.word()) == 16 assert isinstance(fake.word(), str)
#Classe usada para erros gerais relacionados as arestas class ArestasIncompatibilityException(Exception): def __init__(self,message :str): super().__init__(message)
# -*- coding: utf-8 -*- """ @author: krakowiakpawel9@gmail.com @site: e-smartdata.org """ class Drzewo: nazwa = 'Sosna' wiek = 40 wysokosc = 25 drzewo_1 = Drzewo() drzewo_2 = Drzewo() # %% print(id(drzewo_1)) print(id(drzewo_2)) # %% dir(drzewo_1) # %% drzewo_1.nazwa drzewo_1.wiek drzewo_1.wysokosc # %% drzewo_2.nazwa drzewo_2.wiek # %% drzewo_1.stan = 'dobry' print(dir(drzewo_2)) # %% Drzewo.miejsce = 'las' # %% # print(dir(drzewo_2)) # print(drzewo_2.miejsce) drzewo_2.miejsce = 'park' print(drzewo_2.miejsce)
nota1= float(input('Digite a primeira nota: ')) nota2= float(input('Digite a segunda nota: ')) med= (nota1+nota2)/2 if med<5: print('reprovado') if med>5 and med<6.9: print('recuperation') if med>7: print('parabens espertão')
""" Exercício 22 nome = str(input("Digite seu nome completo: ")) print(nome.upper()) print(nome.lower()) nome1 = len(nome) nome2 = nome1 - nome.count(' ') nome3 = nome.split() print('O nome {} possui {} caracteres, e o primeiro nome possui'.format(nome, nome2), len(nome3[0])) """ """ Exercício 23 valor = int(input('Digite qualquer valor entre 0 e 1999: ')) valor = valor + 10000 valor = str(valor) print('Unidades = {}'.format(valor[4])) print('Dezenas = {}'.format(valor[3])) print('Centenas = {}'.format(valor[2])) print('Milhares = {}'.format(valor[1])) """ """ Exercício 24 cid = str(input('Digite a cidade onde nasceu: ')) cid = cid.lower() cid = cid.split() print('sant' in cid[0]) """ """ Exercício 25 nome = str(input('Digite seu nome completo: ')) print('silva' in nome.lower()) """ """ Exercício 26 frase = str(input('Digite uma frase qualquer: ')).lower().strip() print(frase.count('a')) print(frase.find('a')+1) print(frase.rfind('a')+1) """ """ Exercício 27 n = str(input('Digite seu nome completo: ')).strip() nome = n.split() print('Primeiro nome: {}'.format(nome[0])) print('Sobrenome: {}'.format(nome[len(nome)-1])) """
#Embedded file name: /Users/versonator/Hudson/live/Projects/AppLive/Resources/MIDI Remote Scripts/LPD8/consts.py """ The following consts should be substituted with the Sys Ex messages for requesting a controller's ID response and that response to allow for automatic lookup""" ID_REQUEST = 0 ID_RESP = 0 GENERIC_STOP = 23 GENERIC_PLAY = 24 GENERIC_REC = 25 GENERIC_LOOP = 20 GENERIC_RWD = 21 GENERIC_FFWD = 22 GENERIC_TRANSPORT = (GENERIC_STOP, GENERIC_PLAY, GENERIC_REC, GENERIC_LOOP, GENERIC_RWD, GENERIC_FFWD) # 16! Device encoders GENERIC_ENC1 = 56 GENERIC_ENC2 = 57 GENERIC_ENC3 = 58 GENERIC_ENC4 = 59 GENERIC_ENC5 = 60 GENERIC_ENC6 = 61 GENERIC_ENC7 = 62 GENERIC_ENC8 = 63 GENERIC_ENC9 = 64 GENERIC_ENC10 = 65 GENERIC_ENC11 = 66 GENERIC_ENC12 = 67 GENERIC_ENC13 = 68 GENERIC_ENC14 = 69 GENERIC_ENC15 = 70 GENERIC_ENC16 = 71 GENERIC_ENCODERS = (GENERIC_ENC1, GENERIC_ENC2, GENERIC_ENC3, GENERIC_ENC4, GENERIC_ENC5, GENERIC_ENC6, GENERIC_ENC7, GENERIC_ENC8, GENERIC_ENC9, GENERIC_ENC10, GENERIC_ENC11, GENERIC_ENC12, GENERIC_ENC13, GENERIC_ENC14, GENERIC_ENC15, GENERIC_ENC16) GENERIC_SLI1 = 110 GENERIC_SLI2 = 111 GENERIC_SLI3 = 112 GENERIC_SLI4 = 113 GENERIC_SLI5 = 114 GENERIC_SLI6 = 115 GENERIC_SLI7 = 116 GENERIC_SLI8 = 117 GENERIC_SLIDERS = (GENERIC_SLI1, GENERIC_SLI2, GENERIC_SLI3, GENERIC_SLI4, GENERIC_SLI5, GENERIC_SLI6, GENERIC_SLI7, GENERIC_SLI8) GENERIC_BUT1 = 52 GENERIC_BUT2 = 53 GENERIC_BUT3 = 54 GENERIC_BUT4 = 55 GENERIC_BUT5 = 56 GENERIC_BUT6 = 57 GENERIC_BUT7 = 58 GENERIC_BUT8 = 59 GENERIC_BUT9 = 60 GENERIC_BUTTONS = (GENERIC_BUT1, GENERIC_BUT2, GENERIC_BUT3, GENERIC_BUT4, GENERIC_BUT5, GENERIC_BUT6, GENERIC_BUT7, GENERIC_BUT8) GENERIC_PAD1 = 80 GENERIC_PAD2 = 81 GENERIC_PAD3 = 82 GENERIC_PAD4 = 83 GENERIC_PAD5 = 85 GENERIC_PAD6 = 86 GENERIC_PAD7 = 87 GENERIC_PAD8 = 88 GENERIC_PADS = (GENERIC_PAD1, GENERIC_PAD2, GENERIC_PAD3, GENERIC_PAD4, GENERIC_PAD5, GENERIC_PAD6, GENERIC_PAD7, GENERIC_PAD8)
#Program 20 #Write a program to write roll no, name and marks of 'n' students in a data file "marks.dat" #Name: Vikhyat Jagini #Class: 12 #Date of Execution: 26/08/2021 n=int(input("Enter the number of students you want to store data of in the data file:")) f=open(r"C:\Python\Class 12 python\Lab Programs\BinaryFiles\marks.dat",'a') for i in range(n): print("Enter details of student", (i+1),"below") rol=int(input("Enter roll no of student:")) name=input("Enter name of student:") marks=float(input("Enter marks of student:")) rec=str(rol)+","+name+","+str(marks)+"\n" f.write(rec) f.close()
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if ( selector.startswith("/") or selector.startswith("./") or selector.startswith("(") ): return True return False def is_link_text_selector(selector): """ A basic method to determine if a selector is a link text selector. """ if ( selector.startswith("link=") or selector.startswith("link_text=") or selector.startswith("text=") ): return True return False def is_partial_link_text_selector(selector): """ A basic method to determine if a selector is a partial link text selector. """ if ( selector.startswith("partial_link=") or selector.startswith("partial_link_text=") or selector.startswith("partial_text=") or selector.startswith("p_link=") or selector.startswith("p_link_text=") or selector.startswith("p_text=") ): return True return False def is_name_selector(selector): """ A basic method to determine if a selector is a name selector. """ if selector.startswith("name=") or selector.startswith("&"): return True return False def get_link_text_from_selector(selector): """ A basic method to get the link text from a link text selector. """ if selector.startswith("link="): return selector[len("link="):] elif selector.startswith("link_text="): return selector[len("link_text="):] elif selector.startswith("text="): return selector[len("text="):] return selector def get_partial_link_text_from_selector(selector): """ A basic method to get the partial link text from a partial link selector. """ if selector.startswith("partial_link="): return selector[len("partial_link="):] elif selector.startswith("partial_link_text="): return selector[len("partial_link_text="):] elif selector.startswith("partial_text="): return selector[len("partial_text="):] elif selector.startswith("p_link="): return selector[len("p_link="):] elif selector.startswith("p_link_text="): return selector[len("p_link_text="):] elif selector.startswith("p_text="): return selector[len("p_text="):] return selector def get_name_from_selector(selector): """ A basic method to get the name from a name selector. """ if selector.startswith("name="): return selector[len("name="):] if selector.startswith("&"): return selector[len("&"):] return selector def is_id_selector(selector): """ A basic method to determine whether a ID selector or not """ if ":id" in selector: return True return False
# Qutebrowser config # Sessions c.auto_save.session = True c.session.lazy_restore = True # Tabs c.tabs.position = 'left' c.tabs.width = 200 c.tabs.new_position.unrelated = 'next' c.tabs.background = True # Hints c.hints.mode = 'number' c.hints.auto_follow = 'full-match' c.content.pdfjs = True c.content.javascript.enabled = False c.content.javascript.can_access_clipboard = True # Use user agent of upstream browser (Chromium) {{{ # to reduce fingerprinting and compatibility issues c.content.headers.user_agent = ( 'Mozilla/5.0 ({os_info}) ' 'AppleWebKit/{webkit_version} (KHTML, like Gecko) ' '{upstream_browser_key}/{upstream_browser_version} Safari/{webkit_version}' ) # }}} c.editor.command = ['xterm', '-e', 'vim', '{file}', '-c', 'normal {line}G{column0}l'] # Search {{{ c.url.searchengines['ddg'] = c.url.searchengines['DEFAULT'] c.url.auto_search = 'never' c.url.open_base_url = True config.bind('so', 'set-cmd-text -s :open -- ddg') config.bind('sO', 'set-cmd-text -s :open -t -- ddg') config.bind('spp', 'open -- ddg {clipboard}') config.bind('spP', 'open -- ddg {primary}') config.bind('sPp', 'open -t -- ddg {clipboard}') config.bind('sPP', 'open -t -- ddg {primary}') # }}} # Bindings for controlling adblock whitelist {{{ config.bind('tbh', 'config-cycle -p -t -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tbH', 'config-cycle -p -t -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBh', 'config-cycle -p -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBH', 'config-cycle -p -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') # }}} # Aliases {{{ # Wayback Machine {{{ c.aliases['wayback'] = 'spawn -u archive -t lookup wayback' c.aliases['wayback!'] = 'spawn -u archive lookup wayback' c.aliases['waybacksave'] = 'spawn -u archive -b save wayback' c.aliases['waybacksave!'] = 'spawn -u archive save wayback' c.aliases['wb'] = c.aliases['wayback'] c.aliases['wb!'] = c.aliases['wayback!'] c.aliases['wbs'] = c.aliases['waybacksave'] c.aliases['wbs!'] = c.aliases['waybacksave!'] # }}} # archive.today {{{ c.aliases['archive'] = 'spawn -u archive -t lookup archive.today' c.aliases['archive!'] = 'spawn -u archive lookup archive.today' c.aliases['archivesave'] = 'spawn -u archive -b save archive.today' c.aliases['archivesave!'] = 'spawn -u archive save archive.today' c.aliases['ar'] = c.aliases['archive'] c.aliases['ar!'] = c.aliases['archive!'] c.aliases['ars'] = c.aliases['archivesave'] c.aliases['ars!'] = c.aliases['archivesave!'] # }}} # Invidious {{{ c.aliases['invidious'] = 'spawn -u invidious' c.aliases['inv'] = c.aliases['invidious'] # }}} c.aliases['newtab'] = 'open -t about:blank' c.aliases['nt'] = c.aliases['newtab'] c.aliases['h'] = 'help' c.aliases['Help'] = 'help -t' c.aliases['H'] = c.aliases['Help'] # }}} config.load_autoconfig() # vim: set fdm=marker:
#!/usr/bin/env python3 """ Module with function to slice a matrix """ def np_slice(matrix, axes={}): """ Slices a matrix along a specific axes Returns the new matrix """ return matrix[-3:, -3:]
class RichTextBoxSelectionTypes(Enum, IComparable, IFormattable, IConvertible): """ Specifies the type of selection in a System.Windows.Forms.RichTextBox control. enum (flags) RichTextBoxSelectionTypes,values: Empty (0),MultiChar (4),MultiObject (8),Object (2),Text (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self, *args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass Empty = None MultiChar = None MultiObject = None Object = None Text = None value__ = None
CODE_GAP = '-' CODE_BACKGROUND = '-' class State: """ Node in the HMM architecture, with emission probability """ def __init__(self, emission, module_id, state_id): """ :param emission: Multinomial distribution of nucleotide generation, one float value for each nucleotide :param module_id: Id of the module which contains the state :param state_id: Id of the state in the ordered state sequence """ self.emission = emission self.module_id = module_id self.state_id = state_id def is_background(self): """ Specify, if state is outside primers and motifs and emits random nucleotides without preference :return: True, if state is background type """ return False def is_insert(self): """ Specify, if state is inside primers or motifs and emits random nucleotides without preference to simulate insertions between key states :return: True, if state is insert type """ return False def is_motif(self): """ Specify, if state is in motif sequence with preferred nucleotide in emission probabilities :return: True, if state is motif type """ return False def is_sequence(self): """ Specify, if state is in primer sequence with preferred nucleotide in emission probabilities :return: True, if state is sequence type """ return False def is_key(self): """ Specify, if state has specified nucleotide that is preferred in emission probabilities :return: True, if state is key type """ return False def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True class KeyState(State): """ State with specified nucleotide that is preferred in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): State.__init__(self, emission, module_id, state_id) self.nucleotide = nucleotide self.first = first self.last = last def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True def is_key(self): return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.first def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.last class MotifState(KeyState): """ State in motif sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, first, last) self.module_id = module_id def __str__(self): return self.nucleotide.upper() def is_motif(self): return True class SequenceState(KeyState): """ State in primer sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, True, True) self.module_id = module_id def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True class BackgroundState(State): """ State outside primers and motifs, that emits random nucleotides without preference """ def __init__(self, emission, state_id): State.__init__(self, emission, CODE_BACKGROUND, state_id) def __str__(self): return CODE_GAP def is_background(self): return True class InsertState(State): """ State inside primers or motifs, that emits random nucleotides without preference to simulate insertions between key states """ def __init__(self, emission, module_id, state_id): State.__init__(self, emission, module_id, state_id) def __str__(self): return CODE_GAP def is_insert(self): return True
def clean_string(s): result=[] for i in s: if i=="#": if result: result.pop(-1) else: result.append(i) return "".join(result)
def dimensoes(matriz): li = len(matriz) c = 1 for i in matriz: c = len(i) return li, c def soma_matrizes(m1, m2): l, c = dimensoes(m1) if dimensoes(m1) == dimensoes(m2): m3 = m1 for i in range(0, l): for col in range(0, c): m3[i][col] = m1[i][col] + m2[i][col] return m3 else: return False
def collatz(n): # recursion 재귀 함수 if n == 1: return [1] else: if n % 2 == 0: return [n] + collatz(n // 2) else: return [n] + collatz(3 * n + 1) n = int(input()) seq = collatz(n) print(seq) for i in range(len(seq)): print(seq[i], end=" ") print(len(seq))
n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo: ')) if n1 > n2: print('O primeiro número é maior') elif n2 > n1: print('O segundo número é maior') else: print('Os dois números são iguais')
''' isnumeric, isdigit, isdecimal (metodos de String) : essas funções verificam se o usuaario digiou um numero POSITIVO SEM PONTO FLUTUANTE ''' num1 = input('digiteum numero ') num2 = input('digite outro numero ') teste1 = num1.isnumeric() teste2 = num2.isnumeric() try: if teste1: num1 = int(num1) if teste2: num2 = int(num2) else: print('O segundo valor digitado nao e um numero') exit() else: print('O primeiro valor digtado nao e um numero') exit() resultado = num1 + num2 print(f'A soma entre {num1} e {num2} é: {resultado}') except: print('ERROR')
"""Sorting Algorithms config.""" FILES_REPO = "files/" IN_REPO = "files/in/" OUT_REPO = "files/out/" LOGS_REPO = "files/out/logs/" SEPARATOR = " - " STR_SIZE = 50 STR_NUMBER = 50 MAIN_DESCRIPTION = 'Sorting Algorithms' ALGORITHM_DESCRIPTION = 'execute sorting algorithm (insertionsort, \ heapsort, \ mergesort, \ quicksort, \ radixsort, \ selectionsort, \ shellsort)' NUMBER_DESCRIPTION = 'number of input values' ORDER_DESCRIPTION = 'order of input values (crescent, decreasing, random)' SIZE_DESCRIPTION = 'size of input values (small, large)'
""" Description: A demo of the ord() and chr() functions in python\ for ASCII table reference, please visit http://www.asciitable.com/ """ __author__ = "Canadian Coding" # chr() takes an int and returns the corresponding ASCII character print(chr(65)) # prints 'A' print(chr(97)) # prints 'a' # ord() takes a one letter string and returns the corresponding ASCII number as an int print(ord("A")) # Prints 65 print(ord("a")) # Prints 97 def alphabet_by_ord(): """Goes through and prints the uppercase alphabet using ord() and chr() """ current_letter = ord('A') # Initialize to A for letter in range(1,27): #Iterates over all 27 letters of the alphabet print(chr(current_letter)) current_letter += 1 # Move to next letters ordinance def capitalize_by_ord(letter = "a"): """Converts lowercase characters to uppercase using ord() and chr() Returns: (str): A message with the upper and original case version of the letter """ uppercase_letter = ord(letter) - 32 # Decreasing letters ordinance by offset return "Letter {} converted to {}".format(letter, chr(uppercase_letter)) alphabet_by_ord() print(capitalize_by_ord())
""" This module implements the Scorer Class. A Scorer tracks the match, mismatch, gap, and xdrop values. The Scorer is also responsible for calculating the dynamic programming function value and direction. """ class Scorer(): """Scorer Class""" def __init__ ( self, match, mismatch, gap, xdrop ): """ Scorer Constructor. Args: match (int): Match value mismatch (int): Mismatch value gap (int): Match value xdrop (int): X-Drop termination condition """ if not isinstance( match, int ): raise TypeError( "Invalid Match Score Type" ) if not isinstance( mismatch, int ): raise TypeError( "Invalid Mismatch Score Type" ) if not isinstance( gap, int ): raise TypeError( "Invalid Gap Score Type" ) if not isinstance( xdrop, int ): raise TypeError( "Invalid X-Drop Value Type" ) self.match = match self.mismatch = mismatch self.gap = gap self.xdrop = xdrop def calc_sq_value ( self, left_score, above_score, diag_score, nuch, nucv, max_score ): """ Computes the value of a square in the dynamic programming grid as a function of previous three squares and the two nucleotides. Args: left_score (Union[str, int]): Value of square to the left of output square above_score (Union[str, int]): Value of square above the output square diag_score (Union[str, int]): Value of square up and to the left of output square nuch (str): Horizontal sequence nucleotide associated with output square nucv (str): Vertical sequence nucleotide associated with output square max_score (int): The "best" score used to calculate X-Drop termination condition Returns: (Union[str, int]): The value of the square or "X" denoting the X-Drop termination condition has been triggered """ if not isinstance( left_score, (int, str) ): raise TypeError( "Invalid Left Square Score Type" ) if not isinstance( above_score, (int, str) ): raise TypeError( "Invalid Above Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( left_score, str ) and left_score != "X": raise ValueError( "Invalid Left Square Score Value" ) if isinstance( above_score, str ) and above_score != "X": raise ValueError( "Invalid Above Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if not isinstance( max_score, int ): raise TypeError( "Invalid Max Score Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) potential_values = [] if diag_score != "X": if nuch == nucv: potential_values.append( diag_score + self.match ) else: potential_values.append( diag_score + self.mismatch ) if left_score != "X": potential_values.append( left_score + self.gap ) if above_score != "X": potential_values.append( above_score + self.gap ) if len( potential_values ) == 0: return "X" res = max( potential_values ) if res <= max_score - self.xdrop: res = "X" return res def calc_sq_dir_back ( self, left_score, above_score, diag_score, nuch, nucv, this_score ): """ Computes the direction the this_score value came from in the dynamic programming grid. This corresponds to the inverse of the dynamic programming function. Args: left_score (Union[str, int]): Value of square to the left of this_value square above_score (Union[str, int]): Value of square above the this_value square diag_score (Union[str, int]): Value of square up and to the left of this_value square nuch (str): Horizontal sequence nucleotide associated with this_value square nucv (str): Vertical sequence nucleotide associated with this_value square this_score (int): The score of the square in the dynamic programming grid Returns: (Tuple[int, int]): The direction the this_score value came from given as a vector """ if not isinstance( left_score, (int, str) ): raise TypeError( "Invalid Left Square Score Type" ) if not isinstance( above_score, (int, str) ): raise TypeError( "Invalid Above Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( left_score, str ) and left_score != "X": raise ValueError( "Invalid Left Square Score Value" ) if isinstance( above_score, str ) and above_score != "X": raise ValueError( "Invalid Above Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if not isinstance( this_score, int ): raise TypeError( "Invalid Square Score Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) if diag_score != "X": if nuch == nucv and diag_score + self.match == this_score: return (-1, -1) if nuch != nucv and diag_score + self.mismatch == this_score: return (-1, -1) if left_score != "X": if left_score + self.gap == this_score: return (0, -1) if above_score != "X": if above_score + self.gap == this_score: return (-1, 0) raise RuntimeError( "Failure to calculate direction." ) def calc_sq_dir_forw ( self, right_score, below_score, diag_score, nuch, nucv ): """ Computes the direction the this_score value went to in the dynamic programming grid. Args: right_score (Union[str, int]): Value of square to the right of this square below_score (Union[str, int]): Value of square below the this square diag_score (Union[str, int]): Value of square down and to the right of this square nuch (str): Horizontal sequence nucleotide associated with this square nucv (str): Vertical sequence nucleotide associated with this square Returns: (Tuple[int, int]): The direction the this value went to given as a vector """ if not isinstance( right_score, (int, str) ): raise TypeError( "Invalid Right Square Score Type" ) if not isinstance( below_score, (int, str) ): raise TypeError( "Invalid Below Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( right_score, str ) and right_score != "X": raise ValueError( "Invalid Right Square Score Value" ) if isinstance( below_score, str ) and below_score != "X": raise ValueError( "Invalid Below Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) potential_values = [] if diag_score != "X": potential_values.append( diag_score ) if right_score != "X": potential_values.append( right_score ) if below_score != "X": potential_values.append( below_score ) if len( potential_values ) == 0: raise RuntimeError( "Failure to calculate direction." ) res = max( potential_values ) if res == diag_score: return (1, 1) elif res == right_score: return (0, 1) elif res == below_score: return (1, 0) raise RuntimeError( "Failure to calculate direction." )
class Node: def __init__(self, value, next=None): self.value = value self.next = next class LinkedList: def __init__(self, head=None): self.head = head def insert(self, value): node = Node(value) # Node of [3] if self.head is not None: node.next = self.head self.head = node def includes(self, value): current = self.head while current is not None: if current.value == value: return True else: current = current.next return False # insert before def append(self, value): new_node = Node(value) current = self.head if current is None: current = new_node else: while current.next is not None: current = current.next current.next = new_node def insert_before(self, new_value, value): # create new node newNode = Node(new_value) # find target node to insert node = self.head if node == None: return else: # search nodes if node.value == value: newNode.next = self.head self.head = newNode while node.next is not None: if node.next.value == value: newNode.next = node.next node.next = newNode return else: node = node.next def insert_after(self, value, new_value): newNode = Node(new_value) current = self.head if self.head == None: self.head = newNode return else: if current == value: return temp = self.head while temp.next != None: temp = temp.next temp.next = newNode def to_string(self): # defining a blank res variable results = "" # initializing ptr to head current = self.head # traversing and adding it to results while current: results += f"{ {current.value} } -> " current = current.next results += f"None" return results # Code challenge 7 def kth_from_end(self, k): length = -1 current = self.head while current: current = current.next length += 1 if k > length: return "That brings us out of the linked list" elif k < 0: return "please choose a positive number" else: current = self.head position = length - k for _ in range(0, position): current = current.next return current.value
#!/usr/bin/env python # -*- coding: utf-8 -*- db = { 'host': 'localhost', 'port': 6379 } dbnames = { 'default': 1, 'ephermal': 8 }
""" One of the most enjoyable hard questions on Leetcode. A really hard problem until you break it down into smaller subproblems """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def maxPathSum(root: TreeNode) -> int: ans = -float('inf') def find_max(node): nonlocal ans if not node: return 0 closed_loop = max(node.val, node.val + max(l := find_max(node.left), r := find_max(node.right))) ans = max(ans, closed_loop, l + node.val + r) return closed_loop find_max(root) return ans
class Tests(unittest.TestCase): def _sim_model(self, data: Tensor) -> Tensor: """ Simulated model for generating uncertainity scores. Intention is to be a placeholder until real models are used and for testing.""" return torch.rand(size=(data.shape[0],)) def setUp(self): # Init class self.sampler = Sampler(budget=10) # Init random tensor self.data = torch.rand(size=(10,2,2)) # dim (batch, length, features) # Params self.budget = 18 # All sample tests are tested for: # 1. dims (_, length, features) for input and output Tensors # 2. batch size == sample size def test_sample_random(self): self.assertEqual(self.sampler.sample_random(self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_random(self.data).shape[0], self.sampler.budget) def test_sample_least_confidence(self): self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[0], self.sampler.budget) # def test_sample_bayesian(self): # self.assertEqual(self.sampler.sample_bayesian(model=self.sampler._sim_model, no_models=3, data=self.data).shape[1:], self.data.shape[1:]) # self.assertEqual(self.sampler.sample_bayesian(model=self.sampler._sim_model, no_models=3, data=self.data).shape[0], self.sampler.budget) # def test_adversarial_sample(self): # self.assertEqual(self.sampler.sample_adversarial(self.data).shape[1:], self.data.shape[1:]) # self.assertEqual(self.sampler.sample_adversarial(self.data).shape[0], self.sampler.budget)
""" Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them. Note: The distance between two points on a plane is the Euclidean distance. Input : point = [[3, 3], [5, -1], [-2, 4]], K = 2 Output : [[3, 3], [-2, 4]] Square of Distance of origin from this point is (3, 3) = 18 (5, -1) = 26 (-2, 4) = 20 So rhe closest two points are [3, 3], [-2, 4]. Input : point = [[1, 3], [-2, 2]], K = 1 Output : [[-2, 2]] Square of Distance of origin from this point is (1, 3) = 10 (-2, 2) = 8 So the closest point to origin is (-2, 2) Approach: The idea is to calculate the Euclidean distance from the origin for every given point and sort the array according to the Euclidean distance found. Print the first k closest points from the list. Algorithm : Consider two points with coordinates as (x1, y1) and (x2, y2) respectively. The Euclidean distance between these two points will be: √{(x2-x1)2 + (y2-y1)2} Sort the points by distance using the Euclidean distance formula. Select first K points form the list Print the points obtained in any order. Complexity Analysis: Time Complexity: O(n log n). Time complexity to find the distance from the origin for every point is O(n) and to sort the array is O(n log n) Space Complexity: O(n). As we are making an array to store distance from the origin for each point. """ def kClosestPoints(points, K): if not points: return -1 points.sort(key = lambda point: point[0]**2 + point[1]**2) return points[:K] print(kClosestPoints([[3, 3], [5, -1], [-2, 4]], 2))
# -*- coding: utf-8 -*- #: The title of this site SITE_TITLE='HasGeek Funnel' #: Support contact email SITE_SUPPORT_EMAIL = 'test@example.com' #: TypeKit code for fonts TYPEKIT_CODE='' #: Google Analytics code UA-XXXXXX-X GA_CODE='' #: Database backend SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db' #: Secret key SECRET_KEY = 'make this something random' #: Timezone TIMEZONE = 'Asia/Calcutta' #: LastUser server LASTUSER_SERVER = 'https://auth.hasgeek.com/' #: LastUser client id LASTUSER_CLIENT_ID = '' #: LastUser client secret LASTUSER_CLIENT_SECRET = '' #: Used for attribution when shared a proposal on twitter TWITTER_ID = "hasgeek" #: Mail settings #: MAIL_FAIL_SILENTLY : default True #: MAIL_SERVER : default 'localhost' #: MAIL_PORT : default 25 #: MAIL_USE_TLS : default False #: MAIL_USE_SSL : default False #: MAIL_USERNAME : default None #: MAIL_PASSWORD : default None #: DEFAULT_MAIL_SENDER : default None MAIL_FAIL_SILENTLY = False MAIL_SERVER = 'localhost' DEFAULT_MAIL_SENDER = ('Bill Gate', 'test@example.com') # Required for Flask-Mail to work. MAIL_DEFAULT_SENDER = DEFAULT_MAIL_SENDER #: Logging: recipients of error emails ADMINS=[] #: Log file LOGFILE='error.log' #: Messages (text or HTML) WELCOME_MESSAGE = "The funnel is a space for proposals and voting on events. Pick an event to get started."
a = input('Digie algo: ') print('O tipo primitivo è :',type(a)) print('só tem espaços? ',a.isspace()) print('é numérico? ',a.isalnum()) print('è alfanumérico?', a.isalnum()) print('é alfabético? ', a.isalpha()) print('está em maúscilo?',a.isupper()) print('está em minúsculo? ', a.islower())
""" Account: This clump of functions manage the account features for the API. Their functions are like: - Main account management. - Register with {username} {email} {password} {confirmation}. - Login with {username} {password}. - Reset password {recovery key} with {new password} {confirmation}. - Logout. - Requires user logged in. - Close account. - Requires user logged in. - Profile management (All of these require user logged in). - Get profile. - Change password with {old password} {new password} {confirmation}. - Rate place {uuid} with {score}. - Remove rate from place {uuid}. - Bookmark place {uuid} (it will add the bookmark to the end). - Unbookmark place {uuid}. - Move bookmark {uuid} to the end or, if specified {uuid_other}, before {uuid_other}. """
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head = Node("head") self.size = 0 def __str__(self): cur = self.head.next out = "" while cur: out += str(cur.value) + "->" cur = cur.next return out[:-3] def is_empty(self): return self.size == 0 def peek(self): if self.is_empty(): raise Exception("Peeking from an empty stack") return self.head.next.value def push(self, value): node = Node(value) node.next = self.head.next self.head.next = node self.size += 1 def pop(self): if self.is_empty(): raise Exception("Popping from an empty stack") remove = self.head.next self.head.next = self.head.next.next self.size -= 1 return remove.value
print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 014 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') c = float(input('Informe a temperatura em °C: ')) f = c * 9 / 5 + 32 print(f'A temperatura de {c}°C corresponde a {f:.1f}°F') print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
#!/usr/bin/python # related: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python class Worker(): SUCCESS = 1 FAILURE = 2 def test(self): return Worker.FAILURE t = Worker() t.test() if (t.test() == Worker.FAILURE): print("I got a failure status") if (t.test() == Worker.SUCCESS): print("I got a success status")
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result def rescale_bbox(height, width, bbox): """ In case of metric coordinates: Increase either longitude or either latitude (on both min and max values) to obtain the same scale dimension (longitude/latitude) of the image scale dimensions (height/width) :param height: height of the image :param width: width of the image :param bbox: bbox of the map :return: """ x1, y1, x2, y2 = bbox scale_image = float(height) / float(width) scale_bbox = float(y2 - y1) / float(x2 - x1) if scale_image < scale_bbox: x = (((y2 - y1) / scale_image) - x2 + x1) / 2 return [x1 - x, y1, x2 + x, y2] elif scale_image > scale_bbox: y = ((scale_image * (x2 - x1)) - y2 + y1) / 2 return [x1, y1 - y, x2, y2 + y] else: return bbox def calculate_scale(map_scale, map_width): """ Calculates the image scale with in pixels together with the scale label using map scale (meters per pixels) and map width (pixels) """ image_width_meter = round(map_scale * float(map_width)) scale_num_guess = str(int(round(image_width_meter * 0.2))) scale_num = int(2 * round(float(int(scale_num_guess[0])) / 2)) * 10 ** ( len(scale_num_guess[1:])) scale_num = scale_num if scale_num else 1 * 10 ** (len(scale_num_guess[1:])) scale_width = round(scale_num / map_scale) scale_label = f"{scale_num} m" if scale_num < 1000 else "{} km".format( scale_num / 1000) return scale_width, scale_label
# Copyright Notice: # Copyright 2016-2019 DMTF. All rights reserved. # License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Interface-Emulator/blob/master/LICENSE.md # Redfish Emulator Role Service. # Temporary version, to be removed when AccountService goes dynamic class AccountService(object): def __init__(self): self._accounts = { 'Administrator': 'Password', 'User': 'Password' } self._roles = { 'Administrator': 'Admin', 'User': 'ReadOnlyUser' } def checkPriviledgeLevel(self, user, level): if self._roles[user] == level: return True else: return False def getPassword(self, username): if username in self._accounts: return self._accounts[username] else: return None def checkPrivilege(self, privilege, username, errorResponse): def wrap(func): def inner(*args, **kwargs): if self.checkPriviledgeLevel(username(), privilege): return func(*args, **kwargs) else: return errorResponse() return inner return wrap
# the highest score student_scores = input("Input a list of student scores ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) # or you can use the max() function # max = max(student_scores) highest = student_scores[0] for index in range(0, len(student_scores)): if student_scores[index] > highest: highest = student_scores[index] print("The highest score in the class is: ", highest) """ highest_score = 0 for score in student_scores: if score > highest_score: highest_score = score print("The highest score in the class is: {highest_score}") """
"""Constants used by the OpenMediaVault integration.""" DOMAIN = "openmediavault" DEFAULT_NAME = "OpenMediaVault" DATA_CLIENT = "client" ATTRIBUTION = "Data provided by OpenMediaVault integration" DEFAULT_HOST = "10.0.0.1" DEFAULT_USERNAME = "admin" DEFAULT_PASSWORD = "openmediavault" DEFAULT_DEVICE_NAME = "OMV" DEFAULT_SSL = False DEFAULT_SSL_VERIFY = True ATTR_ICON = "icon" ATTR_LABEL = "label" ATTR_UNIT = "unit" ATTR_UNIT_ATTR = "unit_attr" ATTR_GROUP = "group" ATTR_PATH = "data_path" ATTR_ATTR = "data_attr" BINARY_SENSOR_TYPES = { "system_pkgUpdatesAvailable": { ATTR_LABEL: "Update available", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "pkgUpdatesAvailable", }, "system_rebootRequired": { ATTR_LABEL: "Reboot pending", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "rebootRequired", }, "system_configDirty": { ATTR_LABEL: "Config dirty", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "configDirty", }, } SENSOR_TYPES = { "system_cpuUsage": { ATTR_ICON: "mdi:speedometer", ATTR_LABEL: "CPU load", ATTR_UNIT: "%", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "cpuUsage", }, "system_memUsage": { ATTR_ICON: "mdi:memory", ATTR_LABEL: "Memory", ATTR_UNIT: "%", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "memUsage", }, "system_uptimeEpoch": { ATTR_ICON: "mdi:clock-outline", ATTR_LABEL: "Uptime", ATTR_UNIT: "hours", ATTR_GROUP: "System", ATTR_PATH: "hwinfo", ATTR_ATTR: "uptimeEpoch", }, } DEVICE_ATTRIBUTES_FS = [ "size", "available", "type", "mountpoint", "_readonly", "_used", ] DEVICE_ATTRIBUTES_DISK = [ "canonicaldevicefile", "size", "israid", "isroot", "devicemodel", "serialnumber", "firmwareversion", "sectorsize", "rotationrate", "writecacheis", "smartsupportis", "Raw_Read_Error_Rate", "Spin_Up_Time", "Start_Stop_Count", "Reallocated_Sector_Ct", "Seek_Error_Rate", "Load_Cycle_Count", "UDMA_CRC_Error_Count", "Multi_Zone_Error_Rate", ]
# -*- coding: utf-8 -*- # These are found in Repack-MPQ/fileset.{locale}#Mods#Core.SC2Mod#{locale}.SC2Data/LocalizedData/Editor/EditorCategoryStrings.txt # EDSTR_CATEGORY_Race # EDSTR_PLAYERPROPS_RACE # The ??? means that I don't know what language it is. # If multiple languages use the same set they should be comma separated LOCALIZED_RACES = { # enUS 'Terran': 'Terran', 'Protoss': 'Protoss', 'Zerg': 'Zerg', # ruRU 'Терран': 'Terran', 'Протосс': 'Protoss', 'Зерг': 'Zerg', # koKR '테란': 'Terran', '프로토스': 'Protoss', '저그': 'Zerg', # ??? 'Terrani': 'Terran', 'Protosi': 'Protoss', 'Zergi': 'Zerg', # zhCH '人类': 'Terran', '星灵': 'Protoss', '异虫': 'Zerg', # zhTW '人類': 'Terran', '神族': 'Protoss', '蟲族': 'Zerg', # ??? 'Terrano': 'Terran', # deDE 'Terraner': 'Terran', # esES - Spanish # esMX - Latin American # frFR - French - France # plPL - Polish Polish # ptBR - Brazilian Portuguese } # # Codes as found in bytestream # RACE_CODES = { 'rreT': 'Terran', 'greZ': 'Zerg', 'torP': 'Protoss', 'DNAR': 'Random', } MESSAGE_CODES = { '0': 'All', '2': 'Allies', '128': 'Header', '125': 'Ping', } TEAM_COLOR_CODES = { '10ct': "Red", '20ct': "Blue", '30ct': "Teal", '40ct': "Purple", '50ct': "Yellow", '60ct': "Orange", '70ct': "Green", '80ct': "Pink", '90ct': "??", '01ct': "??", '11ct': "??", '21ct': "??", '31ct': "??", '41ct': "??", '51ct': "??", '61ct': "??", } DIFFICULTY_CODES = { 'yEyV': 'Very easy', 'ysaE': 'Easy', 'ideM': 'Medium', 'draH': 'Hard', 'dHyV': 'Very hard', 'asnI': 'Insane', } GAME_TYPE_CODES = { 'virP': 'Private', 'buP': 'Public', 'mmA': 'Ladder', '': 'Single', } # (name, key for team ids) GAME_FORMAT_CODES = { '1v1': '1v1', '2v2': '2v2', '3v3': '3v3', '4v4': '4v4', '5v5': '5v5', '6v6': '6v6', 'AFF': 'FFA', } GAME_SPEED_CODES = { 'rolS': 'Slower', 'wolS': 'Slow', 'mroN': 'Normal', 'tsaF': 'Fast', 'rsaF': 'Faster', } PLAYER_TYPE_CODES = { 'nmuH': 'Human', 'pmoC': 'Computer', 'nepO': 'Open', 'dslC': 'Closed', } GATEWAY_CODES = { 'US': 'Americas', 'KR': 'Asia', 'EU': 'Europe', 'SG': 'South East Asia', 'XX': 'Public Test', } COLOR_CODES = { 'B4141E': 'Red', '0042FF': 'Blue', '1CA7EA': 'Teal', 'EBE129': 'Yellow', '540081': 'Purple', 'FE8A0E': 'Orange', '168000': 'Green', 'CCA6FC': 'Light pink', '1F01C9': 'Violet', '525494': 'Light grey', '106246': 'Dark green', '4E2A04': 'Brown', '96FF91': 'Light green', '232323': 'Dark grey', 'E55BB0': 'Pink' } # TODO: Not sure if this is a complete mapping # # Assuming only 1 Public Test Realm subregion on the following basis: # # Q: Is there only one PTR server or there will be one for each region? # A: There's only one PTR server and it's located in North American. # There are no current plans to have multiple PTR servers. # Source: http://us.blizzard.com/support/article.xml?locale=en_US&articleId=36109 REGIONS = { # United States 'us': { 1: 'us', 2: 'la', }, # Europe 'eu': { 1: 'eu', 2: 'ru', }, # Korea 'kr': { 1: 'kr', 2: 'tw', }, # South East Asia 'sea': { 1: 'sea', }, # Public Test 'xx': { 1: 'xx', }, }
class Solution(object): def singleNumber(self, nums): diff = reduce(lambda x, y: x ^ y, nums, 0) diff &= -diff res = [0, 0] for num in nums: res[num & diff == 0] ^= num return res
# Clase libro | libro() significa heredar de otra clase --> libro(biblioteca) | hijo(padre). class libro: # Contructor de libro, con las variables introducidas | __XX = privado def __init__(self, isbn = "", titulo = "", autor = "", genero = "", portada = "", sinopsis = "", ejemplares = 0): self.__isbn=isbn self.__titulo=titulo self.__autor=autor self.__genero=genero self.__portada=portada self.__sinopsis=sinopsis self.__ejemplares=ejemplares # Generación de property y setter de las distintas variables. @property def isbn(self): return self.__isbn @isbn.setter def isbn(self,a): self.__isbn=a @property def titulo(self): return self.__titulo @titulo.setter def titulo(self,a): self.__titulo=a @property def autor(self): return self.__autor @autor.setter def autor(self,a): self.__autor=a @property def genero(self): return self.__genero @genero.setter def genero(self,a): self.__genero=a @property def portada(self): return self.__portada @portada.setter def portada(self,a): self.__portada=a @property def sinopsis(self): return self.__sinopsis @sinopsis.setter def sinopsis(self,a): self.__sinopsis=a @property def ejemplares(self): return self.__ejemplares @ejemplares.setter def ejemplares(self,a): self.__ejemplares=a
def powerset_of_set(aset): set_list = [x for x in aset] final_set = set() for catchnum in range(len(set_list)): print(catchnum) for index in range(catchnum, len(set_list)): b = "{}".format(set_list[index:]) if b not in final_set: final_set.add(b) return final_set def powerset_of_set(aset): set_list = [x for x in aset] for item in set_list: dfs aset = set(['x', 'y', 'z']) print(powerset_of_set(aset))
# Fungsi enkripsi def encrypt(plain,password): plainIntVector = [] for i in range(len(plain)): plainIntVector.append(ord(plain[i])) passwordIntVector = [] # inisiasi variabel baru untuk membuat setiap perubahan yang terjadi pada # password akan menyebabkan avalanche effect # variabel ini berisi jumlahan dari nilai ascii password dipangkatkan # panjang password mod 256, agar tidak melebihi jumlah ascii added_value = pow(sum([ord(i) for i in password]), len(password), 256) for i in range(len(password)): passwordIntVector.append((ord(password[i]) + added_value) % 256) # fungsi lainnya tidak berubah plainIndex = 0 cipherIntVector = [] while plainIndex < len(plain): for i in range(len(password)): if plainIndex == len(plain): break oneCharCipher = plainIntVector[plainIndex]^passwordIntVector[i] cipherIntVector.append(oneCharCipher) plainIndex += 1 return cipherIntVector def decrypt(cipherIntVector,password): passwordIntVector = [] # fungsi yang sama seperti fungsi cipher juga dimasukkan di sini # agar decipher menghasilkan karakter yang sama added_value = pow(sum([ord(i) for i in password]), len(password), 256) for i in range(len(password)): passwordIntVector.append((ord(password[i]) + added_value) % 256) cipherIndex = 0 plainIntVector = [] while cipherIndex < len(cipherIntVector): for i in range (len(password)): if cipherIndex == len(cipherIntVector): break oneCharPlain = cipherIntVector[cipherIndex]^passwordIntVector[i] plainIntVector.append(oneCharPlain) cipherIndex += 1 plain = '' for i in range(len(plainIntVector)): plain = plain + chr(plainIntVector[i]) return plain plain = input("Plain text: ") password = input("Password: ") cipher = encrypt(plain, password) print ("Cipher: ", end='') print(cipher) print("Cipher in hex:", end=" ") for i in cipher: print(f"{i:02X}", end=" ") print() print("Plain: " + decrypt(cipher,password))
class solve_day(object): with open('inputs/day08.txt', 'r') as f: data = f.readlines() data = [d.strip() for d in data] def part1(self): accumulator = 0 i = 0 index_tracker = [] index_visited = set() index_tracker.append(i) index_visited.add(i) while len(index_tracker) == len(index_visited): d = self.data[i] #parse d: instruction = d.split(' ')[0] direction = d.split(' ')[1][:1] amount = int(d.split(' ')[1][1:]) if instruction == 'nop': i += 1 if instruction == 'acc': accumulator += amount if direction == '+' else -amount i += 1 if instruction == 'jmp': i += amount if direction == '+' else -amount index_tracker.append(i) index_visited.add(i) return accumulator def part2(self): j = 0 # write an outer loop to go in and edit the instructions for k in range(len(self.data)): new_d = [] for l,d in enumerate(self.data): #parse d: instruction = d.split(' ')[0] direction = d.split(' ')[1][:1] amount = int(d.split(' ')[1][1:]) if j == l: if instruction == 'nop': instruction = 'jmp' elif instruction == 'jmp': instruction = 'nop' new_d.append(f'{instruction} {direction}{amount}') accumulator = 0 i = 0 index_tracker = [] index_visited = set() index_tracker.append(i) index_visited.add(i) while len(index_tracker) == len(index_visited): try: d = new_d[i] except: return accumulator #parse d: instruction = d.split(' ')[0] direction = d.split(' ')[1][:1] amount = int(d.split(' ')[1][1:]) if instruction == 'nop': i += 1 if instruction == 'acc': accumulator += amount if direction == '+' else -amount i += 1 if instruction == 'jmp': i += amount if direction == '+' else -amount index_tracker.append(i) index_visited.add(i) j += 1 if __name__ == '__main__': s = solve_day() print(f'Part 1: {s.part1()}') print(f'Part 2: {s.part2()}')
class Marker(object): def __init__(self): self._body = None def make(self): raise NotImplementedError def update(self, marker): pass def show(self): if self._body is None: self._body = self.make() self.update(self._body) def hide(self): if self._body is not None: self._body.remove() self._body = None
""" Дан список my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], выведите все элементы, которые меньше 5. """ my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for i in my_list: if i < 5: print(i)
# Bubble Sort-values of a dictionary as a list #Time Complexity = O(N) def bubbleSort(k): for i in range(1,len(k)): for j in range(len(k)-i): if k[j] > k[j+1]: k[j],k[j+1] = k[j+1],k[j] return k dict = {"a":1, "c":3, "f":6, "e":5, "d":4, "b":2} k = list(dict.values()) print(bubbleSort(k))
class Dog: def eat(self, food): print(self.color, '的', self.kinds, '正在吃', food) dog1 = Dog() dog1.kinds = '京巴' dog1.color = '白色' dog1.color = '黄色' # this line will overwrite the color-attribute of dog1 dog1.eat('骨头') dog2 = Dog() dog2.kinds = '牧羊犬' dog2.color = '灰色' dog2.eat('屎')
saisie_debut = input("le debut :") debut = int(saisie_debut) #si l'utilisateur saisit un chiffre impair if debut % 2 != 0 : debut += 1 saisie_fin = input("la fin :") fin = int(saisie_fin) indice = 1 for elem in range(debut, fin, 2): print("element ", indice," = ", elem) indice += 1
var = """A multi-line docstring""" var = """A multi-line docstring """
# -*- coding: utf-8 -*- """Top-level package for Python Missing Data Strategies.""" __author__ = """Aris Tritas""" __email__ = "a.tritas@gmail.com" __version__ = "0.0.1" imputation_strategies = ("mean", "median", "most_frequent", "infer", "fill")
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2020 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Terceira Edição - Janeiro/2019 - ISBN 978-85-7522-718-3 # # Site: https://python.nilo.pro.br/ # # Arquivo: exercicios3\capitulo 05\exercicio-05-14.py ############################################################################## soma = 0 quantidade = 0 while True: n = int(input("Digite um número inteiro: ")) if n == 0: break soma = soma + n quantidade = quantidade + 1 print("Quantidade de números digitados:", quantidade) print("Soma: ", soma) print(f"Média: {soma/quantidade:10.2f}")
# -*- coding: utf-8 -*- """ Created on Sat Mar 7 10:17:36 2020 @author: teja """ s = '12asdbkFWS(#@!qde' cn = 0 ca = 0 cspl = 0 for i in range(len(s)): if s[i].isalpha(): ca+=1 elif s[i].isnumeric(): cn+=1 else: cspl+=1 print(str(cn) + " " + str(ca) + " " + str(cspl) + " ")
#faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis sobre ela b = input("digite algo ") print(" o tipo primitivo desse valor é: ", type(b)) print("so tem espaços?", b.isspace()) print(" é um número ? ",b.isnumeric()) print(" é um alfabeto ?", b.isalpha()) print(" é um alfanúmerico ? ", b.isalnum()) print("é letra maiuscula ?", b.isupper()) print(" é letra minuscula ?", b.islower()) print(" está capitalizada ?", b.istitle()) print("está informação digitada é o tipo primitivo desse valor é:{},espaços: {}, é um número: {}, é um alfabeto: {},é um alfanúmerico {}, é letra maiuscula {},é letra minuscula {} e está capitalizada {}".format(type(b),b.isspace(),b.isnumeric(),b.isalpha(),b.isalnum(),b.isupper(),b.islower(),b.istitle()))
SMTP_SERVICE_BLOCK = 'smtp-service' SMTP_HOST = 'smtp_host' SMTP_PORT = 'smtp_port' SMTP_USERNAME = 'smtp_username' SMTP_PASSWORD = 'smtp_password' SMTP_USE_TLS = 'smtp_use_tls' SMTP_LEVEL = 'smtp_level' SMTP_DEFAULT_VALUES = { SMTP_HOST: '127.0.0.1', SMTP_PORT: '25', SMTP_USERNAME: None, SMTP_PASSWORD: None, SMTP_USE_TLS: True, SMTP_LEVEL: 0, } SMTP_CONFIG = [ SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_USE_TLS, SMTP_LEVEL, ] FILENAME = 'filename' BUFFERED_CONTENT = 'buffered_content'
"""Constants for pyskyqremote.""" # SOAP/UPnP Constants SKY_PLAY_URN = "urn:nds-com:serviceId:SkyPlay" SKYCONTROL = "SkyControl" SOAP_ACTION = '"urn:schemas-nds-com:service:SkyPlay:2#{0}"' SOAP_CONTROL_BASE_URL = "http://{0}:49153{1}" SOAP_DESCRIPTION_BASE_URL = "http://{0}:49153/description{1}.xml" SOAP_PAYLOAD = """<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/' s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'> # pylint: disable=line-too-long <s:Body> <u:{0} xmlns:u="urn:schemas-nds-com:service:SkyPlay:2"> <InstanceID>0</InstanceID> </u:{0}> </s:Body> </s:Envelope>""" SOAP_RESPONSE = "u:{0}Response" SOAP_USER_AGENT = "SKYPLUS_skyplus" UPNP_GET_MEDIA_INFO = "GetMediaInfo" UPNP_GET_TRANSPORT_INFO = "GetTransportInfo" # WebSocket Constants WS_BASE_URL = "ws://{0}:9006/as/{1}" WS_CURRENT_APPS = "apps/status" # REST Constants REST_BASE_URL = "http://{0}:{1}/as/{2}" REST_CHANNEL_LIST = "services/{0}/{1}" REST_FAVOURITES = "services/favourites" REST_RECORDING_DETAILS = "pvr/details/{0}" REST_RECORDINGS_LIST = "pvr/?limit={0}&offset={1}" REST_QUOTA_DETAILS = "pvr/storage" REST_BOOK_RECORDING = "pvr/action/bookrecording?eid={0}" REST_BOOK_PPVRECORDING = "pvr/action/bookppvrecording?eid={0}&offerref={1}" REST_BOOK_SERIES_RECORDING = "pvr/action/bookseriesrecording?eid={0}" REST_SERIES_LINK = "pvr/action/serieslink?pvrid={0}" REST_SERIES_UNLINK = "pvr/action/seriesunlink?pvrid={0}" REST_RECORDING_KEEP = "pvr/action/keep?pvrid={0}" REST_RECORDING_UNKEEP = "pvr/action/unkeep?pvrid={0}" REST_RECORDING_LOCK = "pvr/action/lock?pvrid={0}" REST_RECORDING_UNLOCK = "pvr/action/unlock?pvrid={0}" REST_RECORDING_DELETE = "pvr/action/delete?pvrid={0}" REST_RECORDING_UNDELETE = "pvr/action/undelete?pvrid={0}" REST_RECORDING_ERASE = "pvr/action/erase?pvrid={0}" REST_RECORDING_ERASE_ALL = "pvr" REST_RECORDING_SET_LAST_PLAYED_POSITION = ( "pvr/action/setlastplayedposition?pos={0}&pvrid={1}" ) REST_PATH_SYSTEMINFO = "system/information" REST_PATH_DEVICEINFO = "system/deviceinformation" REST_PATH_APPS = "apps" REST_GET = "get" REST_POST = "post" REST_DELETE = "delete" # Sky specific constants CURRENT_URI = "CurrentURI" CURRENT_TRANSPORT_STATE = "CurrentTransportState" CURRENT_TRANSPORT_STATUS = "CurrentTransportStatus" CURRENT_SPEED = "CurrentSpeed" DEFAULT_TRANSPORT_STATE = "OK" DEFAULT_TRANSPORT_SPEED = 1 APP_STATUS_VISIBLE = "VISIBLE" PVR = "pvr" XSI = "xsi" SKY_STATE_NOMEDIA = "NO_MEDIA_PRESENT" SKY_STATE_OFF = "POWERED OFF" SKY_STATE_ON = "ON" SKY_STATE_PLAYING = "PLAYING" SKY_STATE_PAUSED = "PAUSED_PLAYBACK" SKY_STATE_STANDBY = "STANDBY" SKY_STATE_STOPPED = "STOPPED" SKY_STATE_TRANSITIONING = "TRANSITIONING" SKY_STATE_UNSUPPORTED = "UNSUPPORTED" SKY_STATUS_LIVE = "LIVE" APP_EPG = "com.bskyb.epgui" COMMANDS = { "power": 0, "select": 1, "backup": 2, "dismiss": 2, "channelup": 6, "channeldown": 7, "interactive": 8, "sidebar": 8, "help": 9, "services": 10, "search": 10, "tvguide": 11, "home": 11, "i": 14, "text": 15, "up": 16, "down": 17, "left": 18, "right": 19, "red": 32, "green": 33, "yellow": 34, "blue": 35, "0": 48, "1": 49, "2": 50, "3": 51, "4": 52, "5": 53, "6": 54, "7": 55, "8": 56, "9": 57, "play": 64, "pause": 65, "stop": 66, "record": 67, "fastforward": 69, "rewind": 71, "boxoffice": 240, "sky": 241, } KNOWN_COUNTRIES = { "DEU": "DEU", "GBR": "GBR", "IRL": "GBR", "ITA": "ITA", } # Random set of other constants EPG_ERROR_PAST_END = "past end of epg" EPG_ERROR_NO_DATA = "no epg data found" RESPONSE_OK = 200 CONNECT_TIMEOUT = 1000 HTTP_TIMEOUT = 6 SOAP_TIMEOUT = 2 AUDIO = "audio" VIDEO = "video" ALLRECORDINGS = "all" REST_GET = "get" REST_POST = "post" REST_DELETE = "DELETE" DEVICE_GATEWAYSTB = "GATEWAYSTB" DEVICE_IPSETTOPBOX = "IPSETTOPBOX" DEVICE_MULTIROOMSTB = "MULTIROOMSTB" DEVICE_TV = "TV" UNSUPPORTED_DEVICES = [DEVICE_IPSETTOPBOX, DEVICE_TV]
# 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。 # #   # # 示例: # # 给定一个链表: 1->2->3->4->5, 和 k = 2. # # 返回链表 4->5. # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: stack = [] cur = head while cur: stack.append(cur) cur = cur.next ans = None for i in range(k): ans = stack.pop(-1) return ans
""" Создайте лямбда-функцию по следующему описанию: Введите строку с клавиатуры. Удалите из нее все буквы алфавита, идущие после буквы "и". Подсказка: воспользуйтесь генератором. Вы можете сравнивать буквы как числа. Чем дальше буква в алфавите, тем она "больше". """ my_string = input("Введите строку: ") new_string = lambda string: [letter for letter in string if letter < "и"] print("".join(new_string(my_string)))
''' Little Jhool and psychic powers Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psychic abilities! He knew everyone was making fun of him, so to stop all of that - he came up with a smart plan. Anyone who came to him to know about their future, he asked them to write a binary number for him - and then, he smartly told them if the future for that person had good in store, or bad. The algorithm which Little Jhool follows is, as following: If the binary number written by the person has six consecutive , or , his future is bad. Otherwise, he says that their future is good. Input format: Single line contains a binary number. Output format: You need to print "Good luck!" (Without quotes, and WITH exclamation mark!) if the Jhool is going to tell them that they're going to have a good time. Else, print "Sorry, sorry!" if the person is going to be told that he'll have a hard time! Constraints: The binary number will be in string format, with the maximum length being characters. SAMPLE INPUT 0001111110 SAMPLE OUTPUT Sorry, sorry! Explanation Since the binary number given has six consecutive 1s, little Jhool tells the man that he's going to have a bad time! ''' num = input() for i in range(len(num)): if num[i:i+6] == '000000' or num[i:i+6] == '111111': print('Sorry, sorry!') break elif int(i)==len(num)-1: print('Good luck!')
""" if elif else """ NUMBER = 17 value = int(input("input a value: ")) if value == NUMBER: print("Winner!!!") elif value > NUMBER: print("your number is greater") else: print("your number is lower")
class ValidatedDictLike: """ This a dict with a `validate` method that may raise any exception. The dict it validation on initialization and any time its contents are changed. If a change is illegal, it is reverted an the exception from `validate` is raised. Thus, it is impossible to put the dict into an invalid state. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: self.validate() except ValidationError: raise ValidationError("Validation failed. Unable to create ValidatedDictLike.") def clear(self): original = dict(self) super().clear() try: self.validate() except ValidationError: super().update(original) raise ValidationError("Validation failed. Unable to clear.") def pop(self, key): val = super().pop(key) try: self.validate() except ValidationError: super().__setitem__(key, val) raise ValidationError("Validation failed. Unable to pop {}".format(key)) def popitem(self): key, val = super().popitem() try: self.validate() except ValidationError: super().__setitem__(key, val) raise ValidationError("Validation failed. Unable to popitem {}".format(key)) def setdefault(self, *args, **kwargs): original = dict(self) super().setdefault(*args, **kwargs) try: self.validate() except ValidationError: super().update(original) raise ValidationError("Validation failed. Unable to setdefault.") def update(self, *args, **kwargs): original = dict(self) super().update(*args, **kwargs) try: self.validate() except ValidationError: super().clear() super().update(original) raise ValidationError("Validation failed. Unable to update.") def __setitem__(self, key, val): super().__setitem__(key, val) try: self.validate() except ValidationError: super().__delitem__(key) raise ValueError("Validation failed. Unable to set {}: {}".format(key, val)) def __delitem__(self, key): val = self[key] super().__delitem__(key) try: self.validate() except ValidationError: super().__setitem__(key, val) raise ValueError("Validation failed. Unable to delete {}".format(key)) def validate(self): pass class ValidationError(Exception): pass
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Defines constants for use in the performance testing framework.""" class DataTypes: """Data types""" TABULAR = 'tabular' IMAGE = 'image' TEXT = 'text' class Algorithms: """Algorithms""" SVM = 'svm' LOGISTIC = 'logistic' DEEP = 'deep' TREE = 'tree' RIDGE = 'ridge' class Tasks: """Machine learning tasks""" BINARY = 'binary' MULTICLASS = 'multiclass' REGRESSION = 'regression' class FeatureType: """Feature types""" CONTINUOUS = 'c' NOMINAL = 'n' class Metrics: """Metrics""" PEAK_MEMORY = 'peak memory' MEMORY_USAGE = 'memory usage' EXECUTION_TIME = 'execution time' FEATURES = 'features' ROWS = 'rows' SHAP_NDCG = 'shap ndcg' TRUE_NDCG = 'true ndcg' DATASET = 'dataset' EXPLAINER = 'explainer' MODEL = 'model' AGREEMENT = 'agreement explainer' CELLS = 'cells' class Timing: """Timing constants.""" TIMEOUT = 256 class ModelParams: """Parameters used in the model""" RANDOM_STATE = 'random_state' class ClassVars: """Dynamically-set class variables.""" LOAD_FUNCTION = 'load_function' TASK = 'task' FEATURE_TYPE = '_feature_type' DATA_TYPE = 'data_type' SIZE = '_size' TARGET_COL = '_target_col' EXPLAINER_FUNC = 'explainer_func' LIMIT = 'limit' DATA_TYPES = 'data_types' ALGORITHMS = 'algorithms' TASKS = 'tasks' EXPLAIN_PARAMS = 'explain_params' class SKLearnDatasets: BOSTON = 'boston' IRIS = 'iris' DIABETES = 'diabetes' DIGITS = 'digits' WINE = 'wine' CANCER = 'cancer' class UCIDatasets: CAR = 'car-eval' BANK = 'bank' BANK_ADD = 'bank-additional' ADULT = 'adult' class BlobDatasets: MSX_SMALL = 'msx_small' MSX_BIG = 'msx_big' class CompasDatasets: COMPAS = "compas" class SEAPHEDatasets: LAWSCHOOL_PASSBAR = "lawschool_passbar" LAWSCHOOL_GPA = "lawschool_gpa" class DatasetSizes: MEDIUM = 750000 BIG = 1500000 GIANT = 5000000 class LightGBMParams: BOOSTING_TYPE = 'boosting_type' BAGGING_FRACTION = 'bagging_fraction' DEFAULT_BAGGING_FRACTION = 0.33 BAGGING_FREQ = 'bagging_freq' DEFAULT_BAGGING_FREQ = 5 RF = 'rf' DART = 'dart' GOSS = 'goss' class DatasetConstants(object): """Dataset related constants.""" CATEGORICAL = 'categorical' CLASSES = 'classes' FEATURES = 'features' NUMERIC = 'numeric' X_TEST = 'x_test' X_TRAIN = 'x_train' Y_TEST = 'y_test' Y_TRAIN = 'y_train'
def test_logout(ui): driver = ui.driver driver.find_element_by_css_selector(".user-dropdown").click() driver.find_element_by_css_selector(".logout-button").click() assert driver.find_element_by_css_selector('.login-form') def test_recorded_sessions_visible(ui_session): assert ui_session is not None
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # https://leetcode-cn.com/problems/longest-common-prefix/description/ # # algorithms # Easy (32.10%) # Total Accepted: 59.9K # Total Submissions: 185.1K # Testcase Example: '["flower","flow","flight"]' # # 编写一个函数来查找字符串数组中的最长公共前缀。 # # 如果不存在公共前缀,返回空字符串 ""。 # # 示例 1: # # 输入: ["flower","flow","flight"] # 输出: "fl" # # # 示例 2: # # 输入: ["dog","racecar","car"] # 输出: "" # 解释: 输入不存在公共前缀。 # # # 说明: # # 所有输入只包含小写字母 a-z 。 # # class Solution: def longestCommonPrefix(self, strs: list) -> str: if not strs: return '' strs.sort(key=len) # print(strs) l = len(strs[0]) # status = False # while l > 0 and not status: while l > 0: start = strs[0][:l] # print(start) count = 1 for string in strs[1:]: if start != string[:l]: l -= 1 break count += 1 if count == len(strs): # status = False return start return '' if __name__ == '__main__': S = Solution() res = S.longestCommonPrefix(["dog","racecar","car"]) print(res)
#!/usr/bin/env python #coding: utf-8 class CMake(object): def __init__(self, cmake_version='3.15', project_name='project', tab=' '): self.txt = [] self.txt.append('CMAKE_MINIMUM_REQUIRED(VERSION {:s})'.format(cmake_version)) self.txt.append('') self.txt.append('project({:s})'.format(project_name)) self.txt.append('') self.tab = tab def add_executable(self, target_name, src=[]): self.txt.append('add_executable({:s}'.format(target_name)) for item in src: self.txt.append(self.tab + item) self.txt.append(')') self.txt.append('') def add_library(self, target_name, src=[], lib_type='STATIC'): self.txt.append('add_library({:s} {:s}'.format(target_name, lib_type)) for item in src: self.txt.append(self.tab + item) self.txt.append(')') self.txt.append('') def target_link_libraries(self, target_name, dep_lst=[]): self.txt.append('target_link_libraries({:s}'.format(target_name)) for item in dep_lst: self.txt.append(self.tab + item) self.txt.append(')') self.txt.append('') def dump(self): for item in self.txt: print(item) def add_target(self, target): target_dump = target.dump() for item in target_dump: self.txt.append(item) class find_package(object): def __init__(self, name): # TODO: 这里需要修正,不能仅仅是产生字符串 # 而是应当执行真的查找 """ https://stackoverflow.com/questions/28863366/command-line-equivalent-of-cmakes-find-package 检查是否存在: cmake --find-package -DNAME=OpenCV -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST 编译(头文件): cmake --find-package -DNAME=OpenCV -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=COMPILE 链接(库文件): cmake --find-package -DNAME=OpenCV -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=LINK 但是看到官方文档有一个备注,说--find_package命令,不建议用: This mode is not well-supported due to some technical limitations. It is kept for compatibility but should not be used in new projects. """ class Target(object): def __init__(self): pass class Library(object): def __init__(self, target_name, lib_type='STATIC'): self.name = target_name self.file_lst = [] self.inc_dir_lst = [] self.lib_type = lib_type self.dep_lib_lst = [] self.tab = ' ' def add_dep_file(self, f): self.file_lst.append(f) def add_dep_files(self, f_lst): self.file_lst += f_lst def add_include_dir(self, inc_dir, priv): if priv not in ['PUBLIC', 'PRIVATE', 'INTERFACE']: print('Error! priv invalid') inc_dir = '{:s} {:s}'.format(priv, inc_dir) self.inc_dir_lst.append(inc_dir) def add_dep_lib(self, dep_lib, priv=''): if priv not in ['', 'PUBLIC', 'PRIVATE', 'INTERFACE']: print('Error! priv invalid') if (isinstance(dep_lib, str)): dep_lib = '{:s} {:s}'.format(priv, dep_lib) self.dep_lib_lst.append(dep_lib) elif (isinstance(dep_lib, CMake.Target.Library)): dep_lib = dep_lib.name dep_lib = '{:s} {:s}'.format(priv, dep_lib) self.dep_lib_lst.append(dep_lib) else: print('Error! dep_lib invalid') def dump(self): txt = [] # target define txt.append('') txt.append('add_library({:s} {:s}'.format(self.name, self.lib_type)) for item in self.file_lst: txt.append(self.tab + item) txt.append(')') txt.append('') # target include directories if len(self.inc_dir_lst)>0: txt.append('target_include_directories({:s}'.format(self.name)) for item in self.inc_dir_lst: txt.append(self.tab + item) txt.append(')') # target link libraries if len(self.dep_lib_lst)>0: txt.append('target_link_libraries({:s}'.format(self.name)) for item in self.dep_lib_lst: txt.append(self.tab + item) txt.append(')') return txt class Executable(object): def __init__(self, target_name): self.name = target_name self.file_lst = [] self.inc_dir_lst = [] self.dep_lib_lst = [] self.tab = ' ' def add_dep_file(self, f): self.file_lst.append(f) def add_dep_files(self, f_lst): self.file_lst += f_lst def add_include_dir(self, inc_dir, priv): if priv not in ['PUBLIC', 'PRIVATE', 'INTERFACE']: print('Error! priv invalid') inc_dir = '{:s} {:s}'.format(priv, inc_dir) self.inc_dir_lst.append(inc_dir) def add_dep_lib(self, dep_lib, priv=''): if priv not in ['', 'PUBLIC', 'PRIVATE', 'INTERFACE']: print('Error! priv invalid') dep_lib = '{:s} {:s}'.format(priv, dep_lib) self.dep_lib_lst.append(dep_lib) def dump(self): txt = [] # target define txt.append('add_executable({:s}'.format(self.name)) for item in self.file_lst: txt.append(self.tab + item) txt.append(')') txt.append('') # target include directories if len(self.inc_dir_lst)>0: txt.append('target_include_directories({:s}'.format(self.name)) for item in self.inc_dir_lst: txt.append(self.tab + item) txt.append(')') # target link libraries if len(self.dep_lib_lst)>0: txt.append('target_link_libraries({:s}'.format(self.name)) for item in self.dep_lib_lst: txt.append(self.tab + item) txt.append(')') return txt
# -*- encoding: utf-8 -*- """ constant 储存各种常量,保证常量的统一性 """ DEFAULT_SPEED = 120 # 默认速度 DEFAULT_TONE = "Sine" # 默认音色 DEFAULT_VOLUME = 0.02 # 默认音量 MAX_VOLUME = 1.0 # 最大音量 MIN_VOLUME = 0.0 # 最小音量 NO_LENGTH = -1 # 用来表示当前音乐没有长度的标记 def getBeatLengthBySpeed(speed): # 根据当前的速度,计算每一拍的长度 return 60 / speed
user_input = 999 while user_input != "0": user_input = input("십진수 숫자를 입력해주세요 : ") try: decimal_number = int(user_input) print(bin(decimal_number)) except ValueError as e: print(e) print("Error - 10진수 숫자만 입력해주시기 바랍니다.")
d = {} x = input('Please enter your name: ') # נשמור במשתנה name את הערך מהמשתמש d['Name'] = x # {'Name' : 'David'} d['Name'] = x + x # {'Name' : 'DavidDavid'} עידכנו את הערך השייך למפתח print(d.get('Name'))
""" https://github.com/parzival-roethlein/prmaya # DESCRIPTION Manage objectSet members (add, remove, reorder, export, import) # USAGE import prmaya.scripts.prObjectSetUi.utils prmaya.scripts.prObjectSetUi.utils.ui() # TODO - export / import members - avoid unwanted maya behavior (clean solutions only possible with custom node?) -- add duplicated members to set (custom sync attribute?, scriptjob?) -- delete set when last member gets deleted (lock set current workaround) """
texts = { # App 'app.description': 'A toolkit for configuring X-Road security servers', 'app.label': 'xrdsst', # Root application parameters 'root.parameter.configfile.description': "Specify configuration file to use instead of default 'config/xrdsst.yml'", # Controllers 'auto.controller.description': 'Automatically performs all operations possible with configuration.', 'cert.controller.description': 'Commands for performing certificate operations.', 'client.controller.description': 'Commands for performing client management operations.', 'init.controller.description': 'Initializes security server with configuration anchor.', 'timestamp.controller.description': 'Commands for performing timestamping service operations.', 'token.controller.description': 'Commands for performing token operations.', 'service.controller.description': 'Commands for performing service operations.', 'status.controller.description': 'Query for server configuration statuses.', 'user.controller.description': 'Creates admin user on the security server.', 'endpoint.controller.description': 'Commands for perform service endpoints operations.', 'member.controller.description': 'Commands for performing member operations.', 'backup.controller.description': 'Commands for performing backup operations.', 'local_group.controller.description': 'Commands for performing client local groups operations', 'diagnostics.controller.description': 'Commands for performing diagnostics operations', 'key.controller.description': 'Commands for performing certificate keys operations', 'csr.controller.description': 'Commands for performing certificate csr operations', 'instance.controller.description': 'Commands for performing instance operations', 'security_server.controller.description': 'Commands for performing security server operations', 'internal_tls.controller.description': 'Commands for performing tls certificate operations', # Messages 'message.file.not.found': "File '{}' not found.", 'message.file.unreadable': "Could not read file '{}'.", 'message.config.unparsable': "Error parsing config: {}", 'message.config.serverless': "No security servers defined in '{}'.", 'message.server.keyless': "No API key available/acquired for '{}'.", 'message.skipped': "SKIPPED '{}'" } server_error_map = { 'core.Server.ClientProxy.CannotCreateSignature.Signer.TokenNotActive': 'Indicates that CLIENT proxy token has not been logged in.', 'core.Server.ClientProxy.IOError': "No valid sign certificate on the CLIENT proxy. The sign certificate may not exist, it may be disabled or it may not have a valid OCSP status.", 'core.Server.ClientProxy.LoggingFailed.InternalError': 'Writing messages to the message log database fails on the CLIENT proxy.', 'core.Server.ClientProxy.LoggingFailed.TimestamperFailed': "Timestamping service of CLIENT proxy currently unavailable, unconfigured or unconnectable.", 'core.Server.ClientProxy.NetworkError': 'CLIENT Proxy is not able to establish a network connection to provider side SERVER Proxy.', 'core.Server.ClientProxy.OutdatedGlobalConf': 'CLIENT proxy is not able to download global configuration from the Central Server and local copy of the global configuration has expired.', 'core.Server.ClientProxy.ServiceFailed.InternalError': 'Processing the request failed because of an internal error on the CLIENT proxy.', 'core.Server.ClientProxy.SslAuthenticationFailed': 'Security server (CLIENT Proxy) has no valid authentication certificate.', 'core.Server.ClientProxy.UnknownMember': 'The request contains invalid client or service identifier.', 'core.Server.ServerProxy.CannotCreateSignature.Signer.TokenNotActive': 'SERVER proxy token has not been logged in, contact service PROVIDER administrator.', 'core.Server.ServerProxy.LoggingFailed.InternalError': 'Processing the request failed because of an internal error on the SERVER proxy.', 'core.Server.ServerProxy.LoggingFailed.TimestamperFailed': 'Timestamping service of SERVER proxy currently unavailable, unconfigured or unconnectable.', 'core.Server.ServerProxy.OutdatedGlobalConf': 'SERVER proxy is not able to download global configuration from the Central Server and local copy of the global configuration has expired.', 'core.Server.ServerProxy.ServiceFailed.CannotCreateSignature': "There's a problem with signer on the PROVIDER SERVER proxy.", 'core.Server.ServerProxy.ServiceFailed.HttpError': 'SERVER proxy was not able to successfully connect to the service PROVIDER information system.', 'core.Server.ServerProxy.ServiceFailed.InvalidSoap': 'The service PROVIDER information system returned a malformed SOAP message to SERVER proxy.', 'core.Server.ServerProxy.ServiceFailed.InternalError': 'Processing the request failed because of an internal error on the PROVIDER SERVER proxy.', 'core.Server.ServerProxy.ServiceFailed.MissingHeaderField': 'The response returned by the service PROVIDER information system is missing some mandatory SOAP headers.', 'core.Server.ServerProxy.ServiceDisabled': 'Security server (SERVER Proxy) has disabled the service, maybe temporarily.', 'core.Server.ServerProxy.SslAuthenticationFailed': 'Security server (SERVER Proxy) has no valid authentication certificate.', 'core.Server.ServerProxy.UnknownService': 'Service identified by the service code included in the request does not exist on the SERVER proxy.' } server_hint_map = { 'core.Server.ClientProxy.IOError': [ """ The sign certificate may not exist, it may be disabled or it may not have a valid OCSP status. * Make sure the sign certificate is imported into the Security Server. * Make sure the sign certificate is active. * Make sure the token holding the sign certificate is available and logged in. * If the OCSP status of the sign certificate is not in the 'good' state, then the Security Server cannot use the certificate. """ ], 'core.Server.ClientProxy.NetworkError': [ """ On the CLIENT proxy, outgoing traffic to the provider SERVER proxy ports 5500 and 5577 must be allowed. PROVIDER side server lookup might be failing because it is registered with wrong public FQDN. """ ], 'core.Server.ClientProxy.OutdatedGlobalConf': [ """ It is possible that CLIENT proxy is unable to connect to the Central Server. Firewall configurations need to be rechecked. Restart of "xroad-confclient" process can be tried, if having shell access to CLIENT proxy. $ systemctl restart xroad-confclient """ ], 'core.Server.ClientProxy.SslAuthenticationFailed': [ """ The authentication certificate may not exist, it may be disabled, it may not be registered or it may not have a valid OCSP status. * Make sure the authentication certificate is imported into the Security Server. * Make sure the authentication certificate is active. * Make sure the authentication certificate is registered. * Make sure the token holding the authentication certificate is available and logged in. * If the OCSP status of the authentication certificate is not in the 'good' state, then the Security Server cannot use the certificate. """ ], 'core.Server.ClientProxy.UnknownMember': [ """ In case the client is not found, the client specified in the request is not registered at CLIENT proxy. In case addresses for service provider are not found, there's an error in the service identifier. """ ], # For the SERVER PROXY the helpful hints are not so many, unless the error in fact originates from the # other security server of the end-user, there is not much that can be done, contacting PROVIDER administrators # is almost always necessary. 'core.Server.ServerProxy.AccessDenied': [ """ The error message indicates that the client subsystem does not have sufficient permissions to invoke the service. Contact the service PROVIDER about the issue and request access permissions to the service. Don't forget to mention the subsystem that you want to use for accessing the service. """ ] } ascii_art = { 'message_flow': [ '╒═Trusted Network═╕ . INTERNET . ╒═Trusted Network══╕', '│ │ ╒══════════╕ . . ╒══════════╕ │ │', '│ │ │ Security │ | | │ Security │ │/ Service (REST) │', '│ xrdsst (REST) -│- ->- │\\ Server /│- ->- | - - ->- - - - | ->-│\\ Server /│- ->- │ │', '│ │ │ - ->- - │ . . │ - ->- - │ │\\ Service (SOAP) │', '│ │ ╘══════════╛ . . ╘══════════╛ │ │', '╘═════════════════╛ INTRANET ╘══════════════════╛', '', ' Service CONSUMER CLIENT Proxy SERVER Proxy Service PROVIDER' ] }
def longest_palindromic_substring(s): t = '^#'+'#'.join(s)+'#$' n = len(t) p = [0]*n c = r = cm = rm = 0 for i in range (1, n-1): p[i] = min(r-i, p[2*c-i]) if r > i else 0 while t[i-p[i]-1] == t[i+p[i]+1]: p[i] += 1 if p[i]+i > r: c, r = i, p[i]+i if p[i] > rm: cm, rm = i, p[i] return s[(cm-rm)//2:(cm+rm)//2]
def stringCompression(string=''): ''' Solution 1 Complexity Analysis O(n) time | O(1) space Perform basic string compression string: string return: string ''' # Gracefully handle type and Falsy values if (not isinstance(string, str) or string == ''): print('Arguments should be a valid non-empty strings') return False compressedChars = []; i = 0 while (i < len(string)): charCount = 1 currentChar = string[i] j = i + 1 while (j < len(string) and currentChar == string[j]): j += 1 charCount += 1 compressedChars.extend([currentChar, str(charCount)]) i = j return ''.join(compressedChars) if (len(compressedChars) < len(string)) else string # Test cases (black box - unit testing) testCases = [ # Normal # Data that is typical (expected) and should be accepted by the system. { 'assert': stringCompression('abbcccdddd'), 'expected': 'a1b2c3d4' }, { 'assert': stringCompression('aabcccccaaa'), 'expected': 'a2b1c5a3' }, { 'assert': stringCompression('abcdefghijkl'), 'expected': 'abcdefghijkl' }, # Boundary data (extreme data, edge case) # Data at the upper or lower limits of expectations that should be accepted by the system. { 'assert': stringCompression('a'), 'expected': 'a' }, { 'assert': stringCompression('abcdefghijklmnopqrstuvxzyw'), 'expected': 'abcdefghijklmnopqrstuvxzyw' }, # Abnormal data (erroneous data) # Data that falls outside of what is acceptable and should be rejected by the system. { 'assert': stringCompression(), 'expected': False }, { 'assert': stringCompression(0), 'expected': False }, { 'assert': stringCompression(''), 'expected': False }, { 'assert': stringCompression([]), 'expected': False }, { 'assert': stringCompression(()), 'expected': False }, { 'assert': stringCompression({}), 'expected': False }, { 'assert': stringCompression(None), 'expected': False }, { 'assert': stringCompression(False), 'expected': False } ] # Run tests for (index, test) in enumerate(testCases): print(f'# Test {index + 1}') print(f'Actual: {test["assert"]}') print(f'Expected: {test["expected"]}') print('🤘 Test PASSED 🤘' if test["assert"] == test["expected"] else '👎 Test FAILED 👎', '\n')
# create a Blender service, we'll call it ... blender blender = Runtime.start("blender","Blender") # connect it to Blender - blender must be running the Blender.py # or easier yet, start blender with the Blender.blend file # select game mode then press p with cursor over the rendering screen if not blender.connect(): print("could not connect to blender - is it running and did you remember to run Blender.py") else: print("connected") # create InMoov service i01 = Runtime.start("i01","InMoov") # next we are going to create the arduino BEFORE startMouthControl creates it arduino = Runtime.start("i01.left","Arduino") # now we attach the arduino to blender - creating a virtual Arduino # and it automagically connects all the serial pipes under the hood blender.attach(arduino) # i01.startMouthControl("MRL.0") # i01.startHead("MRL.0") # mouth = i01.startMouth() neck = Runtime.start("i01.head.neck","Servo") neck.attach(arduino, 7) ######### start mods ################### neck = Runtime.getService("i01.head.neck") neck.map(0,180,90,270) neck.setMinMax(-360, 360) arduino01 = Runtime.getService("arduino01") rothead = Runtime.start("i01.head.rothead", "Servo") rothead.attach(arduino01, 8) #rothead = Runtime.getService("i01.head.rothead") neck.moveTo(90) sleep(10)
class Candidate: _inner_id = 0 def __init__(self, name=""): self._id = Candidate._inner_id self.name = name Candidate._inner_id += 1 CandidateList.append(self) @staticmethod def reset_id(): Candidate._inner_id = 0 class CandidateList: """ CandidateList has no constructor because it is used as a Singleton """ _inner = [] def __str__(self): """ transform the string reference of the list in a list of string object's reference to each candidate stored in it :return: a string (list format) of candidate references """ return str(CandidateList._inner) @staticmethod def append(to_add: Candidate): """ append a candidate on the tail of the CandidateList this function is automatically called when a candidate is created :param to_add: a Candidate object to store """ CandidateList._inner.append(to_add) @staticmethod def insert(to_add: Candidate, pos: int): """ Insert a candidate on the position specified in pos argument :param to_add: Candidate to insert in the list :param pos: the index where you want to store the candidate """ CandidateList._inner.insert(pos, to_add) @staticmethod def get(): """ :return: the list of candidate objects usable in program """ return CandidateList._inner @staticmethod def size(): """ :return: the size of the inner list or the number of candidates stored in the CandidateList """ return len(CandidateList._inner) @staticmethod def is_empty(): return len(CandidateList._inner) == 0 @staticmethod def empty_list(): """ Method to empty the CandidateList and reset the Candidate id """ CandidateList._inner = [] Candidate.reset_id()
class CloudWatchEvent: def __init__(self, schedule_expression: str, is_active: bool, name: str =None): self.name = name self.schedule_expression = schedule_expression self.is_active = is_active
# increasing paths in an array def f1_3(array): # O(N^2) if len(array) <= 1: return ans = [] start_idx, idx = 0, 1 prenum = array[start_idx] while idx < len(array): if array[idx] >= prenum: for i in range(start_idx, idx): ans.append(array[i:idx + 1]) else: start_idx = idx prenum = array[idx] idx += 1 return ans def f1_2(array): # O(N^2) search from start to end if len(array) <= 1: return ans = [] # a list of increasing arrays for start_idx in range(len(array) - 1): prenum = array[start_idx] idx = start_idx + 1 subarray = [prenum] while idx < len(array) and array[idx] >= prenum: subarray.append(array[idx]) ans.append(subarray[:]) prenum = array[idx] idx += 1 return ans def f1(array): # O(N^2) search from end to start if len(array) <= 1: return ans = [] # list of increasing arrays for end_idx in range(1, len(array)): last_num = array[end_idx] subarray = [last_num] idx = end_idx - 1 while idx >= 0: num = array[idx] if num <= last_num: subarray.append(num) ans.append(list(reversed(subarray))) idx -= 1 last_num = num else: break return ans array = [1, 3, 4, 2, 6] print(f1(array)) print(f1_2(array)) print(f1_3(array)) # increasing paths in a tree class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def f2(root): if not root or (not root.left and not root.right): return ans = [] traverse(root, ans) return ans def traverse(root, ans): # O(N) valid_path(root, ans, [root.val]) left, right = root.left, root.right if left: traverse(left, ans) if right: traverse(right, ans) def valid_path(root, ans, path): # O(logN ^2) left, right = root.left, root.right if left and left.val >= root.val: ans.append(path + [left.val]) valid_path(left, ans, path + [left.val]) if right and right.val >= root.val: ans.append(path + [right.val]) valid_path(right, ans, path + [right.val]) def f2_2(root): if not root or (not root.left and not root.right): return ans = [] get_paths(root, [root.val], ans) return ans def get_paths(root, path, ans): left, right = root.left, root.right if left: if left.val >= path[-1]: valid_path_reversed = [left.val] for val in reversed(path): valid_path_reversed.append(val) ans.append(list(reversed(valid_path_reversed))) get_paths(left, path + [left.val], ans) else: get_paths(left, [left.val], ans) if right and right.val >= path[-1]: if right.val >= path[-1]: valid_path_reversed = [right.val] for val in reversed(path): valid_path_reversed.append(val) ans.append(list(reversed(valid_path_reversed))) get_paths(right, path + [right.val], ans) else: get_paths(right, [right.val], ans) node_4 = Node(4) node_5 = Node(5) node_9 = Node(9) node_3 = Node(3) node_6 = Node(6) node_8 = Node(8) node_10 = Node(10) node_4.left = node_5 node_4.right = node_9 node_5.left = node_3 node_5.right = node_6 node_9.left = node_8 node_9.right = node_10 print(f2(node_4)) print(f2_2(node_4))
class Movie(object): def __init__(self): self.title = "" self.id = "" self.plot = "" self.year = "" def __str__(self): return str(self.__dict__)
'''2. Write a Python program that accepts six numbers as input and sorts them in descending order. Input: Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 = n1, n2, n3, n4, n5, n6 = 100000). The six numbers are separated by a space. Input six integers: 15 30 25 14 35 40 After sorting the said integers: 40 35 30 25 15 14''' integers = input("Input six integers:\n") integers = sorted(integers.split(), reverse=True) print("After sorting the said integers:\n",integers)
def list_squared(m, n): data=[[1, 1], [42, 2500], [246, 84100],[287, 84100],[728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100],[4264, 24304900],[6237, 45024100], [9799, 96079204], [9855, 113635600]] result=[] index=0 while True: if m<=data[index][0]<=n: result.append(data[index]) index+=1 if index==len(data): break return result
# Array, two pointers class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if not height or len(height) < 3: return 0 left_max = right_max = 0 ans = left = 0 right = len(height) - 1 while left < right: left_max = max(height[left], left_max) right_max = max(height[right], right_max) if left_max < right_max: ans += left_max - height[left] left += 1 else: ans += right_max - height[right] right -= 1 return ans