content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
You can use the reverse(N, A) procedure defined in today's easy problem [20120611A] to completely sort a list. For
instance, if we wanted to sort the list [2,5,4,3,1], you could execute the following series of reversals:
A = [2, 5, 4, 3, 1]
reverse(2, A) (A = [5, 2, 4, 3, 1])
reverse(5, A) (A = [1, 3,... | """
You can use the reverse(N, A) procedure defined in today's easy problem [20120611A] to completely sort a list. For
instance, if we wanted to sort the list [2,5,4,3,1], you could execute the following series of reversals:
A = [2, 5, 4, 3, 1]
reverse(2, A) (A = [5, 2, 4, 3, 1])
reverse(5, A) (A = [1, 3,... |
while True:
D,N = input().split()
if D == N == '0': break
N = N.replace(D,'')
print(0) if N == '' else print(int(N))
| while True:
(d, n) = input().split()
if D == N == '0':
break
n = N.replace(D, '')
print(0) if N == '' else print(int(N)) |
def factorial(n):
if n == 0: # base case
return 1
else: # divide and conquer
return n * factorial(n - 1) # call the same function passing in an argument that leads down to the base case
for n in range(0, 12):
print(factorial(n))
| def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
for n in range(0, 12):
print(factorial(n)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Event():
pass
class MarketEvent(Event):
def __init__(self, product, sym, last_bar):
self.type = 'MARKET'
self.product = product
self.sym = sym
self.last_bar = last_bar # dict
class RefreshEvent(Event):
def __init__(self)... | class Event:
pass
class Marketevent(Event):
def __init__(self, product, sym, last_bar):
self.type = 'MARKET'
self.product = product
self.sym = sym
self.last_bar = last_bar
class Refreshevent(Event):
def __init__(self):
self.type = 'REFRESHED'
class Signalevent(Ev... |
HELM_BUILD_FILE = """
package(default_visibility = ["//visibility:public"])
exports_files( ["helm"] )
"""
def _helm3_repository_impl(repository_ctx):
os_arch = repository_ctx.attr.os_arch
os_name = repository_ctx.os.name.lower()
if os_name.startswith("mac os"):
os_arch = "darwin-amd64"
else:
... | helm_build_file = '\npackage(default_visibility = ["//visibility:public"])\nexports_files( ["helm"] )\n'
def _helm3_repository_impl(repository_ctx):
os_arch = repository_ctx.attr.os_arch
os_name = repository_ctx.os.name.lower()
if os_name.startswith('mac os'):
os_arch = 'darwin-amd64'
else:
... |
class RevStr(str):
def __iter__(self):
return ItRevStr(self)
class ItRevStr:
def __init__(self, chaine_a_parcourir):
self.chaine_a_parcourir=chaine_a_parcourir
self.position=len(self.chaine_a_parcourir)
def __next__(self):
if self.position==0:
raise StopIteration
self.position-=1
return self.chaine... | class Revstr(str):
def __iter__(self):
return it_rev_str(self)
class Itrevstr:
def __init__(self, chaine_a_parcourir):
self.chaine_a_parcourir = chaine_a_parcourir
self.position = len(self.chaine_a_parcourir)
def __next__(self):
if self.position == 0:
raise St... |
img_properties = 'width="14" height="12" alt=""'
valid_letters = 'YNLUKGFPBDTCIHS8EM'
emoticons = {
"(:-)" : "emoticon-smile.gif",
"(;-)" : "emoticon-wink.gif",
"(:-()" : "emoticon-sad.gif",
"(:-|)" : "emoticon-ambivalent.gif",
"(:-D)" : "emoticon-laugh.gif",
"(:-O)" : "emoticon-surprised.gif",
... | img_properties = 'width="14" height="12" alt=""'
valid_letters = 'YNLUKGFPBDTCIHS8EM'
emoticons = {'(:-)': 'emoticon-smile.gif', '(;-)': 'emoticon-wink.gif', '(:-()': 'emoticon-sad.gif', '(:-|)': 'emoticon-ambivalent.gif', '(:-D)': 'emoticon-laugh.gif', '(:-O)': 'emoticon-surprised.gif', '(:-P)': 'emoticon-tongue-in-ch... |
gamestr = "Icewind Dale EE 2.6.5.0 + BetterHOF + CDTWEAKS"
headers = ["Area", "NPC", "XP", "Gold Carried", "Pickpocket Skill", "Item Price (base)", "Item Type", "Item"]
areas = [
"animtest (Spawned)",
"ar1001 - Easthaven (prologue) - Temple of Tempus",
"ar1008 - Easthaven (prologue) - Snowdrift Inn",
"ar1100 - Eas... | gamestr = 'Icewind Dale EE 2.6.5.0 + BetterHOF + CDTWEAKS'
headers = ['Area', 'NPC', 'XP', 'Gold Carried', 'Pickpocket Skill', 'Item Price (base)', 'Item Type', 'Item']
areas = ['animtest (Spawned)', 'ar1001 - Easthaven (prologue) - Temple of Tempus', 'ar1008 - Easthaven (prologue) - Snowdrift Inn', 'ar1100 - Easthaven... |
'''
a = 'iasdsdasda'
b= 0
c = len(a)
while b<c:
print(a[b])
b+=1
import random
a = random.randrange(1,3)
s = eval(raw_input(">>"))
while a-s!=0:
if a>s:
print("you are low")
elif a<s:
print("you are high")
s = eval(raw_input(">>"))
while a-s==0:
print("you are right")
break
'''... | """
a = 'iasdsdasda'
b= 0
c = len(a)
while b<c:
print(a[b])
b+=1
import random
a = random.randrange(1,3)
s = eval(raw_input(">>"))
while a-s!=0:
if a>s:
print("you are low")
elif a<s:
print("you are high")
s = eval(raw_input(">>"))
while a-s==0:
print("you are right")
break
"""... |
# I got to use a map dictionary (identical values) in one place as it is
# but in another I should convert keys as values and values as keys!
# Note
'''
+ This is only for dictionary which has identical values and when considered as hashmap.
- If dictionary which has duplicate values may not work well.
- If dictionar... | """
+ This is only for dictionary which has identical values and when considered as hashmap.
- If dictionary which has duplicate values may not work well.
- If dictionary which has collection as values may also not work.
"""
hashmap = {'BlankValidationError': 'BVE01', 'InvalidFormatError': 'IFE01', 'InvalidTypeError': ... |
#Internal framework imports
#Typing imports
class ResizeMethod:
NONE = 1
CROP = 2
STRETCH = 3
LETTERBOX = 4
@classmethod
def str2enum(cls, resize_method_string, error_if_none = False):
resize_method_string = resize_method_string.lower()
if resize_method_string == "crop":
... | class Resizemethod:
none = 1
crop = 2
stretch = 3
letterbox = 4
@classmethod
def str2enum(cls, resize_method_string, error_if_none=False):
resize_method_string = resize_method_string.lower()
if resize_method_string == 'crop':
return cls.CROP
elif resize_metho... |
def add(*args):
return list(list(sum(j) for j in zip(*rows)) for rows in zip(*args))
matrix1 = [[1, -2], [-3, 4]]
matrix2 = [[2, -1], [0, -1]]
result = add(matrix1, matrix2)
print(result) | def add(*args):
return list((list((sum(j) for j in zip(*rows))) for rows in zip(*args)))
matrix1 = [[1, -2], [-3, 4]]
matrix2 = [[2, -1], [0, -1]]
result = add(matrix1, matrix2)
print(result) |
class ConfigNotFoundException(Exception):
def __init__(self, message):
super().__init__(message)
class WorkingDirectoryDoesNotExistException(Exception):
def __init__(self, message):
super().__init__(message)
class ImageUploaderException(Exception):
def __init__(self, message):
su... | class Confignotfoundexception(Exception):
def __init__(self, message):
super().__init__(message)
class Workingdirectorydoesnotexistexception(Exception):
def __init__(self, message):
super().__init__(message)
class Imageuploaderexception(Exception):
def __init__(self, message):
s... |
text = '''<?xml version="1.0" encoding="utf-8" ?>
<body copyright="All data copyright San Francisco Muni 2015.">
<predictions agencyTitle="San Francisco Muni" routeTitle="38-Geary" routeTag="38" stopTitle="43rd Ave & Point Lobos Ave" stopTag="13568">
<direction title="Inbound to Downtown">
<prediction epochTim... | text = '<?xml version="1.0" encoding="utf-8" ?> \n<body copyright="All data copyright San Francisco Muni 2015.">\n<predictions agencyTitle="San Francisco Muni" routeTitle="38-Geary" routeTag="38" stopTitle="43rd Ave & Point Lobos Ave" stopTag="13568">\n <direction title="Inbound to Downtown">\n <prediction epochT... |
colour = {'r': '\033[31m', 'g': '\033[32m', 'w': '\033[33m', 'b': '\033[34m', 'p': '\033[35m',
'c': '\033[36m', 'limit': '\033[m'}
def line(n=37):
print('-' * n)
def title(txt, x=37):
print('-' * x)
print(f'{colour["c"]}{txt.center(x)}{colour["limit"]}')
print('-' * x) | colour = {'r': '\x1b[31m', 'g': '\x1b[32m', 'w': '\x1b[33m', 'b': '\x1b[34m', 'p': '\x1b[35m', 'c': '\x1b[36m', 'limit': '\x1b[m'}
def line(n=37):
print('-' * n)
def title(txt, x=37):
print('-' * x)
print(f"{colour['c']}{txt.center(x)}{colour['limit']}")
print('-' * x) |
class widget_type(object):
stage = 0
button = 1
toggle = 2
slider = 3
dropdown = 4
text = 5
input_field = 6
joystick = 7
class widget_date_type(object):
bool = 0
int32 = 1
float = 2
string = 3
class widget_public_function(object):
create = 0
destory = 1
ac... | class Widget_Type(object):
stage = 0
button = 1
toggle = 2
slider = 3
dropdown = 4
text = 5
input_field = 6
joystick = 7
class Widget_Date_Type(object):
bool = 0
int32 = 1
float = 2
string = 3
class Widget_Public_Function(object):
create = 0
destory = 1
acti... |
f = open('task1-test-input.txt')
o = open('o1.txt', 'w')
t = int(f.readline().strip())
for i in xrange(1, t + 1):
o.write("Case #{}:".format(i))
n = f.readline()
n = int(f.readline().strip())
x = [int(j) for j in f.readline().strip().split()]
mean = 0
for j in xrange(0, n):
mean += x[j]
... | f = open('task1-test-input.txt')
o = open('o1.txt', 'w')
t = int(f.readline().strip())
for i in xrange(1, t + 1):
o.write('Case #{}:'.format(i))
n = f.readline()
n = int(f.readline().strip())
x = [int(j) for j in f.readline().strip().split()]
mean = 0
for j in xrange(0, n):
mean += x[j]
... |
# Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
# Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." ... | def compare_lists(list_one, list_two):
if list_one == list_two:
print('The lists are the same')
else:
print('The lists are not the same')
list_one = [1, 2, 5, 6, 2]
list_two = [1, 2, 5, 6, 2]
compare_lists(list_one, list_two)
list_one = [1, 2, 5, 6, 5]
list_two = [1, 2, 5, 6, 5, 3]
compare_lists... |
# spec.py
# Problem 1: Implement this function.
def Newtons_method(f, x0, Df, iters=15, tol=.1e-5):
'''
Use Newton's method to approximate a zero of a function.
Inputs:
f (function): A function handle. Should represent a function
from R to R.
x0 (float): Initial guess.
... | def newtons_method(f, x0, Df, iters=15, tol=1e-06):
"""
Use Newton's method to approximate a zero of a function.
Inputs:
f (function): A function handle. Should represent a function
from R to R.
x0 (float): Initial guess.
Df (function): A function handle. Should represen... |
#
# PySNMP MIB module IEEE8021-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-TC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:13:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) ... |
entries = [
{
"env-title": "atari-alien",
"env-variant": "No-op start",
"score": 1536.05,
},
{
"env-title": "atari-amidar",
"env-variant": "No-op start",
"score": 497.62,
},
{
"env-title": "atari-assault",
"env-variant": "No-op start",
... | entries = [{'env-title': 'atari-alien', 'env-variant': 'No-op start', 'score': 1536.05}, {'env-title': 'atari-amidar', 'env-variant': 'No-op start', 'score': 497.62}, {'env-title': 'atari-assault', 'env-variant': 'No-op start', 'score': 12086.86}, {'env-title': 'atari-asterix', 'env-variant': 'No-op start', 'score': 29... |
TS = "timestep"
H = "hourly"
D = "daily"
M = "monthly"
A = "annual"
RP = "runperiod"
FREQUENCY = "frequency"
VARIABLE = "variable"
KEY = "key"
TYPE = "type"
UNITS = "units"
| ts = 'timestep'
h = 'hourly'
d = 'daily'
m = 'monthly'
a = 'annual'
rp = 'runperiod'
frequency = 'frequency'
variable = 'variable'
key = 'key'
type = 'type'
units = 'units' |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
# edge case
if l1 is None:
return l2
if l2 is None:
return l1
# general case
cur1 = l1
cur2 = l2
ans = ListNode()
cur = ans
while cur... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
cur1 = l1
cur2 = l2
ans = list_node()
cur = ans
while cur1 or cur2:
if not cur2 o... |
class ArgumentError(ValueError):
...
class PathOpError(ValueError):
...
| class Argumenterror(ValueError):
...
class Pathoperror(ValueError):
... |
"""
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
"""
__author__ = 'Daniel'
class Solution(object):
def isPowerOfFour(self, num):
"""
... | """
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
"""
__author__ = 'Daniel'
class Solution(object):
def is_power_of_four(self, num):
"""
... |
# Do not edit. bazel-deps autogenerates this file from.
_JAVA_LIBRARY_TEMPLATE = """
java_library(
name = "{name}",
exports = [
{exports}
],
runtime_deps = [
{runtime_deps}
],
visibility = [
"{visibility}"
]
)\n"""
_SCALA_IMPORT_TEMPLATE = """
scala_import(
name = "{name}",
export... | _java_library_template = '\njava_library(\n name = "{name}",\n exports = [\n {exports}\n ],\n runtime_deps = [\n {runtime_deps}\n ],\n visibility = [\n "{visibility}"\n ]\n)\n'
_scala_import_template = '\nscala_import(\n name = "{name}",\n exports = [\n {exports}\n ],\n jars = [\n... |
# Q20
print("======= a =======")
for x in range(1,200):
if x % 4 == 0:
print('{0:.2f}'.format(x))
print("======= b =======")
#while x < 200:
# if (x % 4 == 0):
# x = x + 1
# print('{0:d}'.format(x))
# x = x + 2
print("======= c =======")
for x in range(1,200):
if x % 2 == 0:
... | print('======= a =======')
for x in range(1, 200):
if x % 4 == 0:
print('{0:.2f}'.format(x))
print('======= b =======')
print('======= c =======')
for x in range(1, 200):
if x % 2 == 0:
print('{0:d}'.format(x))
print('======= d =======')
for x in range(1, 200):
if x % 4 == 0:
print('... |
num = ''
for i in range(10):
num = str(i)
for j in range(10):
num += str(j)
for k in range(10):
num += str(k)
print(num)
num = str(i) + str(j)
num = str(i) | num = ''
for i in range(10):
num = str(i)
for j in range(10):
num += str(j)
for k in range(10):
num += str(k)
print(num)
num = str(i) + str(j)
num = str(i) |
# Copyright (c) OpenMMLab. All rights reserved.
item1 = [1, 2]
item2 = {'a': 0}
item3 = True
item4 = 'test'
item_cfg = {'b': 1}
item5 = {'cfg': item_cfg}
item6 = {'cfg': item_cfg}
| item1 = [1, 2]
item2 = {'a': 0}
item3 = True
item4 = 'test'
item_cfg = {'b': 1}
item5 = {'cfg': item_cfg}
item6 = {'cfg': item_cfg} |
DB_DATA = {
"users": [],
"protected_data": "Lorem ipsum dolor sit amet..."
}
| db_data = {'users': [], 'protected_data': 'Lorem ipsum dolor sit amet...'} |
name = 'Webware for Python'
version = (3, 0, 4)
status = 'stable'
requiredPyVersion = (3, 6)
synopsis = (
"Webware for Python is a time-tested"
" modular, object-oriented web framework.")
webwareConfig = {
'examplePages': [
'Welcome',
'ShowTime',
'CountVisits',
'Error',
... | name = 'Webware for Python'
version = (3, 0, 4)
status = 'stable'
required_py_version = (3, 6)
synopsis = 'Webware for Python is a time-tested modular, object-oriented web framework.'
webware_config = {'examplePages': ['Welcome', 'ShowTime', 'CountVisits', 'Error', 'View', 'Introspect', 'Colors', 'ListBox', 'Forward', ... |
__all__ = ["VERSION"]
# Do not use pkg_resources to find the version but set it here directly!
VERSION = '0.0.1'
| __all__ = ['VERSION']
version = '0.0.1' |
#
# PySNMP MIB module A3COM-HUAWEI-SSH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-SSH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:07:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon')
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_co... |
class OptionsNotSet(Exception):
""" No Options were set"""
class NoPlayerRegistered(Exception):
""" No Players were registered."""
class ValueDoesNotExist(Exception):
""" The value does not exist on a dart-board """
class FieldDoesNotExist(Exception):
""" The given field does not exist on a dart-boa... | class Optionsnotset(Exception):
""" No Options were set"""
class Noplayerregistered(Exception):
""" No Players were registered."""
class Valuedoesnotexist(Exception):
""" The value does not exist on a dart-board """
class Fielddoesnotexist(Exception):
""" The given field does not exist on a dart-boar... |
# coding=utf-8
class BaseOptimizer():
"""Abstract class for Optimizer
"""
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
def get_optimizer(self, weight_params, params):
raise NotImplementedError()
| class Baseoptimizer:
"""Abstract class for Optimizer
"""
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
def get_optimizer(self, weight_params, params):
raise not_implemented_error() |
"""
Description:
Encontra objetos em lista
Author: @Palin/Renan
Created: 2021-07-01
Copyright: (c) Ampere Consultoria Ltda
"""
def find_obj(lst_to_find, name_field: str, value_to_find):
if len(lst_to_find) == 0:
return None
try:
lst_result = list... | """
Description:
Encontra objetos em lista
Author: @Palin/Renan
Created: 2021-07-01
Copyright: (c) Ampere Consultoria Ltda
"""
def find_obj(lst_to_find, name_field: str, value_to_find):
if len(lst_to_find) == 0:
return None
try:
lst_result = list(... |
class ReviewRouter(object):
"""
Sends all review-related operations to a database with the alias of
"reviews". No other apps should use this db alias.
"""
def db_for_read(self, model, **hints):
if model._meta.app_label == "reviews":
return "reviews"
return None
def d... | class Reviewrouter(object):
"""
Sends all review-related operations to a database with the alias of
"reviews". No other apps should use this db alias.
"""
def db_for_read(self, model, **hints):
if model._meta.app_label == 'reviews':
return 'reviews'
return None
def ... |
SPANISH = "Spanish"
FRENCH = "French"
ENGLISH_HELLO_PREFIX = "Hello"
SPANISH_HELLO_PREFIX = "Hola"
FRENCH_HELLO_PREFIX = "Bonjour"
def hello(name: str = None, language: str = None) -> str:
"""Return a personalized greeting.
Defaulting to `Hello, World` if no name and language are passed.
"""
if not na... | spanish = 'Spanish'
french = 'French'
english_hello_prefix = 'Hello'
spanish_hello_prefix = 'Hola'
french_hello_prefix = 'Bonjour'
def hello(name: str=None, language: str=None) -> str:
"""Return a personalized greeting.
Defaulting to `Hello, World` if no name and language are passed.
"""
if not name:
... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | """Rules and macros for collecting LicenseInfo providers."""
load('@rules_license//rules:providers.bzl', 'LicenseInfo', 'LicensesInfo')
_verbosity = 0
def _debug(loglevel, msg):
if _VERBOSITY > loglevel:
print(msg)
def _get_transitive_licenses(deps, licenses, trans):
for dep in deps:
if Licens... |
class SesDevException(Exception):
pass
class AddRepoNoUpdateWithExplicitRepo(SesDevException):
def __init__(self):
super().__init__(
"The --update option does not work with an explicit custom repo."
)
class BadMakeCheckRolesNodes(SesDevException):
def __init__(self):
... | class Sesdevexception(Exception):
pass
class Addreponoupdatewithexplicitrepo(SesDevException):
def __init__(self):
super().__init__('The --update option does not work with an explicit custom repo.')
class Badmakecheckrolesnodes(SesDevException):
def __init__(self):
super().__init__('"mak... |
"""
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475"
Desired Output
0.8475
"""
text = "X-DSPAM-Confidence: 0.8475"
index = text.fin... | """
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475"
Desired Output
0.8475
"""
text = 'X-DSPAM-Confidence: 0.8475'
index = text.find(... |
l = int(input("enter the lower interval"))
u = int(input("enter the upper interval"))
for num in range(l,u+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
| l = int(input('enter the lower interval'))
u = int(input('enter the upper interval'))
for num in range(l, u + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num) |
class Vocabs():
def __init__(self):
reuters = None
aapd = None
VOCABS = Vocabs()
| class Vocabs:
def __init__(self):
reuters = None
aapd = None
vocabs = vocabs() |
def respond(start_response, code, headers=[('Content-type', 'text/plain')], body=b''):
start_response(code, headers)
return [body]
def key2path(key):
b = key.encode('utf-8')
return hashlib.md5(b).digest()
| def respond(start_response, code, headers=[('Content-type', 'text/plain')], body=b''):
start_response(code, headers)
return [body]
def key2path(key):
b = key.encode('utf-8')
return hashlib.md5(b).digest() |
def part1():
pass
if __name__ == '__main__':
with open('input.txt') as f:
lines = f.read().splitlines() | def part1():
pass
if __name__ == '__main__':
with open('input.txt') as f:
lines = f.read().splitlines() |
class A:
def __init__(self):
print("1")
def __init__(self):
print("2")
a= A() | class A:
def __init__(self):
print('1')
def __init__(self):
print('2')
a = a() |
def decay_lr_every(optimizer, lr, epoch, decay_every=30):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = lr * (0.1 ** (epoch // decay_every))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
# TODO: noam scheduler
# "Schedule": {
# "name": "... | def decay_lr_every(optimizer, lr, epoch, decay_every=30):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = lr * 0.1 ** (epoch // decay_every)
for param_group in optimizer.param_groups:
param_group['lr'] = lr |
#!/usr/bin/python3
"""
Main file for testing
"""
makeChange = __import__('0-making_change').makeChange
print(makeChange([1, 2, 25], 37))
print(makeChange([1256, 54, 48, 16, 102], 1453)) | """
Main file for testing
"""
make_change = __import__('0-making_change').makeChange
print(make_change([1, 2, 25], 37))
print(make_change([1256, 54, 48, 16, 102], 1453)) |
WSGI_ENTRY_SCRIPT = """
import logging
from parallelm.ml_engine.rest_model_serving_engine import RestModelServingEngine
from {module} import {cls}
from {restful_comp_module} import {restful_comp_cls}
logging.basicConfig(format='{log_format}')
logging.getLogger('{root_logger_name}').setLevel({log_level})
comp = {res... | wsgi_entry_script = "\nimport logging\n\nfrom parallelm.ml_engine.rest_model_serving_engine import RestModelServingEngine\nfrom {module} import {cls}\nfrom {restful_comp_module} import {restful_comp_cls}\n\n\nlogging.basicConfig(format='{log_format}')\nlogging.getLogger('{root_logger_name}').setLevel({log_level})\n\nco... |
load("@bazel_gazelle//:deps.bzl", "go_repository")
# bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories
def go_repositories():
go_repository(
name = "com_github_fsnotify_fsnotify",
importpath = "github.com/fsnotify/fsnotify",
sum = "h1:hsms1Qy... | load('@bazel_gazelle//:deps.bzl', 'go_repository')
def go_repositories():
go_repository(name='com_github_fsnotify_fsnotify', importpath='github.com/fsnotify/fsnotify', sum='h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=', version='v1.4.9')
go_repository(name='com_github_golang_protobuf', importpath='github.co... |
# Python Program to demonstrate the LIFO principle using stack
print("Stack utilizes the LIFO (Last In First Out) Principle")
print()
stack = [] # Initializating Empty Stack
print("Initializing empty stack :", stack) # Printing empty Stack
# Adding items to the Stack
stack.append("Hey")
stack.append("there!")
stack... | print('Stack utilizes the LIFO (Last In First Out) Principle')
print()
stack = []
print('Initializing empty stack :', stack)
stack.append('Hey')
stack.append('there!')
stack.append('This')
stack.append('is')
stack.append('a')
stack.append('Stack!')
print('After adding items into the stack:', stack)
stack.pop()
print('A... |
# Copyright 2020, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | """Defines errors used by multiple modules in the `tff.templates` package."""
class Templateinitfnparamnotemptyerror(TypeError):
"""`TypeError` for `initialize_fn` having arguments."""
pass
class Templatestatenotassignableerror(TypeError):
"""`TypeError` for `state` not being assignable to expected `state... |
class Plugin_OBJ():
def __init__(self, fhdhr, plugin_utils, broadcast_ip, max_age):
self.fhdhr = fhdhr
self.broadcast_ip = broadcast_ip
self.device_xml_path = '/hdhr/device.xml'
self.cable_schema = "urn:schemas-opencable-com:service:Security:1"
self.ota_schema = "urn:sch... | class Plugin_Obj:
def __init__(self, fhdhr, plugin_utils, broadcast_ip, max_age):
self.fhdhr = fhdhr
self.broadcast_ip = broadcast_ip
self.device_xml_path = '/hdhr/device.xml'
self.cable_schema = 'urn:schemas-opencable-com:service:Security:1'
self.ota_schema = 'urn:schemas-u... |
"""
Data store module
- simple key-value store to organize data collection and lookup / filtering based on meta data.
- the encoding of the meta data follows the encoding of the rest of my Advanced Systems Lab (ASL)
project data processing; project description follows on my homepage
id_str consists of: key1_value1_... | """
Data store module
- simple key-value store to organize data collection and lookup / filtering based on meta data.
- the encoding of the meta data follows the encoding of the rest of my Advanced Systems Lab (ASL)
project data processing; project description follows on my homepage
id_str consists of: key1_value1_... |
class OASInvalidSpec:
...
class OASInvalidTypeValue(OASInvalidSpec, TypeError):
"""OASInvalidTypeValue refers to invalid type of the value.
Thrown if either "default" or "example" value's type does not match
the OASType
"""
...
class OASInvalidConstraints(OASInvalidSpec, ValueError):
"... | class Oasinvalidspec:
...
class Oasinvalidtypevalue(OASInvalidSpec, TypeError):
"""OASInvalidTypeValue refers to invalid type of the value.
Thrown if either "default" or "example" value's type does not match
the OASType
"""
...
class Oasinvalidconstraints(OASInvalidSpec, ValueError):
"""... |
class Sigma:
"""
A representation of the sigma term in the model.
Specifically, this is the sigma of y itself, i.e. the sigma in
y ~ Normal(sum_of_trees, sigma)
The default prior is an inverse gamma distribution on the variance
The parametrization is slightly different to the numpy gamma ... | class Sigma:
"""
A representation of the sigma term in the model.
Specifically, this is the sigma of y itself, i.e. the sigma in
y ~ Normal(sum_of_trees, sigma)
The default prior is an inverse gamma distribution on the variance
The parametrization is slightly different to the numpy gamma ve... |
"""Reverse a list.
Reverse the order of the elements of list _x .
This may reverse "in-place" and destroy the original ordering.
Source: programming-idioms.org
"""
# Implementation author: synapton
# Created on 2017-05-14T03:47:52.643616Z
# Last modified on 2019-09-27T02:57:37.321491Z
# Version 3
# Creates a new, ... | """Reverse a list.
Reverse the order of the elements of list _x .
This may reverse "in-place" and destroy the original ordering.
Source: programming-idioms.org
"""
y = x[::-1] |
def _remove_extensions(file_list):
rv = {}
for f in file_list:
if (f.extension == "c" or f.extension == "s" or f.extension == "S"):
rv[f.path[:-2]] = f
else:
rv[f.path] = f
return rv
def _remove_arch(file_dict, arch):
rv = {}
for f in file_dict:
idx =... | def _remove_extensions(file_list):
rv = {}
for f in file_list:
if f.extension == 'c' or f.extension == 's' or f.extension == 'S':
rv[f.path[:-2]] = f
else:
rv[f.path] = f
return rv
def _remove_arch(file_dict, arch):
rv = {}
for f in file_dict:
idx = f... |
v = ["a", "i", "u", "e", "o"]
c = input()
if c in v:
print("vowel")
else:
print("consonant") | v = ['a', 'i', 'u', 'e', 'o']
c = input()
if c in v:
print('vowel')
else:
print('consonant') |
HXLM_PLUGIN_META = {
'code': "xa_amnesty",
'code_if_approved': "xz_amnesty"
}
| hxlm_plugin_meta = {'code': 'xa_amnesty', 'code_if_approved': 'xz_amnesty'} |
"""
ID: PRTM
Title: Calculating Protein Mass
URL: http://rosalind.info/problems/prtm/
"""
monoisotopic_mass_dict = {
'A': 71.03711,
'C': 103.00919,
'D': 115.02694,
'E': 129.04259,
'F': 147.06841,
'G': 57.02146,
'H': 137.05891,
'I': 113.08406,
'K': 128.09496,
'L': 113.08406,
... | """
ID: PRTM
Title: Calculating Protein Mass
URL: http://rosalind.info/problems/prtm/
"""
monoisotopic_mass_dict = {'A': 71.03711, 'C': 103.00919, 'D': 115.02694, 'E': 129.04259, 'F': 147.06841, 'G': 57.02146, 'H': 137.05891, 'I': 113.08406, 'K': 128.09496, 'L': 113.08406, 'M': 131.04049, 'N': 114.04293, 'P': 97.05276,... |
"""
This package contains the code for testing pyqode.python.
To run the test suite, just run the following command::
tox
To select a specific environment, use the -e option. E.g. to run coverage
tests::
tox -e cov
Here is the list of available test environments:
- py27-pyqt4
- py27-pyqt5
- py... | """
This package contains the code for testing pyqode.python.
To run the test suite, just run the following command::
tox
To select a specific environment, use the -e option. E.g. to run coverage
tests::
tox -e cov
Here is the list of available test environments:
- py27-pyqt4
- py27-pyqt5
- py... |
horpos = list(map(int, open('Day 07.input').readline().split(',')))
mean = sum(horpos) / len(horpos)
target1 = mean - (mean % 1)
target2 = mean + (1 - mean % 1)
print(min(round(sum((abs(x - target1) * (abs(x - target1) + 1)) / 2 for x in horpos)),
round(sum((abs(x - target2) * (abs(x - target2) + 1)) / 2 for ... | horpos = list(map(int, open('Day 07.input').readline().split(',')))
mean = sum(horpos) / len(horpos)
target1 = mean - mean % 1
target2 = mean + (1 - mean % 1)
print(min(round(sum((abs(x - target1) * (abs(x - target1) + 1) / 2 for x in horpos))), round(sum((abs(x - target2) * (abs(x - target2) + 1) / 2 for x in horpos))... |
n = int(input())
positives = []
negatives = []
for _ in range(n):
num = int(input())
if num >= 0:
positives.append(num)
else:
negatives.append(num)
count_of_positives = len(positives)
sum_of_negatives = sum(negatives)
print(positives)
print(negatives)
print(f'Count of po... | n = int(input())
positives = []
negatives = []
for _ in range(n):
num = int(input())
if num >= 0:
positives.append(num)
else:
negatives.append(num)
count_of_positives = len(positives)
sum_of_negatives = sum(negatives)
print(positives)
print(negatives)
print(f'Count of positives: {count_of_po... |
s = "abcdefgh"
for index in range(len(s)):
if s[index] == "i" or s[index] == "u":
print("There is an i or u")
# Code can be rewrited as
for char in s:
if char == "i" or char == "u":
print("There is an i or u") | s = 'abcdefgh'
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print('There is an i or u')
for char in s:
if char == 'i' or char == 'u':
print('There is an i or u') |
#! usr/bin/python3
#-*- coding:utf-8 -*-
"""Constants of MacGyver game"""
# Window settings
number_sprite_side = 15
sprite_size = 40
score_wiev=40
window_side = number_sprite_side * sprite_size
window_height = number_sprite_side * sprite_size + score_wiev
#The window customization
window_title = "MacGyver"
image_icon... | """Constants of MacGyver game"""
number_sprite_side = 15
sprite_size = 40
score_wiev = 40
window_side = number_sprite_side * sprite_size
window_height = number_sprite_side * sprite_size + score_wiev
window_title = 'MacGyver'
image_icon = 'pictures/MacGyver.png'
home_bis = 'pictures/home.jpg'
image_plastic_tube = 'pictu... |
banned_words = input().split()
text = input()
replaced_text = text
for word in banned_words:
replaced_text = replaced_text.replace(word, "*" * len(word))
print(replaced_text)
| banned_words = input().split()
text = input()
replaced_text = text
for word in banned_words:
replaced_text = replaced_text.replace(word, '*' * len(word))
print(replaced_text) |
vocab_sizes_dict = {'BabyAI-BossLevel-v0': 31,
'BabyAI-BossLevelNoUnlock-v0': 31,
'BabyAI-GoTo-v0': 13,
'BabyAI-GoToImpUnlock-v0': 13,
'BabyAI-GoToLocal-v0': 13,
'BabyAI-GoToLocalS5N2-v0': 13,
'BabyAI... | vocab_sizes_dict = {'BabyAI-BossLevel-v0': 31, 'BabyAI-BossLevelNoUnlock-v0': 31, 'BabyAI-GoTo-v0': 13, 'BabyAI-GoToImpUnlock-v0': 13, 'BabyAI-GoToLocal-v0': 13, 'BabyAI-GoToLocalS5N2-v0': 13, 'BabyAI-GoToLocalS6N2-v0': 13, 'BabyAI-GoToLocalS6N3-v0': 13, 'BabyAI-GoToLocalS6N4-v0': 13, 'BabyAI-GoToLocalS7N4-v0': 13, 'Ba... |
str=input("Enter string:")
str_list=list(str)
rev_list=[]
rev_str=""
length=len(str_list)
for i in range(-1,-(length+1),-1):
rev_list.append(str_list[i])
rev=rev_str.join(rev_list)
print(rev)
print("Character in even index:")
for i in range(0,len(str),2):
print(str[i])
| str = input('Enter string:')
str_list = list(str)
rev_list = []
rev_str = ''
length = len(str_list)
for i in range(-1, -(length + 1), -1):
rev_list.append(str_list[i])
rev = rev_str.join(rev_list)
print(rev)
print('Character in even index:')
for i in range(0, len(str), 2):
print(str[i]) |
test_ads_info = [
{'ad_id': 787, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': 'JV', 'item_price': 812.32},
{'ad_id': 476, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': '... | test_ads_info = [{'ad_id': 787, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': 'JV', 'item_price': 812.32}, {'ad_id': 476, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': 'JV', 'ite... |
class BaseAggregator(object):
def __init__(self, *args, **kwargs):
pass
def process(self, current_activities, original_activities, aggregators, *args, **kwargs):
"""
Processes the activities performing any mutations necessary.
:type current_activities: list
:param curren... | class Baseaggregator(object):
def __init__(self, *args, **kwargs):
pass
def process(self, current_activities, original_activities, aggregators, *args, **kwargs):
"""
Processes the activities performing any mutations necessary.
:type current_activities: list
:param curre... |
#
# PySNMP MIB module TELESYN-ATI-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TELESYN-ATI-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 18:22:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ... |
def make_shirt(size, message):
"""Display information regarding the size and message of a shirt."""
print("The shirt size is " + size +
" and the message will read: " + message + ".")
make_shirt('large', 'Archaeology Club')
def make_shirt(size, message):
"""Display information regarding the si... | def make_shirt(size, message):
"""Display information regarding the size and message of a shirt."""
print('The shirt size is ' + size + ' and the message will read: ' + message + '.')
make_shirt('large', 'Archaeology Club')
def make_shirt(size, message):
"""Display information regarding the size and messag... |
"""
Author: Ao Wang
Date: 09/05/19
Description: Affine cipher with decrypter/hack
"""
# The function loads the English alphabet
def loadAlphabet():
alphabet = ""
for i in range(26):
alphabet += chr(ord("a") + i)
return alphabet
# The function returns the greatest common denominator using Euclid's... | """
Author: Ao Wang
Date: 09/05/19
Description: Affine cipher with decrypter/hack
"""
def load_alphabet():
alphabet = ''
for i in range(26):
alphabet += chr(ord('a') + i)
return alphabet
def gcd(num1, num2):
while num1 != 0:
(num1, num2) = (num2 % num1, num1)
return num2
def mod_i... |
#
# PySNMP MIB module FOUNDRY-SN-SWITCH-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FOUNDRY-SN-SWITCH-GROUP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:23:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint) ... |
class Employee:
def __init__(self, surname, name, contact):
self.surname = surname
self.name = name
self.contact = contact
def __eq__(self, other):
return self.name == other.name \
and self.surname == other.surname \
and self.contact == other.contac... | class Employee:
def __init__(self, surname, name, contact):
self.surname = surname
self.name = name
self.contact = contact
def __eq__(self, other):
return self.name == other.name and self.surname == other.surname and (self.contact == other.contact)
class Contact:
def __in... |
# Assume you have a file system named quotaFs
file_system_name = "quotaFs"
# Delete the quotas of groups on the file system with ids 998 and 999
client.delete_quotas_groups(file_system_names=[file_system_name], gids=[998, 999])
# Delete the quotas of groups on the file system with names group1 and group2
client.delet... | file_system_name = 'quotaFs'
client.delete_quotas_groups(file_system_names=[file_system_name], gids=[998, 999])
client.delete_quotas_groups(file_system_names=[file_system_name], group_names=['group1', 'group2']) |
class Atom:
def __init__(self, id_, position, chain_id, name, element, residue=None, altloc=None, occupancy=None):
self.id = id_
self.name = name
self.element = element
self.chain_id = chain_id
self.position = position
self.residue = residue
self.altloc = al... | class Atom:
def __init__(self, id_, position, chain_id, name, element, residue=None, altloc=None, occupancy=None):
self.id = id_
self.name = name
self.element = element
self.chain_id = chain_id
self.position = position
self.residue = residue
self.altloc = alt... |
utils ='''
from extensions.extension import pwd_context
from flask import current_app
# from app.custom_errors import PasswordLength
class PasswordLength(Exception):
pass
def verify_secret(plain_secret: str, hashed_secret: str):
""" check plain password with hashed password """
if len(plain_secret) < 8:... | utils = '\nfrom extensions.extension import pwd_context\nfrom flask import current_app\n# from app.custom_errors import PasswordLength\n\n\nclass PasswordLength(Exception):\n pass\n\n\ndef verify_secret(plain_secret: str, hashed_secret: str):\n """ check plain password with hashed password """\n if len(plain_s... |
"""A module defining the third party dependency OpenSSL"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def openssl_repositories():
maybe(
http_archive,
name = "openssl",
build_file = Label("//openssl:BU... | """A module defining the third party dependency OpenSSL"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
def openssl_repositories():
maybe(http_archive, name='openssl', build_file=label('//openssl:BUILD.openssl.bazel'), sha256='8... |
# V0
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
A.sort(key = lambda x : x % 2)
N = len(A)
res = []
for i in range(N // 2):
res.append(A[i])
res.append(A[N - 1 - i])
ret... | class Solution:
def sort_array_by_parity_ii(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
A.sort(key=lambda x: x % 2)
n = len(A)
res = []
for i in range(N // 2):
res.append(A[i])
res.append(A[N - 1 - i])
return... |
while True:
a,b = map(int,input().split())
if a== b == 0:
break
k = 1
if b >= a-b:
k1 = b
k2 = a-b
else:
k1 = a-b
k2 = b
for i in range(k1+1,a+1):
k*=i
for i in range(2,k2+1):
k//=i
print(k) | while True:
(a, b) = map(int, input().split())
if a == b == 0:
break
k = 1
if b >= a - b:
k1 = b
k2 = a - b
else:
k1 = a - b
k2 = b
for i in range(k1 + 1, a + 1):
k *= i
for i in range(2, k2 + 1):
k //= i
print(k) |
#
# PySNMP MIB module HP-ICF-CHASSIS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CHASSIS
# Produced by pysmi-0.3.4 at Wed May 1 13:33:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
"""Gets the digging in sentences that are non-blocking, since the other ones were
not included in Futrell et al 2019"""
i =0
lines = []
for line in open("../unkified_digging_in_sentences.txt"):
if i < 93:
lines.append(line)
if i >= 186 and i < 279:
lines.append(line)
i += 1
for line in lines... | """Gets the digging in sentences that are non-blocking, since the other ones were
not included in Futrell et al 2019"""
i = 0
lines = []
for line in open('../unkified_digging_in_sentences.txt'):
if i < 93:
lines.append(line)
if i >= 186 and i < 279:
lines.append(line)
i += 1
for line in line... |
class C(Exception):
pass
try:
raise C
except C:
print("caught exception")
| class C(Exception):
pass
try:
raise C
except C:
print('caught exception') |
for i in range(2,21):
with open(f"Tables/ Table of {i}","w") as f:
for j in range(1,11):
f.write(f"{i} X {j} ={i*j}")
if j!=10:
f.write("\n")
| for i in range(2, 21):
with open(f'Tables/ Table of {i}', 'w') as f:
for j in range(1, 11):
f.write(f'{i} X {j} ={i * j}')
if j != 10:
f.write('\n') |
# Example configuration file
# Debug mode
DEBUG = False
# host and port. 127.0.0.1 will only serve locally - set to 0.0.0.0 (or iface IP) to have available externally.
HOST = '0.0.0.0'
PORT = 8765
# Secret key. This ensures only approved applications can use this. YOU MUST CHANGE THIS VALUE TO YOUR OWN SECRET!
# Not... | debug = False
host = '0.0.0.0'
port = 8765
secret = '8ba6d280d4ce9a416e9b604f3f0ebb'
stats_db = 'sqlite:////var/lib/ckanpackager/stats.db'
celery_broker = 'redis://localhost:6379/0'
store_directory = '/var/www/ckanpackager/resources'
temp_directory = '/tmp'
cache_time = 60 * 60 * 24
page_size = 5000
slow_request = 1000... |
b = False
e = "Hello world"
while b:
print(b)
d = True
while d:
print(d and False)
print(d and True)
print("hello")
| b = False
e = 'Hello world'
while b:
print(b)
d = True
while d:
print(d and False)
print(d and True)
print('hello') |
# Please do not any airflow imports in this file
# We want to allow importing constants from this file without any side effects
# Do not change this name unless you change the same constant in monitor_as_dag.py in dbnd-airflow-monitor
MONITOR_DAG_NAME = "databand_airflow_monitor"
| monitor_dag_name = 'databand_airflow_monitor' |
data = input().split()
x = int(data[0])
y = int(data[1])
limit = int(data[2])
for value in range(1,limit+1):
output = ""
if value % x == 0:
output += "Fizz"
if value % y == 0:
output += "Buzz"
if output == "":
print(value)
else:
print(output) | data = input().split()
x = int(data[0])
y = int(data[1])
limit = int(data[2])
for value in range(1, limit + 1):
output = ''
if value % x == 0:
output += 'Fizz'
if value % y == 0:
output += 'Buzz'
if output == '':
print(value)
else:
print(output) |
limit=int(input("enter the limit"))
sum=0
for i in range(1,limit+1,1) :
if(i % 2== 0 ):
print("even no is",i)
sum=sum+i
print(sum)
| limit = int(input('enter the limit'))
sum = 0
for i in range(1, limit + 1, 1):
if i % 2 == 0:
print('even no is', i)
sum = sum + i
print(sum) |
# -*- coding: utf-8 -*-
# the __all__ is generated
__all__ = []
# __init__.py structure:
# common code of the package
# export interface in __all__ which contains __all__ of its sub modules
# import all from submodule quote
# from .quote import *
# from .quote import __all__ as _quote_all
# __all__ += _quote_all
# ... | __all__ = [] |
def war(Naomi_w, Ken_w):
Naomi_wins = 0
while len(Naomi_w) > 0:
for X in Naomi_w:
temp = []
done = 0
Chosen_Naomi = X
Told_Naomi = X
for i in Ken_w:
if i > X:
temp.append((i, i - X))
... | def war(Naomi_w, Ken_w):
naomi_wins = 0
while len(Naomi_w) > 0:
for x in Naomi_w:
temp = []
done = 0
chosen__naomi = X
told__naomi = X
for i in Ken_w:
if i > X:
temp.append((i, i - X))
don... |
#!/usr/bin/env python3
"""Convert arabic numbers to roman numbers.
Title:
Roman Number Generator
Description:
Develop a program that accepts an integer
and outputs the Roman Number equivalent of that number.
Examples:
4 - IV
12 - XII
20 - XX
Submitted by SoReNa
"""
def arabic_to_roman(number: int) -> str:
"""Re... | """Convert arabic numbers to roman numbers.
Title:
Roman Number Generator
Description:
Develop a program that accepts an integer
and outputs the Roman Number equivalent of that number.
Examples:
4 - IV
12 - XII
20 - XX
Submitted by SoReNa
"""
def arabic_to_roman(number: int) -> str:
"""Return roman version of th... |
class TumorSampleProfileList(object):
def __init__(self):
self.tumor_profiles = []
self._name = ''
self._num_read_counts = 0
def __iter__(self):
return iter(self.tumor_profiles)
@property
def name(self):
return self._name
@name.setter
... | class Tumorsampleprofilelist(object):
def __init__(self):
self.tumor_profiles = []
self._name = ''
self._num_read_counts = 0
def __iter__(self):
return iter(self.tumor_profiles)
@property
def name(self):
return self._name
@name.setter
def name(self, va... |
"""Exercicio 34:
Crie uma classe com dois metodos, pelo menos:
recebe_string(): para pegar do console um texto
printa_string(): para imprimir a string no console
"""
class IOTexto():
def __init__(self):
self.texto = ""
def recebe_string(self):
self.texto = input("Defina o texto: ")
def pr... | """Exercicio 34:
Crie uma classe com dois metodos, pelo menos:
recebe_string(): para pegar do console um texto
printa_string(): para imprimir a string no console
"""
class Iotexto:
def __init__(self):
self.texto = ''
def recebe_string(self):
self.texto = input('Defina o texto: ')
def pri... |
'''
Author : MiKueen
Level : Easy
Company : Google
Problem Statement : Two Sum
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
def twoSum(nums, k):
... | """
Author : MiKueen
Level : Easy
Company : Google
Problem Statement : Two Sum
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
"""
def two_sum(nums, k):... |
with open('texto1.txt', 'r') as arquivo:
conteudo = arquivo.read().split(',')
with open('resultado1.txt', 'w') as resultado:
for item in conteudo:
texto = f'novo conteudo Antonella te amo {item.strip()}\n'
resultado.write(texto)
| with open('texto1.txt', 'r') as arquivo:
conteudo = arquivo.read().split(',')
with open('resultado1.txt', 'w') as resultado:
for item in conteudo:
texto = f'novo conteudo Antonella te amo {item.strip()}\n'
resultado.write(texto) |
"""Given a graph G =(V, E) we want to find a minimum spannning tree in the graph (it may not be unique).
A minimuim spanning tree is a subset of the edges which connect all vertices in the graph with the minimal total edge cost.
Uses union and find:
Find:
find which component a particular elemnent belongs to find th... | """Given a graph G =(V, E) we want to find a minimum spannning tree in the graph (it may not be unique).
A minimuim spanning tree is a subset of the edges which connect all vertices in the graph with the minimal total edge cost.
Uses union and find:
Find:
find which component a particular elemnent belongs to find th... |
"""
---> Longest String Chain
---> Medium
"""
class Solution:
def longest_str_chain(self, words) -> int:
word_dict = {}
for w in sorted(words, key=len):
word_dict[w] = max(word_dict.get(w[:i] + w[i + 1:], 0) + 1 for i in range(len(w)))
print(w, word_dict)
return m... | """
---> Longest String Chain
---> Medium
"""
class Solution:
def longest_str_chain(self, words) -> int:
word_dict = {}
for w in sorted(words, key=len):
word_dict[w] = max((word_dict.get(w[:i] + w[i + 1:], 0) + 1 for i in range(len(w))))
print(w, word_dict)
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.