content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
site = 'ftp.skilldrick.co.uk' webRoot = '/public_html' localDir = '.' #by default use current directory remoteDir = 'tmpl' ignoreDirs = ['.git', 'fancybox', 'safeinc'] ignoreFileSuffixes = ['.py', '.pyc', '~', '#', '.swp', '.gitignore', '.lastrun', 'Makefile', '.bat', 'Thumb...
site = 'ftp.skilldrick.co.uk' web_root = '/public_html' local_dir = '.' remote_dir = 'tmpl' ignore_dirs = ['.git', 'fancybox', 'safeinc'] ignore_file_suffixes = ['.py', '.pyc', '~', '#', '.swp', '.gitignore', '.lastrun', 'Makefile', '.bat', 'Thumbs.db', 'README.markdown']
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, data): new_node = Node(data) if not self.head: self....
class Node: def __init__(self, data): self.data = data self.next = None class Circularlinkedlist: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, data): new_node = node(data) if not self.head: self...
n = 8 if n%2==0 and (n in range(2,6) or n>20 ): print ("Not Weird") else: print ("Weird")
n = 8 if n % 2 == 0 and (n in range(2, 6) or n > 20): print('Not Weird') else: print('Weird')
routes = Blueprint("routes", __name__, template_folder="templates") if not os.path.exists(os.path.dirname(recipyGui.config.get("tinydb"))): os.mkdir(os.path.dirname(recipyGui.config.get("tinydb"))) @recipyGui.route("/") def index(): form = SearchForm() query = request.args.get("query", "").strip() escaped_query = r...
routes = blueprint('routes', __name__, template_folder='templates') if not os.path.exists(os.path.dirname(recipyGui.config.get('tinydb'))): os.mkdir(os.path.dirname(recipyGui.config.get('tinydb'))) @recipyGui.route('/') def index(): form = search_form() query = request.args.get('query', '').strip() esc...
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: a = headA b = headB while a != b: if a: a = a.next else: a = headB if b: b = b.next else: b = headA return a
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: a = headA b = headB while a != b: if a: a = a.next else: a = headB if b: b = b.next else: ...
def reformat(string): string = string.replace('-', '').replace('(', '').replace(')', '') return string[-10:] if len(string) > 7 else '495' + string[-7:] n = 4 notes = [input() for i in range(n)] for note in notes[1:]: print('YES' if reformat(notes[0]) == reformat(note) else 'NO')
def reformat(string): string = string.replace('-', '').replace('(', '').replace(')', '') return string[-10:] if len(string) > 7 else '495' + string[-7:] n = 4 notes = [input() for i in range(n)] for note in notes[1:]: print('YES' if reformat(notes[0]) == reformat(note) else 'NO')
class SQLiteQueryResultSpy(object): def __init__(self, row_count, lazy_result): self.row_count = row_count self.number_of_elements = row_count self.lazy_result = lazy_result @property def rowcount(self): return self.row_count def fetchone(self): self.number_of_e...
class Sqlitequeryresultspy(object): def __init__(self, row_count, lazy_result): self.row_count = row_count self.number_of_elements = row_count self.lazy_result = lazy_result @property def rowcount(self): return self.row_count def fetchone(self): self.number_of_...
def odeeuler(F,x0,y0,h,N): x = x0 y = y0 for i in range(1,N+1): y += h*F(x,y) x += h return y
def odeeuler(F, x0, y0, h, N): x = x0 y = y0 for i in range(1, N + 1): y += h * f(x, y) x += h return y
REQUEST_LAUNCH_MSG = "Hello, I'm Otto Investment bot, I' here to inform you about your investments. Do you want me to tell you a report on your portfolio? Or maybe information about specific stock? " REQUEST_LAUNCH_REPROMPT = "Go on, tell me what can I do for you." REQUEST_END_MSG = "Bye bye. " # General INTENT_GENER...
request_launch_msg = "Hello, I'm Otto Investment bot, I' here to inform you about your investments. Do you want me to tell you a report on your portfolio? Or maybe information about specific stock? " request_launch_reprompt = 'Go on, tell me what can I do for you.' request_end_msg = 'Bye bye. ' intent_general_ok = 'Ok ...
# A string index should always be within range s = "Hello" print(s[5]) # Syntax error - valid indices for s are 0-4
s = 'Hello' print(s[5])
#!/anaconda3/bin/python3.6 # coding=utf-8 if __name__ == "__main__": print("suppliermgr package")
if __name__ == '__main__': print('suppliermgr package')
# encoding: utf-8 # Copyright 2008 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. ''' EDRN RDF Service: unit and functional tests. '''
""" EDRN RDF Service: unit and functional tests. """
with open("input.txt") as input_file: lines = input_file.readlines() fish = [int(n) for n in lines[0].split(",")] print(fish) for _ in range(80): fish = [f-1 for f in fish] zeroes = fish.count(-1) for i, f in enumerate(fish): if f == -1: fish[i] = 6 fish.extend([8]*zeroes) pri...
with open('input.txt') as input_file: lines = input_file.readlines() fish = [int(n) for n in lines[0].split(',')] print(fish) for _ in range(80): fish = [f - 1 for f in fish] zeroes = fish.count(-1) for (i, f) in enumerate(fish): if f == -1: fish[i] = 6 fish.extend([8] * zeroes) ...
def test_first(setup_teardown): text_logo = setup_teardown.find_element_by_id('logo').text assert text_logo == 'Your Store'
def test_first(setup_teardown): text_logo = setup_teardown.find_element_by_id('logo').text assert text_logo == 'Your Store'
def calculaMulta (velocidade): if velocidade > 50 and velocidade < 55: return 230 elif velocidade > 55 and velocidade <= 60: return 340 elif velocidade > 60: valor = (velocidade-50) * 19.28 return valor else: return 0 vel = int(input("Informe a v...
def calcula_multa(velocidade): if velocidade > 50 and velocidade < 55: return 230 elif velocidade > 55 and velocidade <= 60: return 340 elif velocidade > 60: valor = (velocidade - 50) * 19.28 return valor else: return 0 vel = int(input('Informe a velocidade :')) p...
class Solution: def removeElement(self, nums: List[int], val: int) -> int: for numbers in range(len(nums)): if val not in nums: break if len(nums) == 0: return 0 else: nums.remove(val) print(len(nums)) ...
class Solution: def remove_element(self, nums: List[int], val: int) -> int: for numbers in range(len(nums)): if val not in nums: break if len(nums) == 0: return 0 else: nums.remove(val) print(len(nums)) prin...
# import matplotlib.pyplot as plt # Menge an Werten zahlen = "1203456708948673516874354531568764645" # Initialisieren der Histogramm Variable histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for index in range(len(zahlen)): histogramm[int(zahlen[index])] += 1 # plt.hist(histogramm, bins = 9) # plt.show() for i in r...
zahlen = '1203456708948673516874354531568764645' histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for index in range(len(zahlen)): histogramm[int(zahlen[index])] += 1 for i in range(0, 10): print('Die Zahl', i, 'kommt', histogramm[i], 'Mal vor.')
#!/usr/bin/env pytho codigo = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', ...
codigo = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '-...
class Cloth: def __init__(self, name, shop_url, available, brand_logo, price, img_url): self.name = name self.shop_url = shop_url self.available = available self.brand_logo = brand_logo self.price = price self.img_url = img_url def __str__(self): print('N...
class Cloth: def __init__(self, name, shop_url, available, brand_logo, price, img_url): self.name = name self.shop_url = shop_url self.available = available self.brand_logo = brand_logo self.price = price self.img_url = img_url def __str__(self): print('...
def pickingNumbers(a): solution = 0 for num1 in a: if a.count(num1) + a.count(num1 + 1) > solution: solution = a.count(num1) + a.count(num1 + 1) return solution
def picking_numbers(a): solution = 0 for num1 in a: if a.count(num1) + a.count(num1 + 1) > solution: solution = a.count(num1) + a.count(num1 + 1) return solution
# while loops def nearest_square(limit): number = 0 while (number+1) ** 2 < limit: number += 1 return number ** 2 test1 = nearest_square(40) print("expected result: 36, actual result: {}".format(test1)) # black jack card_deck = [4, 11, 8, 5, 13, 2, 8, 10] hand = [] while sum(hand) <= 21: hand.a...
def nearest_square(limit): number = 0 while (number + 1) ** 2 < limit: number += 1 return number ** 2 test1 = nearest_square(40) print('expected result: 36, actual result: {}'.format(test1)) card_deck = [4, 11, 8, 5, 13, 2, 8, 10] hand = [] while sum(hand) <= 21: hand.append(card_deck.pop()) pri...
A_1,B_1 = input().split(" ") a = int(A_1) b = int(B_1) if a > b: horas = (24-a) + b print("O JOGO DUROU %i HORA(S)"%(horas)) elif a == b: print("O JOGO DUROU 24 HORA(S)") else: horas = b - a print("O JOGO DUROU %i HORA(S)"%(horas))
(a_1, b_1) = input().split(' ') a = int(A_1) b = int(B_1) if a > b: horas = 24 - a + b print('O JOGO DUROU %i HORA(S)' % horas) elif a == b: print('O JOGO DUROU 24 HORA(S)') else: horas = b - a print('O JOGO DUROU %i HORA(S)' % horas)
# https://app.codesignal.com/arcade/code-arcade/well-of-integration/QmK8kHTyKqh8xDoZk def threeSplit(numbers): # From a list of numbers, cut into three pieces such that each # piece contains an integer, and the sum of integers in each # piece is the same. # We know that the total sum of elements in the arr...
def three_split(numbers): total = sum(numbers) third = total / 3 start_count = 0 acum_sum = 0 result = 0 for idx in range(len(numbers) - 1): acum_sum += numbers[idx] if acum_sum == 2 * third and start_count > 0: result += start_count if acum_sum == third: ...
def elevadorLotado(paradas, capacidade): energiaGasta = 0 while paradas: ultimo = paradas[-1] energiaGasta += 2*ultimo paradas = paradas[:-capacidade] return energiaGasta testes = int(input()) for x in range(testes): NCM = input().split() capacidade = int(NCM[1]) destinhos = list(map...
def elevador_lotado(paradas, capacidade): energia_gasta = 0 while paradas: ultimo = paradas[-1] energia_gasta += 2 * ultimo paradas = paradas[:-capacidade] return energiaGasta testes = int(input()) for x in range(testes): ncm = input().split() capacidade = int(NCM[1]) des...
with open('EN_op_1_57X32A15_31.csv','r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1])
with open('EN_op_1_57X32A15_31.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1])
chars = { 'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '111', '101', '110'], 'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '111', ...
chars = {'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '111', '101', '110'], 'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '111', '100', '111'], 'F': ['111', '100', '111', '100', '100'], 'G': ['0111', '1000', '1011', '1001', '0110'], 'H': ['101',...
SAGA_ENABLED = 1 MIN_DETECTED_FACE_WIDTH = 20 MIN_DETECTED_FACE_HEIGHT = 20 PICKLE_FILES_DIR = "/app/facenet/resources/output" MODEL_FILES_DIR = "/app/facenet/resources/model" UPLOAD_DIR = "/app/resources/images/" # PICKLE_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/output' # MODEL_FILES_DIR...
saga_enabled = 1 min_detected_face_width = 20 min_detected_face_height = 20 pickle_files_dir = '/app/facenet/resources/output' model_files_dir = '/app/facenet/resources/model' upload_dir = '/app/resources/images/'
class Contact: def __init__(self, first_name: str, second_name: str, phone_number: str): self._first_name = first_name self._second_name = second_name self._phone_number = phone_number @property def first_name(self): return self._first_name @property def second_name...
class Contact: def __init__(self, first_name: str, second_name: str, phone_number: str): self._first_name = first_name self._second_name = second_name self._phone_number = phone_number @property def first_name(self): return self._first_name @property def second_nam...
def answer(l): res = 0 length = len(l) for x in xrange(length): left = 0 right = 0 for i in xrange(x): if not (l[x] % l[i]): left = left + 1 for i in xrange(x + 1, length): if not (l[i] % l[x]): right = right + 1 ...
def answer(l): res = 0 length = len(l) for x in xrange(length): left = 0 right = 0 for i in xrange(x): if not l[x] % l[i]: left = left + 1 for i in xrange(x + 1, length): if not l[i] % l[x]: right = right + 1 res...
# NOTE: The sitename and dataname corresponding to the observation are 'y' by default # Any latents that are not population level model_constants = { 'arm.anova_radon_nopred': { 'population_effects':{'mu_a', 'sigma_a', 'sigma_y'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1200) }, ...
model_constants = {'arm.anova_radon_nopred': {'population_effects': {'mu_a', 'sigma_a', 'sigma_y'}, 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1200)}, 'arm.anova_radon_nopred_chr': {'population_effects': {'sigma_a', 'sigma_y', 'mu_a'}, 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1200)}, 'arm.congress': {'populatio...
def addStrings(num1: str, num2: str) -> str: i, j = len(num1) - 1, len(num2) - 1 tmp = 0 result = "" while i >= 0 or j >= 0: if i >= 0: tmp += int(num1[i]) i -= 1 if j >= 0: tmp += int(num2[j]) j -= 1 result = str(tmp % 10) + result...
def add_strings(num1: str, num2: str) -> str: (i, j) = (len(num1) - 1, len(num2) - 1) tmp = 0 result = '' while i >= 0 or j >= 0: if i >= 0: tmp += int(num1[i]) i -= 1 if j >= 0: tmp += int(num2[j]) j -= 1 result = str(tmp % 10) + r...
intin = int(input()) if intin == 2: print("NO") elif intin%2==0: if intin%4==0: print("YES") elif (intin-2)%4==0: print("YES") else: print("NO") else: print("NO")
intin = int(input()) if intin == 2: print('NO') elif intin % 2 == 0: if intin % 4 == 0: print('YES') elif (intin - 2) % 4 == 0: print('YES') else: print('NO') else: print('NO')
def rgb(r, g, b): s="" if r>255: r=255 elif g>255: g=255 elif b>255: b=255 if r<0: r=0 elif g<0: g=0 elif b<0: b=0 r='{0:x}'.format(r) g='{0:x}'.format(g) b='{0:x}'.format(b) if int(r,16)<=15 and int(r,16)>=0: r='0'+r ...
def rgb(r, g, b): s = '' if r > 255: r = 255 elif g > 255: g = 255 elif b > 255: b = 255 if r < 0: r = 0 elif g < 0: g = 0 elif b < 0: b = 0 r = '{0:x}'.format(r) g = '{0:x}'.format(g) b = '{0:x}'.format(b) if int(r, 16) <= 15 a...
# https://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/ def disem(str): result = '' rem_vowels = '' vowels = 'aeiou' for c in str: if c not in vowels and not c.isspace(): result += c elif not c.isspace(): rem_vowels += c...
def disem(str): result = '' rem_vowels = '' vowels = 'aeiou' for c in str: if c not in vowels and (not c.isspace()): result += c elif not c.isspace(): rem_vowels += c print(result + '\n' + rem_vowels) def main(): phrase = input('\nPlease enter a line: ') ...
''' @description 2019/09/22 20:53 '''
""" @description 2019/09/22 20:53 """
def setup(): size (500,500) background (100) smooth() noLoop() strokeWeight(15) str(100) def draw (): fill (250) rect (100,100, 100,100) fill (50) rect (200,200, 50,100)
def setup(): size(500, 500) background(100) smooth() no_loop() stroke_weight(15) str(100) def draw(): fill(250) rect(100, 100, 100, 100) fill(50) rect(200, 200, 50, 100)
#Write a function that accepts a 2D list of integers and returns the maximum EVEN value for the entire list. #You can assume that the number of columns in each row is the same. #Your function should return None if the list is empty or all the numbers in the 2D list are odd. #Do NOT use python's built in max() functi...
def even_empty_odd(list2d): len_list = 0 even_numbers = [] odd_numbers = [] count = 0 for list_number in list2d: len_list += len(list_number) if len_list == 0: return None else: for list_number in list2d: for number in list_number: if numbe...
### assuming you have Google Chrome installed... ## remember `pip3 install -r setup.py` before trying any scrapers in this dir # have a nice day selenium chromedriver requests
selenium chromedriver requests
class Power: def __init__(self, power_id, name, amount): self.power_id = power_id self.power_name = name self.amount = amount @classmethod def from_json(cls, json_object): return cls(json_object["id"], json_object["name"], json_object["amount"]) def __eq__(self, other)...
class Power: def __init__(self, power_id, name, amount): self.power_id = power_id self.power_name = name self.amount = amount @classmethod def from_json(cls, json_object): return cls(json_object['id'], json_object['name'], json_object['amount']) def __eq__(self, other)...
DB_PORT=5432 DB_USERNAME="postgres" DB_PASSWORD="password" DB_HOST="127.0.0.1" DB_DATABASE="eventtriggertest"
db_port = 5432 db_username = 'postgres' db_password = 'password' db_host = '127.0.0.1' db_database = 'eventtriggertest'
setting = { 'file': './data/crime2010_2018.csv', 'limit': 10000, 'source': [0,1,2,3,7,8,10,11,14,16,23,5,25], 'vars': { 0 : 'num', 1 : 'date_reported', 2:'date_occured', 3:'time_occured', 7:'crime_code', 8:'crime_desc', 10:'victim_age', 11:...
setting = {'file': './data/crime2010_2018.csv', 'limit': 10000, 'source': [0, 1, 2, 3, 7, 8, 10, 11, 14, 16, 23, 5, 25], 'vars': {0: 'num', 1: 'date_reported', 2: 'date_occured', 3: 'time_occured', 7: 'crime_code', 8: 'crime_desc', 10: 'victim_age', 11: 'victim_sex', 14: 'premise_desc', 16: 'weapon', 23: 'address', 5: ...
'''from axju.core.tools import SmartCLI from axju.worker.git import GitWorker def main(): cli = SmartCLI(GitWorker) cli.run() if __name__ == '__main__': main() '''
"""from axju.core.tools import SmartCLI from axju.worker.git import GitWorker def main(): cli = SmartCLI(GitWorker) cli.run() if __name__ == '__main__': main() """
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Michael Eaton <meaton@iforium.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Li...
ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} documentation = "\n---\nmodule: win_firewall\nversion_added: '2.4'\nshort_description: Enable or disable the Windows Firewall\ndescription:\n- Enable or Disable Windows Firewall profiles.\noptions:\n profiles:\n descr...
load("//webgen:webgen.bzl", "erb_file", "js_file", "scss_file", "website") def page(name, file, out=None, data=False, math=False, plot=False): extra_templates = [] if data: extra_templates.append("template/data.html") if math: extra_templates.append("template/mathjax.html") if plot: extra_templates.app...
load('//webgen:webgen.bzl', 'erb_file', 'js_file', 'scss_file', 'website') def page(name, file, out=None, data=False, math=False, plot=False): extra_templates = [] if data: extra_templates.append('template/data.html') if math: extra_templates.append('template/mathjax.html') if plot: ...
#data kualitatif a = "the dogis hungry. The cat is bored. the snack is awake." s = a.split(".") print(s) print(s[0]) print(s[1]) print(s[2])
a = 'the dogis hungry. The cat is bored. the snack is awake.' s = a.split('.') print(s) print(s[0]) print(s[1]) print(s[2])
''' Completion sample module ''' def func_module_level(i, a='foo'): 'some docu' return i * a class ModClass: ''' some inner namespace class''' @classmethod def class_level_func(cls, boolean=True): return boolean class NestedClass: ''' some inner namespace class''' @c...
""" Completion sample module """ def func_module_level(i, a='foo'): """some docu""" return i * a class Modclass: """ some inner namespace class""" @classmethod def class_level_func(cls, boolean=True): return boolean class Nestedclass: """ some inner namespace class""" ...
N = int(input()) A = int(input()) for a in range(A+1): for j in range(21): if a + 500 * j == N: print("Yes") exit() print("No")
n = int(input()) a = int(input()) for a in range(A + 1): for j in range(21): if a + 500 * j == N: print('Yes') exit() print('No')
# Scrapy settings for uefispider project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'uefispider' SPIDER_MODULES = ['uefispider.spiders'] NEWSPIDER_MODULE = '...
bot_name = 'uefispider' spider_modules = ['uefispider.spiders'] newspider_module = 'uefispider.spiders' user_agent = 'uefispider (+https://github.com/theopolis/uefi-spider)' item_pipelines = {'uefispider.pipelines.UefispiderPipeline': 1} cookies_debug = True
class Solution: def baseNeg2(self, N: int) -> str: if N == 0: return "0" nums = [] while N != 0: r = N % (-2) N //= (-2) if r < 0: r += 2 N += 1 nums.append(r) return ''.join(map(str, nums[::-...
class Solution: def base_neg2(self, N: int) -> str: if N == 0: return '0' nums = [] while N != 0: r = N % -2 n //= -2 if r < 0: r += 2 n += 1 nums.append(r) return ''.join(map(str, nums[::-1]...
# This file contains the different states of the api class Config(object): DEBUG = False SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS = False class Production(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True
class Config(object): debug = False sqlalchemy_database_uri = 'sqlite:///database.db' sqlalchemy_track_modifications = False class Production(Config): debug = False class Developmentconfig(Config): debug = True
#!/usr/bin/env python print('nihao')
print('nihao')
def friend_find(line): check=[i for i,j in enumerate(line) if j=="red"] total=0 for i in check: if i>=2 and line[i-1]=="blue" and line[i-2]=="blue": total+=1 elif (i>=1 and i<=len(line)-2) and line[i-1]=="blue" and line[i+1]=="blue": total+=1 elif (i<=len(line...
def friend_find(line): check = [i for (i, j) in enumerate(line) if j == 'red'] total = 0 for i in check: if i >= 2 and line[i - 1] == 'blue' and (line[i - 2] == 'blue'): total += 1 elif (i >= 1 and i <= len(line) - 2) and line[i - 1] == 'blue' and (line[i + 1] == 'blue'): ...
# _*_ coding: utf-8 _*_ # # Package: bookstore.src.core.validator __all__ = ["validators"]
__all__ = ['validators']
sanitizedLines = [] with open("diff.txt") as f: for line in f: sanitizedLines.append("https://interclip.app/" + line.strip()) print(str(sanitizedLines))
sanitized_lines = [] with open('diff.txt') as f: for line in f: sanitizedLines.append('https://interclip.app/' + line.strip()) print(str(sanitizedLines))
# # chmod this file securely and be sure to remove the default users # users = { "frodo" : "1ring", "yossarian" : "catch22", "ayla" : "jondalar", }
users = {'frodo': '1ring', 'yossarian': 'catch22', 'ayla': 'jondalar'}
def calcMul(items): mulTotal = 1 for i in items: mulTotal *= i return mulTotal print("The multiple is: ",calcMul([10,20,30]))
def calc_mul(items): mul_total = 1 for i in items: mul_total *= i return mulTotal print('The multiple is: ', calc_mul([10, 20, 30]))
def validate_contract_create(request, **kwargs): if request.validated['auction'].status not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', 'Can\'t add contract in current ({}) auction status'.format(request.validated['auction'].status)) ...
def validate_contract_create(request, **kwargs): if request.validated['auction'].status not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', "Can't add contract in current ({}) auction status".format(request.validated['auction'].status)) request.errors.status = 403 ...
class User: def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode): self.userName = userName self.firstName = firstName self.lastName = lastName self.passportNumber = passportNumber self.address1 = address1 self.address2 = addre...
class User: def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode): self.userName = userName self.firstName = firstName self.lastName = lastName self.passportNumber = passportNumber self.address1 = address1 self.address2 = addr...
# pylint: skip-file # pylint: disable=too-many-instance-attributes class VMInstance(GCPResource): '''Object to represent a gcp instance''' resource_type = "compute.v1.instance" # pylint: disable=too-many-arguments def __init__(self, rname, project, z...
class Vminstance(GCPResource): """Object to represent a gcp instance""" resource_type = 'compute.v1.instance' def __init__(self, rname, project, zone, machine_type, metadata, tags, disks, network_interfaces, service_accounts=None): """constructor for gcp resource""" super(VMInstance, self)....
# # Variables: # - Surname: String # - SurnameLength, NextCodeNumber, CustomerID, i: Integer # - NextChar: Char # Surname = input("Enter your surname: ") SurnameLength = len(Surname) CustomerID = 0 for i in range(0, SurnameLength): NextChar = Surname[i] NextCodeNumber = ord(NextChar) CustomerID = C...
surname = input('Enter your surname: ') surname_length = len(Surname) customer_id = 0 for i in range(0, SurnameLength): next_char = Surname[i] next_code_number = ord(NextChar) customer_id = CustomerID + NextCodeNumber print('Customer ID is ', CustomerID)
class classproperty(object): '''Implements both @property and @classmethod behavior.''' def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): return self.getter(instance) if instance else self.getter(owner)
class Classproperty(object): """Implements both @property and @classmethod behavior.""" def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): return self.getter(instance) if instance else self.getter(owner)
def is_empty(text): if text in [None,'']: return True return False
def is_empty(text): if text in [None, '']: return True return False
mysql_config = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'HOST', 'port': 3306, 'charset': 'utf8mb4', 'database': 'DATABASE', 'raise_on_warnings': False, 'use_pure': False, }
mysql_config = {'user': 'USER', 'password': 'PASSWORD', 'host': 'HOST', 'port': 3306, 'charset': 'utf8mb4', 'database': 'DATABASE', 'raise_on_warnings': False, 'use_pure': False}
movie = {"title": "padmavati", "director": "Bhansali","year": "2018", "rating": "4.5"} print(movie) print(movie['year']) movie['year'] = 2019 #update data. print(movie['year']) print('-' * 20) for x in movie: print(x) #this print key. print(movie[x]) #this print value at key. print('-' *...
movie = {'title': 'padmavati', 'director': 'Bhansali', 'year': '2018', 'rating': '4.5'} print(movie) print(movie['year']) movie['year'] = 2019 print(movie['year']) print('-' * 20) for x in movie: print(x) print(movie[x]) print('-' * 20) movie = {} movie['title'] = 'Manikarnika' movie['Director'] = 'kangana ...
def comb(m, s): if m == 1: return [[x] for x in s] if m == len(s): return [s] return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
def comb(m, s): if m == 1: return [[x] for x in s] if m == len(s): return [s] return [s[:1] + a for a in comb(m - 1, s[1:])] + comb(m, s[1:])
n, x = map(int, input().split()) mark_sheet = [] for _ in range(x): mark_sheet.append( map(float, input().split()) ) for i in zip(*mark_sheet): print( sum(i)/len(i) )
(n, x) = map(int, input().split()) mark_sheet = [] for _ in range(x): mark_sheet.append(map(float, input().split())) for i in zip(*mark_sheet): print(sum(i) / len(i))
__name__ = "lbry" __version__ = "0.42.1" version = tuple(__version__.split('.'))
__name__ = 'lbry' __version__ = '0.42.1' version = tuple(__version__.split('.'))
# coding=utf-8 class AutumnInvokeException(Exception): pass class InvocationTargetException(Exception): pass if __name__ == '__main__': pass
class Autumninvokeexception(Exception): pass class Invocationtargetexception(Exception): pass if __name__ == '__main__': pass
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: ''' T: O(n log n + n^3) S: O(1) ''' n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in rang...
class Solution: def four_sum(self, nums: List[int], target: int) -> List[List[int]]: """ T: O(n log n + n^3) S: O(1) """ n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x ...
class event_meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._...
class Event_Meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_ma...
def sum(a, b): return a + b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) c = sum(a, b) print("The sum of the two numbers is: ", c)
def sum(a, b): return a + b a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) c = sum(a, b) print('The sum of the two numbers is: ', c)
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x)...
class Solution: def sorted_squares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x...
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def computeGCD(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if ((x % i == 0) and (y % i == 0)): ...
class Solution: def compute_gcd(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if x % i == 0 and y % i == 0: gcd = i return gcd def max_points(self, A, B): n = len(A) ...
TVOC =2300 if TVOC <=2500 and TVOC >=2000: print("Level-5", "Unhealty") print("Hygienic Rating - Situation not acceptable") print("Recommendation - Use only if unavoidable/Intense ventilation necessary") print("Exposure Limit - Hours")
tvoc = 2300 if TVOC <= 2500 and TVOC >= 2000: print('Level-5', 'Unhealty') print('Hygienic Rating - Situation not acceptable') print('Recommendation - Use only if unavoidable/Intense ventilation necessary') print('Exposure Limit - Hours')
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
'''Spiral Matrix''' # spiral :: Int -> [[Int]] def spiral(n): '''The rows of a spiral matrix of order N. ''' def go(rows, cols, x): return [list(range(x, x + cols))] + [ list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols)) ] if 0 < rows else [[]] return...
"""Spiral Matrix""" def spiral(n): """The rows of a spiral matrix of order N. """ def go(rows, cols, x): return [list(range(x, x + cols))] + [list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols))] if 0 < rows else [[]] return go(n, n, 0) def main(): """Spiral matrix of order 5, in...
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def...
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date de...
# Users to create/delete users = [ {'name': 'user1', 'password': 'passwd1', 'email': 'mail@example.com', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': 'mdsail@example.com', 'tenant': 'tenant1', 'enabled': False} ] # Roles to create/delete roles = [ {...
users = [{'name': 'user1', 'password': 'passwd1', 'email': 'mail@example.com', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': 'mdsail@example.com', 'tenant': 'tenant1', 'enabled': False}] roles = [{'name': 'SomeRole'}] keypairs = [{'name': 'key1', 'public_key': 'ssh-rsa AAA...
# -*- coding: utf-8 -*- __title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = 'nurupo.contributions@gmail.com' __license__ ...
__title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = 'nurupo.contributions@gmail.com' __license__ = 'MIT' __copyright__ = '...
n=1260 count=0 list=[500,100,50,10] for coin in list: count += n//coin n %= coin print(count)
n = 1260 count = 0 list = [500, 100, 50, 10] for coin in list: count += n // coin n %= coin print(count)
# MEDIUM # inorder traversal using iterative # Time O(N) Space O(H) class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: return self.iterative(root,k) self.index= 1 self.result = -1 self.inOrder(root,k) return self.result def iterative(self,root,k...
class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: return self.iterative(root, k) self.index = 1 self.result = -1 self.inOrder(root, k) return self.result def iterative(self, root, k): stack = [] i = 1 while root or stack: ...
def solution(N): A, B = 0, 0 mult = 1 while N > 0: q, r = divmod(N, 10) if r == 5: A, B = A + mult * 2, B + mult * 3 elif r == 0: A, B = A + mult, B + mult * 9 q -= 1 else: A, B = A + mult, B + mult * (r - 1) mult *= 10 ...
def solution(N): (a, b) = (0, 0) mult = 1 while N > 0: (q, r) = divmod(N, 10) if r == 5: (a, b) = (A + mult * 2, B + mult * 3) elif r == 0: (a, b) = (A + mult, B + mult * 9) q -= 1 else: (a, b) = (A + mult, B + mult * (r - 1)) ...
def sum_digits(n): s=0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500...
def sum_digits(n): s = 0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_fac...
username = input("Please enter your name: ") lastLength = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailboxSize = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print( messages[-1] ) lastLength = mailboxSize message = ...
username = input('Please enter your name: ') last_length = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailbox_size = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print(messages[-1]) last_length = mailboxSize message = input('|') ...
#! /usr/bin/env python # _*_ coding:utf-8 _*_ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): if not p and not q: return True elif not p or not q: ...
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def is_same_tree(self, p, q): if not p and (not q): return True elif not p or not q: return False elif p.val != q.val:...
class disjoint_set: def __init__(self,vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def joinSets(self,otherTree): root = self.find() otherTreeRoot = otherTree.find() if root == otherTreeRoo...
class Disjoint_Set: def __init__(self, vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def join_sets(self, otherTree): root = self.find() ...
def get_test_data(): return { "contact": { "name": "Paul Kempa", "company": "Baltimore Steel Factory" }, "invoice": { "items": [ { "quantity": 12, "description": "Item description No.0", "unitprice": 12000.3, "linetotal": 20 }, ...
def get_test_data(): return {'contact': {'name': 'Paul Kempa', 'company': 'Baltimore Steel Factory'}, 'invoice': {'items': [{'quantity': 12, 'description': 'Item description No.0', 'unitprice': 12000.3, 'linetotal': 20}, {'quantity': 1290, 'description': 'Item description No.0', 'unitprice': 12.3, 'linetotal': 2000...
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self, *args, **kwargs): self.head = Node(None) def appende(self, data): node = Node(data) node.next = self.head self.head = node # Print l...
class Node: def __init__(self, data, next=None): self.data = data self.next = next class Linkedlist: def __init__(self, *args, **kwargs): self.head = node(None) def appende(self, data): node = node(data) node.next = self.head self.head = node def prin...
# # PySNMP MIB module Wellfleet-NPK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NPK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:34:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ...
def retrieveDB_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {"create": "create"} objectDb.set(data) objectDb.update({"cr...
def retrieve_db_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {'create': 'create'} objectDb.set(data) objectDb.update({'cr...
BLACK = -999 DEFAULT = 0 NORMAL = 1 PRIVATE = 10 ADMIN = 21 OWNER = 22 WHITE = 51 SUPERUSER = 999 SU = SUPERUSER
black = -999 default = 0 normal = 1 private = 10 admin = 21 owner = 22 white = 51 superuser = 999 su = SUPERUSER
################################################# Cars = [["Lamborghini", 1000000, 2, 40000], ["Ferrari", 1500000, 2.5, 50000], ["BMW", 800000, 1.5, 20000]] ################################################# print("#"*80) print("#" + "Welcome to XYZ Car Dealership".center(78) + "#") print("#"*80 + "\n") while True: ...
cars = [['Lamborghini', 1000000, 2, 40000], ['Ferrari', 1500000, 2.5, 50000], ['BMW', 800000, 1.5, 20000]] print('#' * 80) print('#' + 'Welcome to XYZ Car Dealership'.center(78) + '#') print('#' * 80 + '\n') while True: print('#' * 80) print('#' + 'What Would You Like To Do Today?'.center(78) + '#') print('...
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) ...
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) ...
white = { "Flour": "100", "Water": "65", "Oil": "4", "Salt": "2", "Yeast": "1.5" }
white = {'Flour': '100', 'Water': '65', 'Oil': '4', 'Salt': '2', 'Yeast': '1.5'}
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(s...
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(...
#!/usr/bin/env python3 def readFile(filename): #READFILE reads a file and returns its entire contents # file_contents = READFILE(filename) reads a file and returns its entire # contents in file_contents # # Load File with open(filename) as fid: file_contents = fid.read() ...
def read_file(filename): with open(filename) as fid: file_contents = fid.read() return file_contents
# values_only # Function which accepts a dictionary of key value pairs and returns a new flat list of only the values. # # Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and # returns a new list by appending the values to it. Best used on 1 level-deep key:v...
def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) return lst ages = {'Peter': 10, 'Isabel': 11, 'Anna': 9} print(values_only(ages))
# Example 1: Showing the Root Mean Squared Error (RMSE) metric. Penalises large residuals # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results ...
housing_dmatrix = xgb.DMatrix(data=X, label=y) params = {'objective': 'reg:linear', 'max_depth': 4} cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) print(cv_results) print(cv_results['test-rmse-mean'].tail(1)) housing_dmatrix = xgb.DMatrix...
# Author: Isabella Doyle # this is the menu def displayMenu(): print("What would you like to do?") print("\t(a) Add new student") print("\t(v) View students") print("\t(q) Quit") # strips any whitespace from the left/right of the string option = input("Please select an option (a/v/q): ").strip...
def display_menu(): print('What would you like to do?') print('\t(a) Add new student') print('\t(v) View students') print('\t(q) Quit') option = input('Please select an option (a/v/q): ').strip() return option def do_add(students): student_dict = {} studentDict['Name'] = input("Enter st...
def my_sum(n): return sum(list(map(int, n))) def resolve(): n, a, b = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)
def my_sum(n): return sum(list(map(int, n))) def resolve(): (n, a, b) = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)