content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
""" Utility routines for handling control file contents."""
def cfg_string_to_list(input_string):
""" Convert a string containing items separated by commas into a list."""
if "," in input_string:
output_list = input_string.split(",")
else:
output_list = [input_string]
return output_list | """ Utility routines for handling control file contents."""
def cfg_string_to_list(input_string):
""" Convert a string containing items separated by commas into a list."""
if ',' in input_string:
output_list = input_string.split(',')
else:
output_list = [input_string]
return output_list |
for j in range(1, 9):
for i in range(1,j+1):
print("%d * %d = %d" % (i,j,i*j),end="\t")
print()
| for j in range(1, 9):
for i in range(1, j + 1):
print('%d * %d = %d' % (i, j, i * j), end='\t')
print() |
# Relationship instance name
JSON_RELATIONSHIP_INTERACT_WITH = "interaction"
JSON_RUN_TIME = "runtime"
JSON_DEPLOYMENT_TIME = "deploymenttime"
JSON_NODE_DATABASE = "datastore"
JSON_NODE_SERVICE= "service"
JSON_NODE_MESSAGE_BROKER = "messagebroker"
JSON_NODE_MESSAGE_ROUTER = "messagerouter"
JSON_NODE_MESSAGE_ROUTER_KS... | json_relationship_interact_with = 'interaction'
json_run_time = 'runtime'
json_deployment_time = 'deploymenttime'
json_node_database = 'datastore'
json_node_service = 'service'
json_node_message_broker = 'messagebroker'
json_node_message_router = 'messagerouter'
json_node_message_router_kservice = 'kservice'
json_node_... |
""" Sorting algorithms """
def insert_sort(list_num):
""" Insertion sort
Start from second element
Save it alongside with it's index
Run from previous element to first one
While checking if value should be moved
In the end, put saved value after last moved index
... | """ Sorting algorithms """
def insert_sort(list_num):
""" Insertion sort
Start from second element
Save it alongside with it's index
Run from previous element to first one
While checking if value should be moved
In the end, put saved value after last moved index
"""
... |
'''
06 - Binning data
When the data on the x axis is a continuous value, it can
be useful to break it into different bins in order to get
a better visualization of the changes in the data.
For this exercise, we will look at the relationship between
tuition and the Undergraduate population abbreviated as UG in ... | """
06 - Binning data
When the data on the x axis is a continuous value, it can
be useful to break it into different bins in order to get
a better visualization of the changes in the data.
For this exercise, we will look at the relationship between
tuition and the Undergraduate population abbreviated as UG in ... |
N = int(input())
c=1
res=[]
for i in range (1,int((N+2)/2)):
if N%i == 0:
res.append(i)
c+=1
res.append(N)
print(c)
print(*res)
| n = int(input())
c = 1
res = []
for i in range(1, int((N + 2) / 2)):
if N % i == 0:
res.append(i)
c += 1
res.append(N)
print(c)
print(*res) |
# -*- coding: utf-8 -*-
"""
Disease Case Tracking and Contact Tracing
"""
module = request.controller
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
# -----------------------------------------------------------------------------
def index():
"Module's Home Page"... | """
Disease Case Tracking and Contact Tracing
"""
module = request.controller
if not settings.has_module(module):
raise http(404, body='Module disabled: %s' % module)
def index():
"""Module's Home Page"""
module_name = settings.modules[module].name_nice
response.title = module_name
return dict(... |
#program to get string which is n
word = input('Enter numbers \n')
texts = list(word)
print(f'{texts}')
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
integer = ""
for i in texts:
if i in numbers:
integer += i
print(integer)
| word = input('Enter numbers \n')
texts = list(word)
print(f'{texts}')
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
integer = ''
for i in texts:
if i in numbers:
integer += i
print(integer) |
""" Generate the information necessary to product the vrctst input files
"""
# import os
# import autofile
# import automol
# import varecof_io
# from phydat import phycon
# from autorun._run import run_script
# from autorun._run import from_input_string
#
#
# # Default names of input and output files
# INPUT_NAME = '... | """ Generate the information necessary to product the vrctst input files
""" |
#Programming I
#######################
# Mission 6.1 #
# Task List #
#######################
#Background
#==========
#After his success in the driverless vehicle, Tom
#ventures into private investigation services. To keep
#track of his progress on the cases, he like to
#create a task list dynamicall... | def generate_tasklist(num):
for i in range(1, num + 1):
if i % 7 == 1:
print('Day | Task(s)')
print(str(i) + ' | ')
else:
print(str(i) + ' | ')
generate_tasklist(num) |
pdf_path_month_hour = "C:/Users/Nyrobtseva/Documents/Python_Parser_stravenky/Month hour registration_07_2020_David_Tampier.pdf"
csv_path_month_hour = "month_hours.csv" # should be changed to smth better
pdf_path_travel_costs = "C:/Users/Nyrobtseva/Documents/Python_Parser_stravenky/cz_travelexpenses_DavidTampier_July.... | pdf_path_month_hour = 'C:/Users/Nyrobtseva/Documents/Python_Parser_stravenky/Month hour registration_07_2020_David_Tampier.pdf'
csv_path_month_hour = 'month_hours.csv'
pdf_path_travel_costs = 'C:/Users/Nyrobtseva/Documents/Python_Parser_stravenky/cz_travelexpenses_DavidTampier_July.pdf'
csv_path_travel_costs = 'travel_... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head=None
def print_llist(self):
temp = self.head
while temp:
print(temp.data)
temp=temp.next
lli... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_llist(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
llist = linked_list()
llist... |
###########################
# 6.0002 Problem Set 1b: Space Change
# Name: Ethan Fulbright
# Collaborators: Jesi Ross, Yale CS lecture - Computer Science 201a, Prof. Dana Angluin
# Time:
# Author: charz, cdenise
# ================================
# Part B: Golden Eggs
# ================================
# Problem 1
de... | def dp_make_weight(egg_weights, target_weight, memo={}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sor... |
input_repository = '/home/alog0/taeha/Spark/Count_caching/input/All_uncache_1'
count = 0
with open(input_repository, 'r', encoding='utf-8-sig') as data_file:
while True:
line = data_file.readline()
if not line:
break
line_split = line.split(':')
path = line_split[0]
num = line_split[1]
count += int(num... | input_repository = '/home/alog0/taeha/Spark/Count_caching/input/All_uncache_1'
count = 0
with open(input_repository, 'r', encoding='utf-8-sig') as data_file:
while True:
line = data_file.readline()
if not line:
break
line_split = line.split(':')
path = line_split[0]
... |
# Distribute Candy
# https://www.interviewbit.com/problems/distribute-candy/
#
# There are N children standing in a line. Each child is assigned a rating value.
#
# You are giving candies to these children subjected to the following requirements:
# Each child must have at least one candy.
# Children with a higher rati... | class Solution:
def candy(self, A):
candies = [1]
for i in range(1, len(A)):
candies.append(candies[-1] + 1 if A[i] > A[i - 1] else 1)
result = candies[-1]
for i in range(len(A) - 2, -1, -1):
curr = candies[i + 1] + 1 if A[i] > A[i + 1] else 1
res... |
# coding: utf-8
##############################################################################
# Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
#
# Subject to your compliance with these terms, you may use Microchip software
# and any derivatives exclusively with Microchip products. It is your
... | project_path = 'config/' + Variables.get('__CONFIGURATION_NAME') + '/gfx/driver/ili9488'
gfx_driver_h = comp.createFileSymbol('GFX_DRIVER_H', None)
GFX_DRIVER_H.setSourcePath('../../templates/gfx_driver.h.ftl')
GFX_DRIVER_H.setDestPath('gfx/driver/')
GFX_DRIVER_H.setOutputName('gfx_driver.h')
GFX_DRIVER_H.setProjectPat... |
class DiskQueueLength(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_disk_queue_length(idx_name)
class DiskQueueLengthColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_disks()
| class Diskqueuelength(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_disk_queue_length(idx_name)
class Diskqueuelengthcolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_disks() |
#3-1
# names = ['will', 'jess', 'jacob', 'adam']
# for name in names:
# print(name.title())
#3-2
names = ['will', 'jess', 'jacob', 'adam']
for name in names:
print(f"Hello, {name.title()}")
| names = ['will', 'jess', 'jacob', 'adam']
for name in names:
print(f'Hello, {name.title()}') |
# -*- coding: utf-8 -*-
"""Top-level package for scify."""
__author__ = """Daniel Bok"""
__email__ = 'daniel.bok@outlook.com'
__version__ = '0.1.0'
| """Top-level package for scify."""
__author__ = 'Daniel Bok'
__email__ = 'daniel.bok@outlook.com'
__version__ = '0.1.0' |
class Student:
def __init__(self):
self.name = 'Mohan'
self.age = 10
self.country = 'India'
def mydelete(self):
del self.age
myobj1 = Student()
print("Before deleting: ")
print(myobj1.__dict__)
del myobj1.country # deleting outside of the class
print("After del... | class Student:
def __init__(self):
self.name = 'Mohan'
self.age = 10
self.country = 'India'
def mydelete(self):
del self.age
myobj1 = student()
print('Before deleting: ')
print(myobj1.__dict__)
del myobj1.country
print('After deleting outside of the class: ')
print(myobj1.__dic... |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if num == 0:
raise(ValueError)
if num == 1:
return "1"
if num == 2:
return "1 1"
answer = [None, 1, 1]
i ... | def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if num == 0:
raise ValueError
if num == 1:
return '1'
if num == 2:
return '1 1'
answer = [None, 1, 1]
i = 3
... |
# Multiple Comparisons
# the way vs. the better way
# simplify chained comparison
# Manas Dash
# Raksha Bhandhan day of 2020
time_of_the_day = 6
day_of_the_week = 'mon'
# this way
if time_of_the_day < 12 and time_of_the_day > 6:
print('Good morning')
# a better way
if 6 < time_of_the_day < 12:
print('Good morning... | time_of_the_day = 6
day_of_the_week = 'mon'
if time_of_the_day < 12 and time_of_the_day > 6:
print('Good morning')
if 6 < time_of_the_day < 12:
print('Good morning')
if day_of_the_week == 'Mon' or day_of_the_week == 'Wed' or day_of_the_week == 'Fri' or (day_of_the_week == 'Sun'):
print('its just a week day'... |
"""
API Example:
from devml import stats, mkdata
path = "/Users/noah/src/wulio/checkout/"
org_df = mkdata.create_org_df(path)
author_counts = stats.author_commit_count(org_df)
"""
__version__ = "0.5.1"
| """
API Example:
from devml import stats, mkdata
path = "/Users/noah/src/wulio/checkout/"
org_df = mkdata.create_org_df(path)
author_counts = stats.author_commit_count(org_df)
"""
__version__ = '0.5.1' |
## Designing MinStack
## 1. Using Linked List
## 2. Using Arrays/Lists
class MinStack:
head = None
def __init__(self):
"""
initialize your data structure here.
"""
def push(self, x: int) -> None:
if self.head==None:
self.head = self.Node(x, x, None)
... | class Minstack:
head = None
def __init__(self):
"""
initialize your data structure here.
"""
def push(self, x: int) -> None:
if self.head == None:
self.head = self.Node(x, x, None)
else:
self.head = self.Node(x, min(self.head.min_val, x), sel... |
app.stepsPerSecond = 60
s = 5; d = Circle(200, 200, 25, fill='purple')
def onKeyHold(keys):
# Movement Control
if ('right' in keys): d.centerX += s
if ('left' in keys): d.centerX -= s
if ('up' in keys): d.centerY -= s
if ('down' in keys): d.centerY += s
# Edge Movement
if (d.left >= app.ri... | app.stepsPerSecond = 60
s = 5
d = circle(200, 200, 25, fill='purple')
def on_key_hold(keys):
if 'right' in keys:
d.centerX += s
if 'left' in keys:
d.centerX -= s
if 'up' in keys:
d.centerY -= s
if 'down' in keys:
d.centerY += s
if d.left >= app.right:
d.right... |
# Q1
def is_Empty(stack):
if stack == []:
return True
else:
return False
def pop(stack):
if is_Empty(stack):
print("Underflow")
else:
item = stack.pop()
print(item, 'is popped')
if len(stack) == 0:
top = None
else:
... | def is__empty(stack):
if stack == []:
return True
else:
return False
def pop(stack):
if is__empty(stack):
print('Underflow')
else:
item = stack.pop()
print(item, 'is popped')
if len(stack) == 0:
top = None
else:
top = len(s... |
class LinkedListNode:
def __init__(self, val):
self.val = val
self.next = None
def intersection(a, b):
nodes = set()
while a is not None:
nodes.add(a.val)
a = a.next
while b is not None:
if b.val in nodes:
return b.val
b = b.next
retur... | class Linkedlistnode:
def __init__(self, val):
self.val = val
self.next = None
def intersection(a, b):
nodes = set()
while a is not None:
nodes.add(a.val)
a = a.next
while b is not None:
if b.val in nodes:
return b.val
b = b.next
return N... |
# TODO
class A:
def __init__(self, value):
self.value = value
def __matmul__(self, other):
print('__matmul__')
return A(self.value * other.value)
def __imatmul__(self, other):
print('__imatmul__')
self.value *= other.value
return self
a = A(1)
b = A(2)
p... | class A:
def __init__(self, value):
self.value = value
def __matmul__(self, other):
print('__matmul__')
return a(self.value * other.value)
def __imatmul__(self, other):
print('__imatmul__')
self.value *= other.value
return self
a = a(1)
b = a(2)
print((a @ ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2004-2014 Alterra, Wageningen-UR
# Allard de Wit (allard.dewit@wur.nl), April 2014
"""Settings for PCSE
Default values will be read from the files 'pcse/settings/default_settings.py'
User specific settings are read from '$HOME/.pcse/user_settings.py'. Any
settings defined in use... | """Settings for PCSE
Default values will be read from the files 'pcse/settings/default_settings.py'
User specific settings are read from '$HOME/.pcse/user_settings.py'. Any
settings defined in user settings will override the default settings
Setting must be defined as ALL-CAPS and can be accessed as attributes
from p... |
__author__ = 'Tierprot'
class MutGen():
AA_voc = ["G", "A", "V", "L", "I", "P", "F", "Y", "W", "S",
"T", "C", "M", "N", "Q", "K", "R", "H", "D", "E"]
def __init__(self, input_file, vocabulary=None, positions=None):
try:
main_name, main_sequence = MutGen.load_seq(inp... | __author__ = 'Tierprot'
class Mutgen:
aa_voc = ['G', 'A', 'V', 'L', 'I', 'P', 'F', 'Y', 'W', 'S', 'T', 'C', 'M', 'N', 'Q', 'K', 'R', 'H', 'D', 'E']
def __init__(self, input_file, vocabulary=None, positions=None):
try:
(main_name, main_sequence) = MutGen.load_seq(input_file)
sel... |
for _ in range(int(input())):
k, q = map(int, input().split())
mot = sorted(list(map(int, input().split())))
sat = sorted(list(map(int, input().split())))
qs = []
for i in range(q):
qs.append(int(input()))
gen = [mot[i]+sat[j] for i in range(k) for j in range(min(k, 10001//(i+1)))]
... | for _ in range(int(input())):
(k, q) = map(int, input().split())
mot = sorted(list(map(int, input().split())))
sat = sorted(list(map(int, input().split())))
qs = []
for i in range(q):
qs.append(int(input()))
gen = [mot[i] + sat[j] for i in range(k) for j in range(min(k, 10001 // (i + 1))... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Estimation methods for the Euler Number"""
def series(n_terms=1000):
"""Estimate e with series: 1/1 + 1/1 + 1/(1*2) + 1/(1*2*3) + ..."""
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
prin... | """Estimation methods for the Euler Number"""
def series(n_terms=1000):
"""Estimate e with series: 1/1 + 1/1 + 1/(1*2) + 1/(1*2*3) + ..."""
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(sum([1 / factorial(i) for i in range(n_term... |
# This example uses python classes for addition
class Numbers(object):
def __init__(self):
self.sum = 0
def add(self,x):
# Addtion funciton
self.sum += x
def total(self):
# Returns the total of the sum
return self.sum
if __name__ == "__main__":
# Prints 12 on the terminal when t... | class Numbers(object):
def __init__(self):
self.sum = 0
def add(self, x):
self.sum += x
def total(self):
return self.sum
if __name__ == '__main__':
add = numbers()
add.add(5)
add.add(7)
y = add.total()
print('Total Sum : ', y) |
class CheckFileGenerationEnum:
GENERATED_SUCCESS = "generated_success"
GENERATED_EMPTY = "generated_empty"
NOT_GENERATED = "not_generated"
# try to find the internal value and return
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
# p... | class Checkfilegenerationenum:
generated_success = 'generated_success'
generated_empty = 'generated_empty'
not_generated = 'not_generated'
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def __setattr__(self, key, value):
raise val... |
value = '6'
if value == '7':
print('The value is 7')
elif value == '8':
print('The value is 8')
else:
print('The value is not one we are looking for')
print('Finished!')
| value = '6'
if value == '7':
print('The value is 7')
elif value == '8':
print('The value is 8')
else:
print('The value is not one we are looking for')
print('Finished!') |
def json_dates_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
return str(obj)
| def json_dates_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
return str(obj) |
#Dock download & install
def getDocker():
run('sudo apt-get update')
run('sudo apt-get install -y docker.io')
run('sudo docker pull sn1k/submodulo-alberto')
#Ejecucion de docker
def runDocker():
run('sudo docker run -p 80:80 -i -t sn1k/submodulo-alberto')
| def get_docker():
run('sudo apt-get update')
run('sudo apt-get install -y docker.io')
run('sudo docker pull sn1k/submodulo-alberto')
def run_docker():
run('sudo docker run -p 80:80 -i -t sn1k/submodulo-alberto') |
"Twilio backend for the RapidSMS project."
__version__ = '1.0.1'
| """Twilio backend for the RapidSMS project."""
__version__ = '1.0.1' |
class Trie(object):
'''The main Trie object.'''
def __init__(self, words):
'''Takes the text given and creates a Trie.'''
self.root = Node(None, '')
self.words = words
self.build(words)
def build(self, text):
'''Encapsulates all of the preprocessing build logic.'''
... | class Trie(object):
"""The main Trie object."""
def __init__(self, words):
"""Takes the text given and creates a Trie."""
self.root = node(None, '')
self.words = words
self.build(words)
def build(self, text):
"""Encapsulates all of the preprocessing build logic."""
... |
a,b=map(int,input().split())
c,d=map(int,input().split())
e,f=map(int,input().split())
if (a-c)*(d-f)==(b-d)*(c-e):
print('WHERE IS MY CHICKEN?')
else:
print('WINNER WINNER CHICKEN DINNER!') | (a, b) = map(int, input().split())
(c, d) = map(int, input().split())
(e, f) = map(int, input().split())
if (a - c) * (d - f) == (b - d) * (c - e):
print('WHERE IS MY CHICKEN?')
else:
print('WINNER WINNER CHICKEN DINNER!') |
def info():
name = input("Enter Your Name : ")
fname = input("Enter Your Father Name : ")
mname = input("Enter Your Mother Name : ")
while True:
try:
age = int(input("\033[0m Enter your age: "))
break
except Exception as e:
print("\033[31m invalid age\nplease try again ")
cont... | def info():
name = input('Enter Your Name : ')
fname = input('Enter Your Father Name : ')
mname = input('Enter Your Mother Name : ')
while True:
try:
age = int(input('\x1b[0m Enter your age: '))
break
except Exception as e:
print('\x1b[31m invalid age\... |
# Personal Greeter
# Demonstrates getting user input
name = input("Hi. What's your name? ")
print(name)
print("Hi,", name)
input("\n\nPress the enter key to exit.")
| name = input("Hi. What's your name? ")
print(name)
print('Hi,', name)
input('\n\nPress the enter key to exit.') |
def plusOne(arr):
result = int("".join([str(each) for each in arr])) + 1
result = str(result)
return list(result)
# if want = result[-1] = digits[-1] + 1:
# l = digits[-1]
# digits.pop()
# l = l + 1
# digits.append(l)
# return digits
if __name__ == "__main__":... | def plus_one(arr):
result = int(''.join([str(each) for each in arr])) + 1
result = str(result)
return list(result)
if __name__ == '__main__':
arr = [1, 2, 4, 5, 6]
print(plus_one(arr)) |
def approve_new_user(sender, instance, created, *args, **kwarg):
if created:
instance.is_staff = True
instance.is_superuser = True
instance.save()
| def approve_new_user(sender, instance, created, *args, **kwarg):
if created:
instance.is_staff = True
instance.is_superuser = True
instance.save() |
def pylist_to_listnode(self, pylist, link_count):
if len(pylist) > 1:
ret = precompiled.listnode.ListNode(pylist.pop())
ret.next = self.pylist_to_listnode(pylist, link_count)
return ret
else:
return precompiled.listnode.ListNode(pylist.pop(), None)
def XXX(self, l1: ListNode, l2... | def pylist_to_listnode(self, pylist, link_count):
if len(pylist) > 1:
ret = precompiled.listnode.ListNode(pylist.pop())
ret.next = self.pylist_to_listnode(pylist, link_count)
return ret
else:
return precompiled.listnode.ListNode(pylist.pop(), None)
def xxx(self, l1: ListNode, l2... |
def fill_tile(n):
if n == 0 or n == 1 or n == 2:
return 1
return fill_tile(n-1) + fill_tile(n-2) + fill_tile(n-3)
print(fill_tile(8))
| def fill_tile(n):
if n == 0 or n == 1 or n == 2:
return 1
return fill_tile(n - 1) + fill_tile(n - 2) + fill_tile(n - 3)
print(fill_tile(8)) |
#Following are the operators supported
# + Addition
# - Subration
# * Multiplication
# / Division
# % Modulus
# // Integer Division
# ** Exponential
#
#If any of operand is float the result is float
print(3+2) #prints 5
print(3-2) #prints 1
print(3*2) #prints 6
print(2.5+2) #Prints 4.5 (float)
#In division resu... | print(3 + 2)
print(3 - 2)
print(3 * 2)
print(2.5 + 2)
print(10 / 2)
print(5 % 2)
print(14.75 % 4)
print(3.5 ** 2)
print(3 ** 3)
print(10.5 // 2)
print(-5 // 2)
print('2' + '3')
print('abc' + str(2 + 3))
print(3 * 'Hello')
print(3 * True)
e = 2 + 3j
f = 4 - 6j
print(e + f)
print(e * f)
print(e - f) |
"""
78 Two bags of Potatoes - https://codeforces.com/problemset/problem/239/A
"""
y,k,n = map(int,input().split())
f=[]
x=k-y%k
while(x<n-y+1):
f.append(str(x))
x+=k
if len(f):
print(' '.join(f))
else:
print('-1') | """
78 Two bags of Potatoes - https://codeforces.com/problemset/problem/239/A
"""
(y, k, n) = map(int, input().split())
f = []
x = k - y % k
while x < n - y + 1:
f.append(str(x))
x += k
if len(f):
print(' '.join(f))
else:
print('-1') |
num = 0
total = 0
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
numb = float(number)
except:
print("invalid input")
continue
num = num + 1
total = total + numb
print(int(total), num, total/num)
| num = 0
total = 0
while True:
number = input('Enter a number: ')
if number == 'done':
break
try:
numb = float(number)
except:
print('invalid input')
continue
num = num + 1
total = total + numb
print(int(total), num, total / num) |
"""
Faster R-CNN with Wasserstein NMS (only train)
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.115
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.265
Average Precision (AP) @[ ... | """
Faster R-CNN with Wasserstein NMS (only train)
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.115
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.265
Average Precision (AP) @[ ... |
def migrate(cr, installed_version):
cr.execute("""
DROP TABLE IF EXISTS request_wizard_assign CASCADE;
DELETE FROM ir_model WHERE model = 'request.wizard.assign';
""")
| def migrate(cr, installed_version):
cr.execute("\n DROP TABLE IF EXISTS request_wizard_assign CASCADE;\n DELETE FROM ir_model WHERE model = 'request.wizard.assign';\n ") |
child_network_params = {
"learning_rate": 3e-5,
"max_epochs": 100,
"beta": 1e-3,
"batch_size": 20
}
controller_params = {
"max_layers": 3,
"components_per_layer": 4,
'beta': 1e-4,
'max_episodes': 2000,
"num_children_per_episode": 10
}
| child_network_params = {'learning_rate': 3e-05, 'max_epochs': 100, 'beta': 0.001, 'batch_size': 20}
controller_params = {'max_layers': 3, 'components_per_layer': 4, 'beta': 0.0001, 'max_episodes': 2000, 'num_children_per_episode': 10} |
# WAP that takes some text and returns a list of all characters
# in the text which are not vowels, sorted in alphabetical order.
# You can either enter the text from the keyboard or
# initialize a string variable with the string
# soln get the set and subtract the set from the vowels set
# text = set(input().lower()... | for i in set(input().upper()) - frozenset('AEIOU'):
print(i) |
SEED = 1
TOPIC_POKEMONS = 'pokemons'
TOPIC_USERS = 'users'
GROUP_DASHBOARD = 'dashboard'
GROUP_LOGIN_CHECKER = 'checker'
DATA = 'data/pokemon.csv'
COORDINATES = {
'GAUSS_LAT_MADRID': {'mu': 40.45, 'sigma': 0.2},
'GAUSS_LON_MADRID': {'mu': -3.60, 'sigma': 0.4},
'GAUSS_LAT_SEGOVIA': {'mu': 40.95, 'sigma': ... | seed = 1
topic_pokemons = 'pokemons'
topic_users = 'users'
group_dashboard = 'dashboard'
group_login_checker = 'checker'
data = 'data/pokemon.csv'
coordinates = {'GAUSS_LAT_MADRID': {'mu': 40.45, 'sigma': 0.2}, 'GAUSS_LON_MADRID': {'mu': -3.6, 'sigma': 0.4}, 'GAUSS_LAT_SEGOVIA': {'mu': 40.95, 'sigma': 0.1}, 'GAUSS_LON_... |
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
longest = 0
stack = []
begin = -1
for i in range(len(s)):
if '(' == s[i]:
stack.append(i)
elif ')' == s[i]:
... | class Solution(object):
def longest_valid_parentheses(self, s):
"""
:type s: str
:rtype: int
"""
longest = 0
stack = []
begin = -1
for i in range(len(s)):
if '(' == s[i]:
stack.append(i)
elif ')' == s[i]:
... |
"""
1698. Number of Distinct Substrings in a String
Medium
Given a string s, return the number of distinct substrings of s.
A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.
Example 1:
... | """
1698. Number of Distinct Substrings in a String
Medium
Given a string s, return the number of distinct substrings of s.
A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.
Example 1:
... |
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
number = int(input("Enter a number: "))
if number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif number == 0:
print("The factorial of 0 is 1")
els... | def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
number = int(input('Enter a number: '))
if number < 0:
print('Sorry, factorial does not exist for negative numbers')
elif number == 0:
print('The factorial of 0 is 1')
else:
print('The factorial of', number, 'is'... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"nothing_here": "00_core.ipynb",
"expand_hyphen": "notation.ipynb",
"del_dot": "notation.ipynb",
"del_zero": "notation.ipynb",
"get_unique": "notation.ipynb",
"exp... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'nothing_here': '00_core.ipynb', 'expand_hyphen': 'notation.ipynb', 'del_dot': 'notation.ipynb', 'del_zero': 'notation.ipynb', 'get_unique': 'notation.ipynb', 'expand_star': 'notation.ipynb', 'expand_colon': 'notation.ipynb', 'expand_regex': 'notati... |
def cumulative(list_of_numbers):
cumulative_sum = 0
new_list = []
for i in list_of_numbers:
cumulative_sum += i
new_list.append(cumulative_sum)
return new_list
list = [1,2,3,4,5,6,7,8,9]
print(cumulative(list)) | def cumulative(list_of_numbers):
cumulative_sum = 0
new_list = []
for i in list_of_numbers:
cumulative_sum += i
new_list.append(cumulative_sum)
return new_list
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(cumulative(list)) |
PACKAGES = {
"ctypes": ["0.17.1", ["ctypes.foreign"]],
"ctypes-foreign": ["0.4.0"], # WARNING: requires libffi-dev
}
opam = struct(
version = "2.0",
switches = {
"mina-0.1.0": struct(
default = True,
compiler = "4.07.1",
packages = PACKAGES
),
... | packages = {'ctypes': ['0.17.1', ['ctypes.foreign']], 'ctypes-foreign': ['0.4.0']}
opam = struct(version='2.0', switches={'mina-0.1.0': struct(default=True, compiler='4.07.1', packages=PACKAGES), '4.07.1': struct(compiler='4.07.1', packages=PACKAGES)}) |
def EIderivs(E_grid, I_grid, pars):
"""
Time derivatives for E/I variables (dE/dt, dI/dt).
"""
tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars['theta_E']
tau_I, a_I, theta_I = pars['tau_I'], pars['a_I'], pars['theta_I']
wEE, wEI = pars['wEE'], pars['wEI']
wIE, wII = pars['wIE'], pars['wII']
I... | def e_iderivs(E_grid, I_grid, pars):
"""
Time derivatives for E/I variables (dE/dt, dI/dt).
"""
(tau_e, a_e, theta_e) = (pars['tau_E'], pars['a_E'], pars['theta_E'])
(tau_i, a_i, theta_i) = (pars['tau_I'], pars['a_I'], pars['theta_I'])
(w_ee, w_ei) = (pars['wEE'], pars['wEI'])
(w_ie, w_ii) = (pa... |
labels={}
def lex(filecontents):
filecontents=list(filecontents)
tokens=[]
#Implementations left#
#Stack keywords
#Rotate
#16 bit operations
#JUMP operations
keywords=["STA","MVI","MOV","LDA","ADD","ADC","ADI","ACI","SUB","SUI","SBB","SBI","INR","DCR","CMP",
"CPI","ANA","ANI","XRA","XRI","ORA","OR... | labels = {}
def lex(filecontents):
filecontents = list(filecontents)
tokens = []
keywords = ['STA', 'MVI', 'MOV', 'LDA', 'ADD', 'ADC', 'ADI', 'ACI', 'SUB', 'SUI', 'SBB', 'SBI', 'INR', 'DCR', 'CMP', 'CPI', 'ANA', 'ANI', 'XRA', 'XRI', 'ORA', 'ORI', 'JMP', 'JNZ', 'JZ', 'JC', 'JNC']
next_state = {'STA': 1,... |
_base_ = './cascade_rcnn_r101_fpn_1x.py'
model = dict(
pretrained='open-mmlab://msra/hrnetv2_w40',
backbone=dict(
_delete_=True,
type='HRNet',
extra=dict(
stage1=dict(
num_modules=1,
num_branches=1,
block='BOTTLENECK',
... | _base_ = './cascade_rcnn_r101_fpn_1x.py'
model = dict(pretrained='open-mmlab://msra/hrnetv2_w40', backbone=dict(_delete_=True, type='HRNet', extra=dict(stage1=dict(num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4,), num_channels=(64,)), stage2=dict(num_modules=1, num_branches=2, block='BASIC', num_block... |
def collectUntil(enoughGold):
while hero.gold < enoughGold:
item = hero.findNearestItem()
if item:
hero.moveXY(item.pos.x, item.pos.y)
collectUntil(25)
hero.buildXY("decoy", 40, 52)
hero.moveXY(20, 52)
collectUntil(50)
hero.buildXY("decoy", 68, 22)
hero.buildXY("decoy", 3... | def collect_until(enoughGold):
while hero.gold < enoughGold:
item = hero.findNearestItem()
if item:
hero.moveXY(item.pos.x, item.pos.y)
collect_until(25)
hero.buildXY('decoy', 40, 52)
hero.moveXY(20, 52)
collect_until(50)
hero.buildXY('decoy', 68, 22)
hero.buildXY('decoy', 30, 20) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Do a sequence of checks on the parsed CNV data
"""
| """ Do a sequence of checks on the parsed CNV data
""" |
def howmanyfingersdoihave():
ear.pauseListening()
sleep(1)
fullspeed()
i01.moveHead(49,74)
i01.moveArm("left",75,83,79,24)
i01.moveArm("right",65,82,71,24)
i01.moveHand("left",74,140,150,157,168,92)
i01.moveHand("right",89,80,98,120,114,0)
sleep(2)
i01.moveHand("right",... | def howmanyfingersdoihave():
ear.pauseListening()
sleep(1)
fullspeed()
i01.moveHead(49, 74)
i01.moveArm('left', 75, 83, 79, 24)
i01.moveArm('right', 65, 82, 71, 24)
i01.moveHand('left', 74, 140, 150, 157, 168, 92)
i01.moveHand('right', 89, 80, 98, 120, 114, 0)
sleep(2)
i01.moveHa... |
create_favorite_query = '''
mutation {{
createFavorite (
title: "{title}",
description: "{description}",
category: "{category}",
ranking: {ranking}
) {{
message
errors
favorite {{
id
title
}}
}}
}}
'''
update_favorite_query = '''
mutation {{
updateFavorite (
id: ... | create_favorite_query = '\nmutation {{\n createFavorite (\n title: "{title}",\n description: "{description}",\n category: "{category}",\n ranking: {ranking}\n ) {{\n message\n errors\n favorite {{\n id\n title\n }}\n }}\n}}\n'
update_favorite_query = '\nmutation {{\n updateFavorite... |
# calculator
print(1+2)
print(3)
print(10%2)
print(11%2) | print(1 + 2)
print(3)
print(10 % 2)
print(11 % 2) |
# This script is used to format multiple en-ro translation datasets into the following format:
# {english sequence}{TAB character}{romanian sequence}
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# corpus
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# import xml.etree.ElementTree as ET
#
# DATASET_CORPUS = "S:\\datasets\\eng-ron_corp... | dataset_path = 'S:\\processed\\dataset_all.txt'
with open(DATASET_PATH, encoding='utf-8') as file:
for (i, line) in enumerate(file):
if line.count('\t') != 1:
raise value_error(f'Only one TAB character must be in a single line.({i + 1})') |
___assertEqual(float(False), 0.0)
___assertIsNot(float(False), False)
___assertEqual(float(True), 1.0)
___assertIsNot(float(True), True)
| ___assert_equal(float(False), 0.0)
___assert_is_not(float(False), False)
___assert_equal(float(True), 1.0)
___assert_is_not(float(True), True) |
expected_output = {
"aal5VccEntry": {"3": {}, "4": {}, "5": {}},
"aarpEntry": {"1": {}, "2": {}, "3": {}},
"adslAtucChanConfFastMaxTxRate": {},
"adslAtucChanConfFastMinTxRate": {},
"adslAtucChanConfInterleaveMaxTxRate": {},
"adslAtucChanConfInterleaveMinTxRate": {},
"adslAtucChanConfMaxInter... | expected_output = {'aal5VccEntry': {'3': {}, '4': {}, '5': {}}, 'aarpEntry': {'1': {}, '2': {}, '3': {}}, 'adslAtucChanConfFastMaxTxRate': {}, 'adslAtucChanConfFastMinTxRate': {}, 'adslAtucChanConfInterleaveMaxTxRate': {}, 'adslAtucChanConfInterleaveMinTxRate': {}, 'adslAtucChanConfMaxInterleaveDelay': {}, 'adslAtucCha... |
"""
I AM TIRED
Date: 13 March 2020
By Rowan Rathod
This is a short and easy script that just creates or overwrites a file called 'tired.txt'
and repeatedly writes the sentence "i am tired".
At each sentence, one letter is capitalised. On the next sentence, the next character is capitalised instead.
This repeats unti... | """
I AM TIRED
Date: 13 March 2020
By Rowan Rathod
This is a short and easy script that just creates or overwrites a file called 'tired.txt'
and repeatedly writes the sentence "i am tired".
At each sentence, one letter is capitalised. On the next sentence, the next character is capitalised instead.
This repeats unti... |
def default_format_volume_name(template, spawner):
return template.format(username=spawner.user.name)
def escaped_format_volume_name(label_template, spawner):
"""Use this strategy if your usernames include illegal characters
for volume names and you do not use absolute paths in your volume
label templa... | def default_format_volume_name(template, spawner):
return template.format(username=spawner.user.name)
def escaped_format_volume_name(label_template, spawner):
"""Use this strategy if your usernames include illegal characters
for volume names and you do not use absolute paths in your volume
label templa... |
class _FixDoesNotApplyError(Exception):
"""Error raised when a given fixer function does not apply to a particular case."""
pass
class _CouldNotApplyFixError(Exception):
"""Error raised when we could not apply a fix for some reason."""
pass
| class _Fixdoesnotapplyerror(Exception):
"""Error raised when a given fixer function does not apply to a particular case."""
pass
class _Couldnotapplyfixerror(Exception):
"""Error raised when we could not apply a fix for some reason."""
pass |
def int_input(msg):
inp = raw_input(msg)
try:
inp = int(inp)
if inp <= 0:
print("Please enter a non-negative number")
return int_input(msg)
else:
return inp
except:
print("Please enter a valid non-decimal number")
return int_input(msg)
def run():
global starting_hand
... | def int_input(msg):
inp = raw_input(msg)
try:
inp = int(inp)
if inp <= 0:
print('Please enter a non-negative number')
return int_input(msg)
else:
return inp
except:
print('Please enter a valid non-decimal number')
return int_input(m... |
class Solution:
# @param triangle, a list of lists of integers
# @return an integer
def minimumTotal(self, triangle):
n = len(triangle)
dp = triangle[-1]
for i in xrange(n-2, -1, -1):
for j in xrange(i+1):
dp[j] = triangle[i][j] + min(dp[j], dp[j+1])
... | class Solution:
def minimum_total(self, triangle):
n = len(triangle)
dp = triangle[-1]
for i in xrange(n - 2, -1, -1):
for j in xrange(i + 1):
dp[j] = triangle[i][j] + min(dp[j], dp[j + 1])
return dp[0] |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
return root
if node.value < root.value:
root.left = insert(root.left, node)
else:
root.right = inser... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
return root
if node.value < root.value:
root.left = insert(root.left, node)
else:
root.right = inser... |
class Solution:
# @return an integer
def reverse(self, x):
int_max = 2147483647
limit = int_max/10
if x > 0:
sig = 1
elif x < 0:
sig = -1
x = -x
else:
return x
y = 0
while x:
if y > limit:
... | class Solution:
def reverse(self, x):
int_max = 2147483647
limit = int_max / 10
if x > 0:
sig = 1
elif x < 0:
sig = -1
x = -x
else:
return x
y = 0
while x:
if y > limit:
return 0
... |
def print_headers():
headers = [
"V_energyF_Electricity_001,",
"V_Costs_Transport_USGC-NEA_NaturalGas_001,",
"V_Costs_MediumPressureSteam_001,",
"V_Costs_CoolingWater_001,",
"V_massF_BiodieselOutput_001,",
"V_Costs_Transport_SG-SC_Methanol_001,",
"V_Price_Storage_NaturalGas_001,",
"V_Price_CoolingWater_001,... | def print_headers():
headers = ['V_energyF_Electricity_001,', 'V_Costs_Transport_USGC-NEA_NaturalGas_001,', 'V_Costs_MediumPressureSteam_001,', 'V_Costs_CoolingWater_001,', 'V_massF_BiodieselOutput_001,', 'V_Costs_Transport_SG-SC_Methanol_001,', 'V_Price_Storage_NaturalGas_001,', 'V_Price_CoolingWater_001,', 'V_Pri... |
first_day = 500 #accounts deleted
pair_user = 50 #hrn
odd_user = 40 #hrn
profit = 500 #hrn
pair_users = 250 * pair_user #hrn
odd_users = 250 * odd_user #hrn
total_loss_of_deleted_users = pair_users + odd_users
total_loss = profit - total_loss_of_deleted_users
print("total loss:" ,total_loss)
| first_day = 500
pair_user = 50
odd_user = 40
profit = 500
pair_users = 250 * pair_user
odd_users = 250 * odd_user
total_loss_of_deleted_users = pair_users + odd_users
total_loss = profit - total_loss_of_deleted_users
print('total loss:', total_loss) |
"""
Some math functions.
"""
def factors(a_int):
"""Find factors of an integer."""
factors_list = []
for i in range(1, a_int):
if a_int % i == 0:
factors_list.append(i)
return factors_list
| """
Some math functions.
"""
def factors(a_int):
"""Find factors of an integer."""
factors_list = []
for i in range(1, a_int):
if a_int % i == 0:
factors_list.append(i)
return factors_list |
i = 3
shit_indicator = 0
simple_nums = [2]
while len(simple_nums) < 10001:
for k in range(2, i):
if i % k == 0:
shit_indicator = 1
break
if shit_indicator == 1:
pass
else:
simple_nums.append(i)
i += 1
shit_indicator = 0
print(simple_nums[... | i = 3
shit_indicator = 0
simple_nums = [2]
while len(simple_nums) < 10001:
for k in range(2, i):
if i % k == 0:
shit_indicator = 1
break
if shit_indicator == 1:
pass
else:
simple_nums.append(i)
i += 1
shit_indicator = 0
print(simple_nums[-1]) |
OPTIONS = {
'start': '2018-01' # start of the planning horizon
, 'num_period': 90 # size of the planning horizon
# simulation params:
, 'simulation': {
'num_resources': 15 # this depends on the number of tasks actually
, 'num_parallel_tasks': 1 # number of parallel missions
,... | options = {'start': '2018-01', 'num_period': 90, 'simulation': {'num_resources': 15, 'num_parallel_tasks': 1, 'maint_duration': 6, 'max_used_time': 1000, 'max_elapsed_time': 60, 'elapsed_time_size': 15, 'min_usage_period': 0, 'perc_capacity': 0.15, 'min_avail_percent': 0.1, 'min_avail_value': 1, 'min_hours_perc': 0.5, ... |
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
ans = collections.deque()
c = 1
for n in reversed(digits):
c, t = divmod(n + c, 10)
ans.appendleft(t)
if c > 0:
ans.appendleft(c)
return list(ans) | class Solution:
def xxx(self, digits: List[int]) -> List[int]:
ans = collections.deque()
c = 1
for n in reversed(digits):
(c, t) = divmod(n + c, 10)
ans.appendleft(t)
if c > 0:
ans.appendleft(c)
return list(ans) |
n = int(input())
values = [int(input()) for _ in range(n)]
for value in values:
msg = 'ODD '
if value % 2 == 0:
msg = 'EVEN '
if value < 0:
msg = msg + 'NEGATIVE'
elif value > 0:
msg = msg + 'POSITIVE'
else:
msg = 'NULL'
print(msg)
| n = int(input())
values = [int(input()) for _ in range(n)]
for value in values:
msg = 'ODD '
if value % 2 == 0:
msg = 'EVEN '
if value < 0:
msg = msg + 'NEGATIVE'
elif value > 0:
msg = msg + 'POSITIVE'
else:
msg = 'NULL'
print(msg) |
#
# PySNMP MIB module DOCS-SUBMGT3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-SUBMGT3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:45:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
# -*- coding: utf-8 -*-
def __setitem__(self, key, value):
"""Called to implement assignment to self[key]."""
if isinstance(value, tuple):
self._statements.__setitem__(key, value[0])
if len(tuple) >= 1:
self._comments.__setitem__(key, value[1])
else:
self._comme... | def __setitem__(self, key, value):
"""Called to implement assignment to self[key]."""
if isinstance(value, tuple):
self._statements.__setitem__(key, value[0])
if len(tuple) >= 1:
self._comments.__setitem__(key, value[1])
else:
self._comments.__setitem__(key, None)... |
def number_of_tweets_per_day(df):
"""This function takes a pandas dataframe of twitter data and returns the number of tweets
per day on a given day.
Example
----------
Input: twitter_df
Tweets Date
@BongaDlulane Please send an... | def number_of_tweets_per_day(df):
"""This function takes a pandas dataframe of twitter data and returns the number of tweets
per day on a given day.
Example
----------
Input: twitter_df
Tweets Date
@BongaDlulane Please send an ... |
'''
Kattis - beatspread
Very easy math problem.
Time: O(1), Space: O(1)
'''
num_tc = int(input())
for i in range(num_tc):
a, b = map(int, input().split())
l = (a+b)//2
s = (a-b)//2
if (a+b)%2 == 1 or s < 0:
print(f"impossible")
else:
print(f"{l} {s}") | """
Kattis - beatspread
Very easy math problem.
Time: O(1), Space: O(1)
"""
num_tc = int(input())
for i in range(num_tc):
(a, b) = map(int, input().split())
l = (a + b) // 2
s = (a - b) // 2
if (a + b) % 2 == 1 or s < 0:
print(f'impossible')
else:
print(f'{l} {s}') |
class Node:
'''each node represents a different dog or cat object
They each have a name, a type (cat or dog), and a
reference to the next animal in the shelter queue
'''
def __init__(self, animal_type, next_node=None):
self.animal_type = animal_type
self.next = next_node
class Inva... | class Node:
"""each node represents a different dog or cat object
They each have a name, a type (cat or dog), and a
reference to the next animal in the shelter queue
"""
def __init__(self, animal_type, next_node=None):
self.animal_type = animal_type
self.next = next_node
class Inva... |
target_x = range(211, 233)
target_y = range(-124, -68)
# part 1 and 2
x_hits = []
infinite_x_hits = []
for vx in range(1, target_x.stop):
pos = 0
i = 0
while pos < target_x.stop and vx > i:
pos += vx - i
i += 1
if pos in target_x:
x_hits.append((vx, i))
if vx == i a... | target_x = range(211, 233)
target_y = range(-124, -68)
x_hits = []
infinite_x_hits = []
for vx in range(1, target_x.stop):
pos = 0
i = 0
while pos < target_x.stop and vx > i:
pos += vx - i
i += 1
if pos in target_x:
x_hits.append((vx, i))
if vx == i and pos in target_... |
n = 0
factor = 20
while True:
n = n + factor
is_divisible = True
for i in range(1, factor + 1):
if n % i != 0:
is_divisible = False
break
if (is_divisible):
break
print(n)
| n = 0
factor = 20
while True:
n = n + factor
is_divisible = True
for i in range(1, factor + 1):
if n % i != 0:
is_divisible = False
break
if is_divisible:
break
print(n) |
line = input().split(" ")
n = int(line[0]) # nodes
m = int(line[1]) # edges
graph = {}
def find_lowest_cost_node(costs, processed):
lowest_cost_node = None
lowest_cost = float("inf")
for node, cost in costs.items():
if cost < lowest_cost and node not in processed:
lowest_cost_node = ... | line = input().split(' ')
n = int(line[0])
m = int(line[1])
graph = {}
def find_lowest_cost_node(costs, processed):
lowest_cost_node = None
lowest_cost = float('inf')
for (node, cost) in costs.items():
if cost < lowest_cost and node not in processed:
lowest_cost_node = node
... |
class Solution:
# @param {string} s
# @return {integer}
def lengthOfLongestSubstring(self, s):
n = len(s)
if n <=1:
return n
start = 0
max_count = 1
c_dict = {s[0]:0}
for p in range(1,n):
sub = s[start:p]
c = s[p]
... | class Solution:
def length_of_longest_substring(self, s):
n = len(s)
if n <= 1:
return n
start = 0
max_count = 1
c_dict = {s[0]: 0}
for p in range(1, n):
sub = s[start:p]
c = s[p]
if c in sub:
start = c_... |
broj = -1
while broj != 0:
print("Trenutni broj je " + str(broj))
broj = int(intpu("Unesite novi broj: "))
print("Kraj")
| broj = -1
while broj != 0:
print('Trenutni broj je ' + str(broj))
broj = int(intpu('Unesite novi broj: '))
print('Kraj') |
name="Ashwin"
def student():
print("Name",name) #accessing in def also
student()
if name[0]=="A": #accessing in global
print("Starts from A")
x = 300
def myfunc():
global x
x = 200
print(x)
myfunc()
print(x) | name = 'Ashwin'
def student():
print('Name', name)
student()
if name[0] == 'A':
print('Starts from A')
x = 300
def myfunc():
global x
x = 200
print(x)
myfunc()
print(x) |
# GENERATED VERSION FILE
# TIME: Fri Sep 11 18:59:53 2020
__version__ = '0.3.0+038435e'
short_version = '0.3.0'
| __version__ = '0.3.0+038435e'
short_version = '0.3.0' |
""" Data types for RAIL File Input/Output """
#from rail.core.data import DataFile
#class TextFile(DataFile):
# """
# A data file in plain text format.
# """
# suffix = "txt"
# format = "http://edamontology.org/format_2330"
#@classmethod
#def read(cls, path):
#@classmethod
#def writ... | """ Data types for RAIL File Input/Output """ |
def quick_sort(nums: list) -> list:
if len(nums) <= 1:
return nums
mid = nums[0]
return quick_sort([i for i in nums if i < mid]) + [mid] + quick_sort([i for i in nums if i > mid])
| def quick_sort(nums: list) -> list:
if len(nums) <= 1:
return nums
mid = nums[0]
return quick_sort([i for i in nums if i < mid]) + [mid] + quick_sort([i for i in nums if i > mid]) |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.jwt_validation_request
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class JwtValidationRequest(object):
"""Implementation of the 'JwtValidationRequest' model.
Jwt validation request
... | """
idfy_rest_client.models.jwt_validation_request
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Jwtvalidationrequest(object):
"""Implementation of the 'JwtValidationRequest' model.
Jwt validation request
Attributes:
jwt (string): The J... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.