content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Zoo:
def __init__(self, name, budget, animal_capacity, workers_capacity):
self.__budget = budget
self.__animal_capacity = animal_capacity
self.__workers_capacity = workers_capacity
self.name = name
self.animals = []
self.workers = []
def add_animal(self, an... | class Zoo:
def __init__(self, name, budget, animal_capacity, workers_capacity):
self.__budget = budget
self.__animal_capacity = animal_capacity
self.__workers_capacity = workers_capacity
self.name = name
self.animals = []
self.workers = []
def add_animal(self, a... |
def arrMul(lst):
out = [None] * len(lst)
prod = 1
i = 0
while i < len(lst):
out [i] = prod
prod *= lst[i]
i += 1
print ("First Four Pass",out)
prod = 1
i = len(lst) - 1
while i >= 0:
out[i] *= prod
prod *= lst[i]
i -= 1
... | def arr_mul(lst):
out = [None] * len(lst)
prod = 1
i = 0
while i < len(lst):
out[i] = prod
prod *= lst[i]
i += 1
print('First Four Pass', out)
prod = 1
i = len(lst) - 1
while i >= 0:
out[i] *= prod
prod *= lst[i]
i -= 1
return out
print... |
#
# PySNMP MIB module TUBS-IBR-PROC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TUBS-IBR-PROC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:52 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')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
class GRPCConfiguration:
def __init__(self, client_side: bool, server_string=None, user_agent=None,
message_encoding=None, message_accept_encoding=None,
max_message_length=33554432):
self._client_side = client_side
if client_side and server_string is not None:
... | class Grpcconfiguration:
def __init__(self, client_side: bool, server_string=None, user_agent=None, message_encoding=None, message_accept_encoding=None, max_message_length=33554432):
self._client_side = client_side
if client_side and server_string is not None:
raise value_error('Passed ... |
#string method
name ="Emanuele Micheletti"
print(len(name))
print(name.find("B")) # -1 if not found, index otherwise
print(name.capitalize())
print(name.upper())
print(name.lower())
print(name.isdigit()) #false if contains alpha char, True only if all chars are numeric
print(name.isalpha()) #space is not alpha
print... | name = 'Emanuele Micheletti'
print(len(name))
print(name.find('B'))
print(name.capitalize())
print(name.upper())
print(name.lower())
print(name.isdigit())
print(name.isalpha())
print(name.count('e'))
print(name.replace('e', 'a'))
print(name * 3) |
"""
Module: 'websocket' on esp32_LoBo
MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32')
Stubber: 1.0.0
"""
class websocket:
''
def close():
pass
def ioctl():
pass
def read():
pass
... | """
Module: 'websocket' on esp32_LoBo
MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32')
Stubber: 1.0.0
"""
class Websocket:
""""""
def close():
pass
def ioctl():
pass
def read():
... |
# Definition for singly-linked list.
class _ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: _ListNode, val: int) -> _ListNode:
prev = None
curr = head
while curr is not None:
if c... | class _Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_elements(self, head: _ListNode, val: int) -> _ListNode:
prev = None
curr = head
while curr is not None:
if curr.val == val:
if ... |
class PlayFabBaseObject():
pass
class PlayFabRequestCommon(PlayFabBaseObject):
"""
This is a base-class for all Api-request objects.
It is currently unfinished, but we will add result-specific properties,
and add template where-conditions to make some code easier to follow
"""
pass
class P... | class Playfabbaseobject:
pass
class Playfabrequestcommon(PlayFabBaseObject):
"""
This is a base-class for all Api-request objects.
It is currently unfinished, but we will add result-specific properties,
and add template where-conditions to make some code easier to follow
"""
pass
class Pla... |
ENVFileTemplate="""
#!/usr/bin/env bash
# https://github.com/toggl/toggl_api_docs
export TOGGL_API_TOKEN=''
# Sometimes you have a billable rate and a non-billable rate.
export BILLABLE_RATE='10.0'
export NON_BILLABLE_RATE='5.0'
export FULFILLMENT_DELAY='30'
# Make sure to iterate the invoice number with each use
ex... | env_file_template = "\n#!/usr/bin/env bash\n\n# https://github.com/toggl/toggl_api_docs\nexport TOGGL_API_TOKEN=''\n\n# Sometimes you have a billable rate and a non-billable rate.\nexport BILLABLE_RATE='10.0'\nexport NON_BILLABLE_RATE='5.0'\nexport FULFILLMENT_DELAY='30'\n\n# Make sure to iterate the invoice number wit... |
"""Repeating elements: All elements appear exactly once except one element, we have to find that element.
Also all elements from 0 to max of the array are present at least once in the array. Eg: [0, 2, 1, 3, 2, 2] O/P: 2"""
""" Solution: """
def repeating_element(a) -> int:
n = len(a)
for i in range(n):
... | """Repeating elements: All elements appear exactly once except one element, we have to find that element.
Also all elements from 0 to max of the array are present at least once in the array. Eg: [0, 2, 1, 3, 2, 2] O/P: 2"""
' Solution: '
def repeating_element(a) -> int:
n = len(a)
for i in range(n):
... |
# https://practice.geeksforgeeks.org/problems/distribute-n-candies/1#
# try to distribute as many candies as possible in a complete round
# when a candies required in a turn are more than left, then
# find out the last person to get full turn candy
# give remaining to next and return the array
class Solution:
... | class Solution:
def ap_sum(self, a, d, n):
return int(n * (2 * a + (n - 1) * d) / 2)
def distribute_candies(self, N, K):
rem = N
full_rounds = 0
while rem > 0:
this_round = self.apSum(1 + K * full_rounds, 1, K)
if this_round > rem:
break
... |
num = int(input('Digite algum numero: '))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f'Analisando numero {num}')
if u > 0:
print(f'Unidade: {u}')
if d > 0:
print(f'Dezena: {d}')
if c > 0:
print(f'Centena: {c}')
if m > 0:
print(f'Milhar: {m}')
| num = int(input('Digite algum numero: '))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f'Analisando numero {num}')
if u > 0:
print(f'Unidade: {u}')
if d > 0:
print(f'Dezena: {d}')
if c > 0:
print(f'Centena: {c}')
if m > 0:
print(f'Milhar: {m}') |
"""Defines a repository rule for configuring the helm executable.
"""
def _impl(repository_ctx):
substitutions = {"%{TOOL_ATTRS}": " target_tool = \"%s\"\n" % repository_ctx.attr.target_tool}
repository_ctx.template(
"BUILD",
Label("@ltd_fox_hound_rules_helm//toolchains/helm:BUILD.tpl"),
... | """Defines a repository rule for configuring the helm executable.
"""
def _impl(repository_ctx):
substitutions = {'%{TOOL_ATTRS}': ' target_tool = "%s"\n' % repository_ctx.attr.target_tool}
repository_ctx.template('BUILD', label('@ltd_fox_hound_rules_helm//toolchains/helm:BUILD.tpl'), substitutions, False)
... |
class Solution:
def ipToCIDR(self, ip, n):
"""
:type ip: str
:type n: int
:rtype: List[str]
"""
def iptoint(ip):
nums = list(map(int, ip.split('.')))
return sum(num << (32 - (i + 1) * 8) for i, num in enumerate(nums))
def inttoip(num):
... | class Solution:
def ip_to_cidr(self, ip, n):
"""
:type ip: str
:type n: int
:rtype: List[str]
"""
def iptoint(ip):
nums = list(map(int, ip.split('.')))
return sum((num << 32 - (i + 1) * 8 for (i, num) in enumerate(nums)))
def inttoip... |
"""
Author: shikechen
Function: def FileTool class
Version: 6.0
Date: 2019/2/8
"""
class PasswordTool:
def __init__(self, password):
self.password = password
self.strength_level = 0
def process_password(self):
# Rule 1: length >= 8
if len(self.password) >= 8:
... | """
Author: shikechen
Function: def FileTool class
Version: 6.0
Date: 2019/2/8
"""
class Passwordtool:
def __init__(self, password):
self.password = password
self.strength_level = 0
def process_password(self):
if len(self.password) >= 8:
self.strength_level... |
# Pandigital products
def check_pandigital_product(x, y):
if ''.join(sorted(str(x*y)+str(x)+str(y))) == '123456789':
return True
return False
pandig_products = []
for x in range(int(10), int(1e4)):
for y in range(int(10), int(1e4)):
if len(str(x)+str(y)+str(x*y)) != 9:
... | def check_pandigital_product(x, y):
if ''.join(sorted(str(x * y) + str(x) + str(y))) == '123456789':
return True
return False
pandig_products = []
for x in range(int(10), int(10000.0)):
for y in range(int(10), int(10000.0)):
if len(str(x) + str(y) + str(x * y)) != 9:
continue
... |
######################################################################
# Author: Thy H. Nguyen TODO: Change this to your names
# Username: nguyent2 TODO: Change this to your usernames
#
# Assignment: A09: Caesar Cipher
#
# Purpose: The class imports a file, encrypts the file, and exports the ciph... | class Caesarcipher:
"""
A class to encrypt and decrypt
"""
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def __init__(self, input_file='message_input.txt', key=0, crypt_type='encrypt'):
"""
A constructor for the CaesarCipher class
:param input_file: The file to be encrypted/decryp... |
# -*- coding: utf-8 -*-
class Guild:
def __init__(self, data=None):
self.id: str = ""
self.name: str = ""
self.icon: str = ""
self.owner_id: str = ""
self.owner: bool = False
self.member_count: int = 0
self.max_members: int = 0
self.description: str ... | class Guild:
def __init__(self, data=None):
self.id: str = ''
self.name: str = ''
self.icon: str = ''
self.owner_id: str = ''
self.owner: bool = False
self.member_count: int = 0
self.max_members: int = 0
self.description: str = ''
self.joined_... |
"""
Given a data stream input of non-negative integers a1, a2, ..., an, ...,
summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ...,
then the summary will be:
1 [1, 1]
3 [1, 1], [3, 3]
7 [1, 1], [3, 3],... | """
Given a data stream input of non-negative integers a1, a2, ..., an, ...,
summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ...,
then the summary will be:
1 [1, 1]
3 [1, 1], [3, 3]
7 [1, 1], [3, 3],... |
class PiRGBArray:
def __init__(self, *args, **kwargs):
self.array = None
def truncate(self, _):
pass
class PiYUVArray:
def __init__(self, *args, **kwargs):
self.array = None
| class Pirgbarray:
def __init__(self, *args, **kwargs):
self.array = None
def truncate(self, _):
pass
class Piyuvarray:
def __init__(self, *args, **kwargs):
self.array = None |
class Course:
def __init__(self,name,ratings):
self.name=name
self.ratings=ratings
def average(self):
numberOfRatings= len(self.ratings)
average = sum(self.ratings)/numberOfRatings
print("Average Ratings For ",self.name," Is ",average)
c1 = Course... | class Course:
def __init__(self, name, ratings):
self.name = name
self.ratings = ratings
def average(self):
number_of_ratings = len(self.ratings)
average = sum(self.ratings) / numberOfRatings
print('Average Ratings For ', self.name, ' Is ', average)
c1 = course('Java Co... |
class SubClass1:
pass
class SubClass2:
pass
async def async_function() -> None:
return
| class Subclass1:
pass
class Subclass2:
pass
async def async_function() -> None:
return |
GOOGLE_MAP_API_KEY = 'AIzaSyA2b8Zh0rzAJQjwDn0_CZ_tHdPXm6G2Sjs'
FIREBASE_FCM_API_KEY = 'AIzaSyAYd8wWQYEJFBzdLJgSGaa1fpJO0OT4APA'
| google_map_api_key = 'AIzaSyA2b8Zh0rzAJQjwDn0_CZ_tHdPXm6G2Sjs'
firebase_fcm_api_key = 'AIzaSyAYd8wWQYEJFBzdLJgSGaa1fpJO0OT4APA' |
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(std):
print('%s: %s' % (std.name, std.score))
#print(std.name,std.score)
def get_grade(self):
if self.score >= 90:
retur... | class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(std):
print('%s: %s' % (std.name, std.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
... |
List1=[]
user=int(input())
for i in range(user):
List1.append(int(input()))
n=len(List1)
for k in range(n-1):
for j in range(n-1-k):
if List1[j]>List1[j+1]:
List1[j],List1[j+1]=List1[j+1],List1[j]
for i in List1:
print(i)
| list1 = []
user = int(input())
for i in range(user):
List1.append(int(input()))
n = len(List1)
for k in range(n - 1):
for j in range(n - 1 - k):
if List1[j] > List1[j + 1]:
(List1[j], List1[j + 1]) = (List1[j + 1], List1[j])
for i in List1:
print(i) |
class Solution(object):
# dp - Bottom up, O(n) space
def climbStairs_On(self, n):
"""
:type n: int
:rtype: int
"""
ls = [0]*(n+1)
if n == 0:
return 1
if n == 1:
return 1
ls[0] = ls[1] = 1
for i ... | class Solution(object):
def climb_stairs__on(self, n):
"""
:type n: int
:rtype: int
"""
ls = [0] * (n + 1)
if n == 0:
return 1
if n == 1:
return 1
ls[0] = ls[1] = 1
for i in range(2, len(ls)):
ls[i] = ls[i -... |
# Part of the Crubit project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
# Create a loader/trampoline repository that we can call into to... | load('@bazel_tools//tools/build_defs/repo:git.bzl', 'new_git_repository')
def _llvm_loader_repository(repository_ctx):
repository_ctx.file('BUILD')
if 'PREBUILT_LLVM_PATH' in repository_ctx.os.environ:
path = repository_ctx.os.environ['PREBUILT_LLVM_PATH']
if not path.startswith('/'):
... |
#Fizz Buzz Algorithm
def fizzBuzz(input):
if (input % 3 == 0) and (input % 5 == 0):
return "FizzBuzz"
elif input % 3 == 0:
return "Fizz"
elif input % 5 == 0:
return "Buzz"
return input
data = int(input("Enter any number :"))
print(fizzBuzz(data)) | def fizz_buzz(input):
if input % 3 == 0 and input % 5 == 0:
return 'FizzBuzz'
elif input % 3 == 0:
return 'Fizz'
elif input % 5 == 0:
return 'Buzz'
return input
data = int(input('Enter any number :'))
print(fizz_buzz(data)) |
def power(base , pow):
answer = 1
for index in range(pow):
answer = answer * base
return answer
print(power(2 , 14)) | def power(base, pow):
answer = 1
for index in range(pow):
answer = answer * base
return answer
print(power(2, 14)) |
# Only 4xx errors information will be returned currently
# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors
MSG = "msg"
# 400x
BAD_REQUEST_4000 = 4000
INVALID_INPUT_4001 = 4001
INVALID_INPUT_4001_MSG = "Invalid inputs."
WRONG_CREDENTIALS_4002 = 4002
WRONG_CREDENTIALS_4002_MSG = "Incorrect us... | msg = 'msg'
bad_request_4000 = 4000
invalid_input_4001 = 4001
invalid_input_4001_msg = 'Invalid inputs.'
wrong_credentials_4002 = 4002
wrong_credentials_4002_msg = 'Incorrect username(email) or password or both.'
not_found_4040 = 4040
user_not_found_4041 = 4041
user_inactive_4042 = 4042
user_inactive_4042_msg = 'The cu... |
class Solution(object):
def coinChangeIter(self, coins, amount):
sum = 0
dp = [0 for i in range(amount+1)]
for i in range(1, amount+1):
min = -1
for coin in coins:
if i-coin >= 0 and dp[i-coin] != -1:
if min < 0 or dp[i-coin] +1 < ... | class Solution(object):
def coin_change_iter(self, coins, amount):
sum = 0
dp = [0 for i in range(amount + 1)]
for i in range(1, amount + 1):
min = -1
for coin in coins:
if i - coin >= 0 and dp[i - coin] != -1:
if min < 0 or dp[i -... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 22:43:50 2019
@author: ZWH
"""
| """
Created on Mon Dec 2 22:43:50 2019
@author: ZWH
""" |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
def func():
print('first')
print('second')
return 3
print('third')
func() | def func():
print('first')
print('second')
return 3
print('third')
func() |
def add_(a,b):
return a+b
def sub_(a,b):
return a-b | def add_(a, b):
return a + b
def sub_(a, b):
return a - b |
class Solution(object):
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
try:
if '.' in IP:
# IPv4
strs = IP.split('.')
if len(strs) == 4:
for s in strs:
if ... | class Solution(object):
def valid_ip_address(self, IP):
"""
:type IP: str
:rtype: str
"""
try:
if '.' in IP:
strs = IP.split('.')
if len(strs) == 4:
for s in strs:
if not s or (len(s) > 1... |
"""
Ejercicio 2. Escribir un script que nos muestre por pantalla todos los numeros pares del 1 al 120
"""
contador = 1
for contador in range(1,121):
if contador%2 == 0:
print(f"es par {contador}")
"""
else:
print(f"{contador} es impar")
"""
| """
Ejercicio 2. Escribir un script que nos muestre por pantalla todos los numeros pares del 1 al 120
"""
contador = 1
for contador in range(1, 121):
if contador % 2 == 0:
print(f'es par {contador}')
'\n else:\n print(f"{contador} es impar")\n ' |
'''Initialize biosql db '''
#biodb_conn_string = 'sqlite://biodb.sqlite'
# biodb_conn_string = 'mysql://root:@127.0.0.1/mybiodb'
#biodb_conn_string = 'postgres://mybiodb:mypass@127.0.0.1/mybiodb'
# timestamps_db = 'sqlite://biodb.sqlite'
biodb_handler = BioSQLHandler(settings.biodb_conn_string, compatibility_mode = Fal... | """Initialize biosql db """
biodb_handler = bio_sql_handler(settings.biodb_conn_string, compatibility_mode=False, time_stamps=settings.timestamps_db, pool_size=5)
biodb = biodb_handler.adaptor
if biodb_handler._build_error:
response.flash = 'DB model building error'
'Initial configuration data '
biodatabases = [row... |
user_range = input("Type a range (star and end): ").split()
for u in range(0, len(user_range)):
user_range[u] = int(user_range[u])
even_sum = 0
for i in range(user_range[0], user_range[1]):
if i % 2 == 0:
even_sum += i
print("The total even add is: {:d}".format(even_sum))
| user_range = input('Type a range (star and end): ').split()
for u in range(0, len(user_range)):
user_range[u] = int(user_range[u])
even_sum = 0
for i in range(user_range[0], user_range[1]):
if i % 2 == 0:
even_sum += i
print('The total even add is: {:d}'.format(even_sum)) |
# Solution
# O(nd) time / O(n) space
# n - target amount
# d - number of denominations
def numberOfWaysToMakeChange(n, denoms):
ways = [0 for amount in range(n + 1)]
ways[0] = 1
for denom in denoms:
for amount in range(1, n + 1):
if denom <= amount:
ways[amount] += ways[... | def number_of_ways_to_make_change(n, denoms):
ways = [0 for amount in range(n + 1)]
ways[0] = 1
for denom in denoms:
for amount in range(1, n + 1):
if denom <= amount:
ways[amount] += ways[amount - denom]
return ways[n] |
print(" Week 1 - Day-2 ")
print("--------------------")
print(" v = 6" + " AND "+ "c = 5")
print("--------------------")
v = 6
c = 5
if v < c:
print(" c big than v")
else:
print(" c small than v")
input('Press ENTER to continue...')
| print(' Week 1 - Day-2 ')
print('--------------------')
print(' v = 6' + ' AND ' + 'c = 5')
print('--------------------')
v = 6
c = 5
if v < c:
print(' c big than v')
else:
print(' c small than v')
input('Press ENTER to continue...') |
# A simple graph representing a series of cities and the connections between
# them.
map = {
"Seattle": {"San Francisco"},
"San Francisco": {"Seattle", "Los Angeles", "Denver"},
"Los Angeles": {"San Francisco", "Phoenix"},
"Phoenix": {"Los Angeles", "Denver"},
"Denver": {"Phoenix", "San Francisco",... | map = {'Seattle': {'San Francisco'}, 'San Francisco': {'Seattle', 'Los Angeles', 'Denver'}, 'Los Angeles': {'San Francisco', 'Phoenix'}, 'Phoenix': {'Los Angeles', 'Denver'}, 'Denver': {'Phoenix', 'San Francisco', 'Houston', 'Kansas City'}, 'Kansas City': {'Denver', 'Houston', 'Chicago', 'Nashville'}, 'Houston': {'Kans... |
RECEIVED_REQUEST = 'RT'
REQUEST_SUCCESS = 'TS'
REQUEST_FAILED = 'TF'
REQUEST_PROCESSING = 'SP'
NETWORK_ISSUE = 'NC'
CONFIRMING_REQUEST = 'SC'
UNIONBANK_RESPONSE_CODES = {
RECEIVED_REQUEST: {
'message': 'Received Transaction Request',
'apis': 'all',
'description': 'Transaction has reached U... | received_request = 'RT'
request_success = 'TS'
request_failed = 'TF'
request_processing = 'SP'
network_issue = 'NC'
confirming_request = 'SC'
unionbank_response_codes = {RECEIVED_REQUEST: {'message': 'Received Transaction Request', 'apis': 'all', 'description': 'Transaction has reached UnionBank'}, REQUEST_SUCCESS: {'m... |
# Write your check_for_name function here:
def check_for_name(sentence, name) -> object:
return name.lower() in sentence.lower()
# Uncomment these function calls to test your function:
print(check_for_name("My name is Jamie", "Jamie"))
# should print True
print(check_for_name("My name is jamie", "Jamie"))
# ... | def check_for_name(sentence, name) -> object:
return name.lower() in sentence.lower()
print(check_for_name('My name is Jamie', 'Jamie'))
print(check_for_name('My name is jamie', 'Jamie'))
print(check_for_name('My name is Samantha', 'Jamie')) |
# loops with range
for x in range(0, 10, 1):
pass # insert what to do in each iteration
# 0 represents the value to start iterating with
# 10 represents the value to stop iterating at
# 1 represents the value in which the iterator changes per iteration
for x in range(0, 10, 1):
pass # start iteration at 0, end... | for x in range(0, 10, 1):
pass
for x in range(0, 10, 1):
pass
for x in range(0, 10):
pass
for x in range(10):
pass
for x in range(0, 10, 2):
print(x)
for x in range(5, 1, -3):
print(x)
my_list = ['abc', 123, 'xyz']
for i in range(0, len(my_list)):
print(i, my_list[i])
for v in my_list:
p... |
# sum = sum + 10
# sum += 10
# i = i + 1
# i += 1
# number = number / 10
# number /= 10
# number = number / divisor
# number /= divisor
# product = product * 45
# product *= 45
# factroial = factorial * func(3)
# factorial *= func(3)
"""
var = var [operator] value
var [operator]= value
"""
| """
var = var [operator] value
var [operator]= value
""" |
inputText = "{{{{{{<!>!>,<o!>},<a,\"i!!!>i!!,!>,<<e<i<<>,{{{<!>},<!><!>,<!!!>!!!>!!!>{\"!>},<!!!<!>},<oi!>!,'>}}}},{{<{!!!>},<!!,!!!>!!!>!!e!a!!!!<!>},<!!!>u!>,<!>!!u!!!!!>},<!>!>,<{>}},{<\"a!!!!'!>},<!}\"!>!!<o}i!<>,<<e,<eo!a}!!\"!>,<!>!>!>,<e{\"e\">}},{{<!oi'<!o!>ue>,{<!>},<i!>,<i>,{<'>}}}},{{<\"a,!>},<!!e!>,<e!!}!!o... | input_text = '{{{{{{<!>!>,<o!>},<a,"i!!!>i!!,!>,<<e<i<<>,{{{<!>},<!><!>,<!!!>!!!>!!!>{"!>},<!!!<!>},<oi!>!,\'>}}}},{{<{!!!>},<!!,!!!>!!!>!!e!a!!!!<!>},<!!!>u!>,<!>!!u!!!!!>},<!>!>,<{>}},{<"a!!!!\'!>},<!}"!>!!<o}i!<>,<<e,<eo!a}!!"!>,<!>!>!>,<e{"e">}},{{<!oi\'<!o!>ue>,{<!>},<i!>,<i>,{<\'>}}}},{{<"a,!>},<!!e!>,<e!!}!!o!!!... |
bedroom_choices = {
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10
}
price_choices = {
'100000': 'KES100,000',
'200000': 'KES200,000',
'300000': 'KES300,000',
'400000': 'KES400,000',
'500000': 'KES500,000',
'600000': 'KES... | bedroom_choices = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10}
price_choices = {'100000': 'KES100,000', '200000': 'KES200,000', '300000': 'KES300,000', '400000': 'KES400,000', '500000': 'KES500,000', '600000': 'KES600,000', '700000': 'KES700,000', '800000': 'KES800,000', '900000': ... |
with open("./Day_Three/input.txt") as File:
input = File.read().strip().split("\n")
class Main():
def __init__(self, input):
self.input = input
def partOne(input: str) -> int:
finalArr = [ {0:0, 1:0} for _ in range(len(input[0]))]
for row in input:
for i, v i... | with open('./Day_Three/input.txt') as file:
input = File.read().strip().split('\n')
class Main:
def __init__(self, input):
self.input = input
def part_one(input: str) -> int:
final_arr = [{0: 0, 1: 0} for _ in range(len(input[0]))]
for row in input:
for (i, v) in enume... |
#########################################################
# Author: Zach, Dave and Feroz Farazi (msff2@cam.ac.uk) #
# Date: 24 Nov 2020 #
#########################################################
"""This module defines SPARQL queries"""
def get_lucode_label():
"""Sets the curre... | """This module defines SPARQL queries"""
def get_lucode_label():
"""Sets the current SPARQL query"""
query = '\n Prefix ns1:<http://www.theworldavatar.com/kb/ontocropenergy/> \n Prefix ns2: <http://www.theworldavatar.com/ontology/ontocropenergy/OntoCropEnergy.owl#> \n Prefix ns... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 13:43:05 2020
@author: Tushar Saxena
"""
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class Tree:
def __init__(self):
self.root = None
def getRoot... | """
Created on Tue Jan 14 13:43:05 2020
@author: Tushar Saxena
"""
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class Tree:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def add(self, val... |
# Single Number
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
# Example 1:
# Input: [2,2,1]
# Output: 1
# Example 2:
# Input: [4,1,2,1,2]
# Ou... | def single_number(nums):
seen = []
for i in nums:
if i in seen:
seen.remove(i)
else:
seen.append(i)
return seen[0]
if __name__ == '__main__':
nums = list(map(int, input().split(',')))
r = single_number(nums)
print(r) |
n = int(input())
cod = []
tmp = False
for i in range(n):
cod.append(input())
for i in range(n):
for j in list(set(cod) - set(cod[i])):
for k in list(set(cod) - set([cod[i],j])):
if k in cod[i] + j or k in j + cod[i]:
print(k)
tmp = True
break
if tmp:
break
if tmp:
break
if not tmp:
print('ok... | n = int(input())
cod = []
tmp = False
for i in range(n):
cod.append(input())
for i in range(n):
for j in list(set(cod) - set(cod[i])):
for k in list(set(cod) - set([cod[i], j])):
if k in cod[i] + j or k in j + cod[i]:
print(k)
tmp = True
break
... |
# Leo colorizer control file for splus mode.
# This file is in the public domain.
# Properties for splus mode.
properties = {
"doubleBracketIndent": "false",
"indentCloseBrackets": "}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)",
"indentOpenBr... | properties = {'doubleBracketIndent': 'false', 'indentCloseBrackets': '}', 'indentNextLine': '\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)', 'indentOpenBrackets': '{', 'lineComment': '#', 'lineUpClosingBracket': 'true', 'wordBreakChars': '_,+-=<>/?^&*'}
splus_main_attributes_dict = {'defaul... |
class Solution(object):
def generateParenthesis(self, N):
if N == 0: return ['']
ans = []
for c in range(N):
for left in self.generateParenthesis(c):
for right in self.generateParenthesis(N-1-c):
ans.append('({}){}'.format(left, right))
... | class Solution(object):
def generate_parenthesis(self, N):
if N == 0:
return ['']
ans = []
for c in range(N):
for left in self.generateParenthesis(c):
for right in self.generateParenthesis(N - 1 - c):
ans.append('({}){}'.format(lef... |
###########################################################
# Fixed parameters for speech recognition
###########################################################
# Model and feature type
model_type = 'Wav2Letter' # DeepSpeech or Wav2Letter
feature_type = 'mfcc' # rawspeech (Wav2Letter), rawframes (DeepSpeech), spectro... | model_type = 'Wav2Letter'
feature_type = 'mfcc'
sample_rate = 16000
window_size = 0.02
window_stride = 0.01
window = 'hamming'
noise_dir = None
noise_prob = 0.4
noise_min = 0.0
noise_max = 0.5
labels_path = './labels.json'
train_manifest = './manifest_files_cm/libri_train_clean_360_manifest.csv'
val_manifest = './manif... |
# --------------
# Code starts here
class_1=[]
class_2=[]
class_1.append('Geoffrey Hinton')
class_1.append('Andrew Ng')
class_1.append('Sebastian Raschka')
class_1.append('Yoshua Bengio')
class_2.append('Hilary Mason')
class_2.append('Carla Gentry')
class_2.append('Corinna Cortes')
new_class=class_1 + class_2
print(ne... | class_1 = []
class_2 = []
class_1.append('Geoffrey Hinton')
class_1.append('Andrew Ng')
class_1.append('Sebastian Raschka')
class_1.append('Yoshua Bengio')
class_2.append('Hilary Mason')
class_2.append('Carla Gentry')
class_2.append('Corinna Cortes')
new_class = class_1 + class_2
print(new_class)
new_class.append('Pete... |
class ChannelBirthday:
def __init__(self, channel_id, server_id):
self.channel_id = channel_id
self.server_id = server_id
def __eq__(self, other):
return self.server_id == other.server_id
| class Channelbirthday:
def __init__(self, channel_id, server_id):
self.channel_id = channel_id
self.server_id = server_id
def __eq__(self, other):
return self.server_id == other.server_id |
# pylint: disable=R0903
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------... | class Wafscenariomixin(object):
profile = None
def current_subscription(self):
subs = self.cmd('az account show').get_output_in_json()
return subs['id'] |
class Trie:
def __init__(self, name, isendofword = False ):
self.name = name
self.isendofword = isendofword
self.elements = dict()
def __repr__(self):
return str(
{
'name' : self.name,
'isendiftheword' : self.isendofword,
... | class Trie:
def __init__(self, name, isendofword=False):
self.name = name
self.isendofword = isendofword
self.elements = dict()
def __repr__(self):
return str({'name': self.name, 'isendiftheword': self.isendofword, 'elements': self.elements.keys()})
def search(trie, name):
... |
N = int(input()[-1])
if N in [2, 4, 5, 7, 9]:
print("hon")
elif N in [0, 1, 6, 8]:
print("pon")
else:
print("bon")
| n = int(input()[-1])
if N in [2, 4, 5, 7, 9]:
print('hon')
elif N in [0, 1, 6, 8]:
print('pon')
else:
print('bon') |
""" Messenger class file """
class Messenger:
""" Class that represents a messenger object (interface) """
def send(self, user_id: str, text: str):
""" Sends to the user_id (backend must understand) the text message"""
raise NotImplementedError("Abstract method MUST be implemented")
def ... | """ Messenger class file """
class Messenger:
""" Class that represents a messenger object (interface) """
def send(self, user_id: str, text: str):
""" Sends to the user_id (backend must understand) the text message"""
raise not_implemented_error('Abstract method MUST be implemented')
def... |
# https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
if __name__ == '__main__':
a = int(input())
b = int(input())
c = int(input())
d = int(input())
caculation = pow(a,b) + pow(c,d)
print(caculation)
| if __name__ == '__main__':
a = int(input())
b = int(input())
c = int(input())
d = int(input())
caculation = pow(a, b) + pow(c, d)
print(caculation) |
class Movie():
""" This Class provides a way to store movie related information
Such as title, storyline, poster image url, and trailer.
To create and instance of the Movie class, import media into
your python file then create an instance by:
variable = media.Movie(movie_title, ... | class Movie:
""" This Class provides a way to store movie related information
Such as title, storyline, poster image url, and trailer.
To create and instance of the Movie class, import media into
your python file then create an instance by:
variable = media.Movie(movie_title, movie_s... |
# Union-Find with path compression and union with rank
class UF:
def __init__(self, n):
self.count = [1] * n
self.parent = [_ for _ in range(n)]
def find(self, i): # find root(i) and compress the path
if self.parent[i] != i:
self.parent[i] = self.find(self.parent[i])
... | class Uf:
def __init__(self, n):
self.count = [1] * n
self.parent = [_ for _ in range(n)]
def find(self, i):
if self.parent[i] != i:
self.parent[i] = self.find(self.parent[i])
return self.parent[i]
def union(self, i, j):
(pi, pj) = (self.find(i), self.f... |
# Author: BHARATHI KANNAN N - Github: https://github.com/bharathikannann, linkedin: https://linkedin.com/in/bharathikannann
#
# ## Doubly Linked List
# - A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains three fields: two link fields... | class Node(object):
def __init__(self, data, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class Doublylinkedlist(object):
def __init__(self):
self.head = None
def insert_at_first(self, data):
new_node = node(data)
if self.head ... |
class ApplicationException(Exception):
...
class NoteExists(ApplicationException):
...
class InputError(ApplicationException):
...
class ActionAborted(ApplicationException):
...
class PathIsNotDefined(ApplicationException):
def __init__(self):
super().__init__(
"Path to n... | class Applicationexception(Exception):
...
class Noteexists(ApplicationException):
...
class Inputerror(ApplicationException):
...
class Actionaborted(ApplicationException):
...
class Pathisnotdefined(ApplicationException):
def __init__(self):
super().__init__('Path to notes is not defi... |
___assertEqual(len('123'), 3)
___assertEqual(len(()), 0)
___assertEqual(len((1, 2, 3, 4)), 4)
___assertEqual(len([1, 2, 3, 4]), 4)
___assertEqual(len({}), 0)
___assertEqual(len({'a':1, 'b': 2}), 2)
| ___assert_equal(len('123'), 3)
___assert_equal(len(()), 0)
___assert_equal(len((1, 2, 3, 4)), 4)
___assert_equal(len([1, 2, 3, 4]), 4)
___assert_equal(len({}), 0)
___assert_equal(len({'a': 1, 'b': 2}), 2) |
#1. Create a greeting for your program.
print('welocme to brand name generator')
#2. Ask the user for the city that they grew up in.
city_name = input('enter your city name')
print('city name is '+city_name)
#3. Ask the user for the name of a pet.
pet_name = input('enter your pet name')
print('pet name is ' + pet_name)... | print('welocme to brand name generator')
city_name = input('enter your city name')
print('city name is ' + city_name)
pet_name = input('enter your pet name')
print('pet name is ' + pet_name)
print('my best recomodate :- ' + city_name + pet_name) |
#Validate credit cards using Luhn's algorithm. Input should be 16 digits.
def luhn():
card_number=input("Enter the card number to be checked: ")
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd = digits[-1::-2]
even = digits[-2::-2]
checksum... | def luhn():
card_number = input('Enter the card number to be checked: ')
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd = digits[-1::-2]
even = digits[-2::-2]
checksum = 0
checksum += sum(odd)
for d in even:
checksum += sum(digits_o... |
# E[0] = sum(Vi/N)
# E[k] = sum(max(Vi, E[k-1])/N)
def expectation(N, K, V, mean):
# # Recursion form fails
# if K == 0: return mean
# e = expectation(N, K-1, V, mean)
# return sum(max(v, e)/N for v in V)
ek = mean
for k in range(K):
ek = sum(max(v, ek)/N for v in V)
return ek
def... | def expectation(N, K, V, mean):
ek = mean
for k in range(K):
ek = sum((max(v, ek) / N for v in V))
return ek
def solve(N, K, V):
mean = sum(V) / N
return expectation_faster(N, K, sorted(V), mean)
def expectation_faster(N, K, V, mean):
ek = mean
for k in range(K):
x = binary... |
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
"""Hash table.
"""
res = 0
d = {0: -1}
c = 0
for i, n in enumerate(nums):
if n == 1:
c -= 1
else:
c += 1
if c in d:
res... | class Solution:
def find_max_length(self, nums: List[int]) -> int:
"""Hash table.
"""
res = 0
d = {0: -1}
c = 0
for (i, n) in enumerate(nums):
if n == 1:
c -= 1
else:
c += 1
if c in d:
... |
class Msg:
SERVER_BANNER = '''
##### # ###### ####### ##### # # # ##### ####### ###### # # ####### ######
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # ... | class Msg:
server_banner = '\n ##### # ###### ####### ##### # # # ##### ####### ###### # # ####### ###### \n# # # # # # # # # # # # # # # # # # # # # # # \n# # # # # # # # # # # # #... |
sample_request = {
'id': '91b20aa5-9ccf-498d-8944-5d3a32ab1b37',
'timestamp': '2018-02-17T11:26:58.76Z',
'lang': 'en',
'result': {
'source': 'agent',
'resolvedQuery': 'hello',
'speech': '',
'action': 'hello',
'actionIncomplete': False,
'parameters': {
... | sample_request = {'id': '91b20aa5-9ccf-498d-8944-5d3a32ab1b37', 'timestamp': '2018-02-17T11:26:58.76Z', 'lang': 'en', 'result': {'source': 'agent', 'resolvedQuery': 'hello', 'speech': '', 'action': 'hello', 'actionIncomplete': False, 'parameters': {}, 'contexts': [], 'metadata': {'intentId': '6e4d06c7-bdd0-4e44-b130-a1... |
n = int(input())
A = [0] + [int(i) for i in input().split()]
def maxHeapify(i):
left = 2 * i
right = 2 * i + 1
if left <= n and A[left] > A[i]:
largest = left
else:
largest = i
if right <= n and A[right] > A[largest]:
largest = right
if largest != i:
A[i], A[l... | n = int(input())
a = [0] + [int(i) for i in input().split()]
def max_heapify(i):
left = 2 * i
right = 2 * i + 1
if left <= n and A[left] > A[i]:
largest = left
else:
largest = i
if right <= n and A[right] > A[largest]:
largest = right
if largest != i:
(A[i], A[la... |
class SkString:
def __init__(self, text):
self.text = text
def to_upper(self):
return self.text.upper()
def to_lower(self):
return self.text.lower()
def to_title(self):
return self.text.title() | class Skstring:
def __init__(self, text):
self.text = text
def to_upper(self):
return self.text.upper()
def to_lower(self):
return self.text.lower()
def to_title(self):
return self.text.title() |
class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
# write your code here
l1 = list(s)
l2 = list(t)
length1 = len(l1)
length2 = len(l2)
if length1 != length2:
r... | class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
l1 = list(s)
l2 = list(t)
length1 = len(l1)
length2 = len(l2)
if length1 != length2:
return False
else:
... |
"""Exceptions for versionner"""
class VersionnerError(Exception):
"""Generic versionne error"""
ret_code = 2
class ConfigError(VersionnerError):
"""Configuration error"""
| """Exceptions for versionner"""
class Versionnererror(Exception):
"""Generic versionne error"""
ret_code = 2
class Configerror(VersionnerError):
"""Configuration error""" |
"""Parser classes for SIMBAD"""
__author__ = "Felix Simkovic"
__date__ = "04 May 2017"
__version__ = "0.1"
class _Parser(object):
def __init__(self, fname):
self.logfile = fname
| """Parser classes for SIMBAD"""
__author__ = 'Felix Simkovic'
__date__ = '04 May 2017'
__version__ = '0.1'
class _Parser(object):
def __init__(self, fname):
self.logfile = fname |
def read_file(file_name):
data = ""
with open(file_name, "r") as file:
data = file.read()
return data
def parse_input(text):
lines = text.split("\n")
return lines
def part1():
lines = parse_input(read_file("day4_input.txt"))
good_passphrases = 0
for line in lines:
wor... | def read_file(file_name):
data = ''
with open(file_name, 'r') as file:
data = file.read()
return data
def parse_input(text):
lines = text.split('\n')
return lines
def part1():
lines = parse_input(read_file('day4_input.txt'))
good_passphrases = 0
for line in lines:
words... |
#This script will read 3 numbers "n", "x" and "y" and print a validation for each number in the range 1:n of whether the number is divisible by x, divisible by y or divisible by both.
def xyMultiple(n,x,y):
for i in range(1,n+1):
isDivX = False
isDivY = False
res = "Div by "
if i % x... | def xy_multiple(n, x, y):
for i in range(1, n + 1):
is_div_x = False
is_div_y = False
res = 'Div by '
if i % x == 0:
is_div_x = True
res += str(x)
if i % y == 0:
is_div_y = True
res += str(y)
if isDivX or isDivY:
... |
# -*- coding: utf-8 -*-
def salpeter(m, ksi0=1.0):
return ksi0 * m ** -2.35
| def salpeter(m, ksi0=1.0):
return ksi0 * m ** (-2.35) |
class nmap_plugin():
# user-defined
script_id = 'http-methods'
script_source = 'service'
script_types = ['port_info']
script_obj = None
output = ''
def __init__(self, script_object):
self.script_obj = script_object
self.output = script_object['output']
def port_info(se... | class Nmap_Plugin:
script_id = 'http-methods'
script_source = 'service'
script_types = ['port_info']
script_obj = None
output = ''
def __init__(self, script_object):
self.script_obj = script_object
self.output = script_object['output']
def port_info(self):
"""
... |
"""
Errors about messages.
"""
class SendMessageFailed(Exception):
"""Raises when sending a message is failed."""
pass
class CreateReactionFailed(Exception):
"""Raises when creating the reaction is failed."""
pass
class DeleteReactionFailed(Exception):
"""Raises when deleting the reaction is... | """
Errors about messages.
"""
class Sendmessagefailed(Exception):
"""Raises when sending a message is failed."""
pass
class Createreactionfailed(Exception):
"""Raises when creating the reaction is failed."""
pass
class Deletereactionfailed(Exception):
"""Raises when deleting the reaction is fail... |
sysconfig = dict(
experiment = 'Exp',
)
devices = dict(
Sample = device('nicos.devices.sample.Sample',
description = 'The currently used sample',
),
Exp = device('nicos.devices.experiment.Experiment',
description = 'experiment object',
dataroot = 'data',
sendmail = True,... | sysconfig = dict(experiment='Exp')
devices = dict(Sample=device('nicos.devices.sample.Sample', description='The currently used sample'), Exp=device('nicos.devices.experiment.Experiment', description='experiment object', dataroot='data', sendmail=True, serviceexp='p0', sample='Sample')) |
def order_square(a):
right = 0
while right < len(a) and a[right] < 0:
right +=1
left = right-1
output = []
while left >= 0 and right < len(a):
if a[left]**2 < a[right]**2:
output.append(a[left]**2)
left -=1
else:
output.append(a[... | def order_square(a):
right = 0
while right < len(a) and a[right] < 0:
right += 1
left = right - 1
output = []
while left >= 0 and right < len(a):
if a[left] ** 2 < a[right] ** 2:
output.append(a[left] ** 2)
left -= 1
else:
output.append(a[r... |
#
# PySNMP MIB module GENOSALARMNOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENOSALARMNOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def test_case_mme_update(populated_database, case_obj, user_obj, mme_patient, mme_submission):
""" Test the function that registers an effected individual as submitted to MatchMaker """
adapter = populated_database
mme_submission['server_responses'] = [ {'patient': mme_patient }]
# Make sure no c... | def test_case_mme_update(populated_database, case_obj, user_obj, mme_patient, mme_submission):
""" Test the function that registers an effected individual as submitted to MatchMaker """
adapter = populated_database
mme_submission['server_responses'] = [{'patient': mme_patient}]
assert adapter.case_colle... |
def array123(arr):
myarr = [1,2,3]
for i in range(len(arr)):
if arr[i: (i+3)] == myarr:
return True
return False
result = array123([1, 1, 2, 3, 1])
print(result)
result = array123([1, 1, 2, 4, 1])
print(result)
result = array123([1, 1, 2, 1, 2, 3])
print(result) | def array123(arr):
myarr = [1, 2, 3]
for i in range(len(arr)):
if arr[i:i + 3] == myarr:
return True
return False
result = array123([1, 1, 2, 3, 1])
print(result)
result = array123([1, 1, 2, 4, 1])
print(result)
result = array123([1, 1, 2, 1, 2, 3])
print(result) |
def getListInFile(fileName):
'''
DOCSTRING : Gets and reads a file in args
INPUT : name of file to open
OUTPUT : return list of colours
'''
with open(fileName, mode='r') as cFile:
listOfColours = cFile.readlines()
return listOfColours
cFile.close() | def get_list_in_file(fileName):
"""
DOCSTRING : Gets and reads a file in args
INPUT : name of file to open
OUTPUT : return list of colours
"""
with open(fileName, mode='r') as c_file:
list_of_colours = cFile.readlines()
return listOfColours
cFile.close() |
class DictAsObject(dict):
def __getattr__(self, name):
return self.__getitem__(name)
def __getitem__(self, name):
value = dict.__getitem__(self, name)
if isinstance(value, dict) and not isinstance(value, DictAsObject):
value = DictAsObject(value)
dict.__setitem__(self, name, value)
ret... | class Dictasobject(dict):
def __getattr__(self, name):
return self.__getitem__(name)
def __getitem__(self, name):
value = dict.__getitem__(self, name)
if isinstance(value, dict) and (not isinstance(value, DictAsObject)):
value = dict_as_object(value)
dict.__seti... |
def find_median(Arr, start, size):
myList = []
for i in range(start, start + size):
myList.append(Arr[i])
myList.sort()
return myList[size // 2]
def fastSelect(array, k):
n = len(array)
if 0 < k <= n:
setOfMedians = []
arr_less_P = []
arr_equal_P = []
... | def find_median(Arr, start, size):
my_list = []
for i in range(start, start + size):
myList.append(Arr[i])
myList.sort()
return myList[size // 2]
def fast_select(array, k):
n = len(array)
if 0 < k <= n:
set_of_medians = []
arr_less_p = []
arr_equal_p = []
... |
def BiRNN(x, weights, biases):
lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype=tf.float32)
return tf.matmul(outputs[-1], weights['out']) + biases['out'] | def bi_rnn(x, weights, biases):
lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype=tf.float32)
return tf.matmul(outputs[-1], weights['out']) + biases['out'] |
# https://app.codesignal.com/arcade/code-arcade/mirror-lake/rNrF4v5etMdFNKD3s
def isSubstitutionCipher(string1, string2):
# Is one string able to be made with a substitution cipher?
# We don't know what it is, but we can start comparing both
# and inferring what a candidate substitution may be. Then,
# ... | def is_substitution_cipher(string1, string2):
cipher = {}
used = {}
for i in range(len(string1)):
(char1, char2) = (string1[i], string2[i])
if not char1 in cipher:
if char2 in used:
return False
cipher[char1] = char2
used[char2] = 1
... |
STACK_COUNT = 6
INITIAL_STACK_SIZE = 6
MAX_STACK_SIZE = 15
STACK_RANGE = range(STACK_COUNT)
class GameState:
def __init__(self):
self.actions_taken = 0
# List of lists of tuples
# Finished stacks become None - won state contains 4 Nones and 2 empty lists
self.stacks = []
... | stack_count = 6
initial_stack_size = 6
max_stack_size = 15
stack_range = range(STACK_COUNT)
class Gamestate:
def __init__(self):
self.actions_taken = 0
self.stacks = []
self.cheats = []
for i in STACK_RANGE:
self.stacks.append([])
self.cheats.append(False)
... |
class humano:
def __init__(self, nombre, armadura, nivel, ataque, ojos=2, piernas=2, dientes=32,salud=100):
self.ojos=ojos
self.piernas=piernas
self.dientes=dientes
self.nombre=nombre
self.armadura=armadura
self.nivel=nivel
self.ataque=ataque
self.salu... | class Humano:
def __init__(self, nombre, armadura, nivel, ataque, ojos=2, piernas=2, dientes=32, salud=100):
self.ojos = ojos
self.piernas = piernas
self.dientes = dientes
self.nombre = nombre
self.armadura = armadura
self.nivel = nivel
self.ataque = ataque
... |
for _ in range(int(input())):
c = [int(n) for n in input()]
i_t = (c[3] ^ c[4] ^ c[5] ^ c[6]) << 2 | (c[1] ^ c[2] ^ c[5] ^ c[6]) << 1 | (c[0] ^ c[2] ^ c[4] ^ c[6])
if i_t: c[i_t - 1] ^= 1
print(''.join(map(str, [c[2], c[4], c[5], c[6]])))
| for _ in range(int(input())):
c = [int(n) for n in input()]
i_t = (c[3] ^ c[4] ^ c[5] ^ c[6]) << 2 | (c[1] ^ c[2] ^ c[5] ^ c[6]) << 1 | c[0] ^ c[2] ^ c[4] ^ c[6]
if i_t:
c[i_t - 1] ^= 1
print(''.join(map(str, [c[2], c[4], c[5], c[6]]))) |
#################################### User part start ##################################
""" GUI Color Theme. Set True for light mode, Valid values True, False """
DARK_THEME = False
""" Units for time expenses. Valid values are 'seconds', minutes', 'hours' """
UNITS = 'minutes'
""" Time to process a single word """... | """ GUI Color Theme. Set True for light mode, Valid values True, False """
dark_theme = False
" Units for time expenses. Valid values are 'seconds', minutes', 'hours' "
units = 'minutes'
' Time to process a single word '
word = 0.1
' Time to process a single table '
table = 25
' Time to process a single image/screensh... |
class Config:
batch_size = 100
n_epochs = 50
init_lr = 1e-2 # this would not take effect as using cyclic lr
momentum = 0.0
weight_decay = 5e-4
eta_min = 1e-5
eta_max = 1e-2
shuffle = False
part_labeled = 0.3 # the percentage of labeled data
n_features = 39
n_classes = 48
... | class Config:
batch_size = 100
n_epochs = 50
init_lr = 0.01
momentum = 0.0
weight_decay = 0.0005
eta_min = 1e-05
eta_max = 0.01
shuffle = False
part_labeled = 0.3
n_features = 39
n_classes = 48
n_hidden_nodes = n_classes * 2
temp = 1
teacher_tar_fmt = 'teacher_plb... |
# TO DO
# Move constants/codes to new file
class Tokenizer:
"""
Advances through raw Jack code, ignores irrelevant characters, separates tokens, and identifies token types.
"""
KEYWORD = 0
IDENTIFIER = 1
SYMBOL = 2
INT_CONSTANT = 3
STRING_CONSTANT = 4
SYMBOLS = r"{}()[].,;+-*/&|... | class Tokenizer:
"""
Advances through raw Jack code, ignores irrelevant characters, separates tokens, and identifies token types.
"""
keyword = 0
identifier = 1
symbol = 2
int_constant = 3
string_constant = 4
symbols = '{}()[].,;+-*/&|<>=~'
keywords = ['class', 'constructor', 'fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.