content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.righ... | class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.rig... |
# Tuples
coordinates = (4, 5) # Cant be changed or modified
print(coordinates[1])
# coordinates[1] = 10
# print(coordinates[1])
| coordinates = (4, 5)
print(coordinates[1]) |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.... | """Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.
"""
deps = ['build/goma', 'recipe_engine/context', 'recipe_engine/file', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engin... |
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('... | _a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(t('site'), _f == 'site', url(_a, 'default', 'site'))]
if request.args:
_t = request.args[0]
response.menu.append((t('edit'), _c == 'default... |
__author__ = 'sibirrer'
# this file contains a class to make a Moffat profile
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
... | __author__ = 'sibirrer'
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
def __init__(self):
self.param_names = ['amp... |
tempratures = [10,-20, -289, 100]
def c_to_f(c):
if c<-273.15:
return ""
return c* 9/5 +32
def writeToFile(input):
with open("output.txt","a") as file:
file.write(input)
for temp in tempratures:
writeToFile(str(c_to_f(temp)))
| tempratures = [10, -20, -289, 100]
def c_to_f(c):
if c < -273.15:
return ''
return c * 9 / 5 + 32
def write_to_file(input):
with open('output.txt', 'a') as file:
file.write(input)
for temp in tempratures:
write_to_file(str(c_to_f(temp))) |
class VoiceClient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = "/voice/v1/{}"
def create(self,
direction,
to,
caller_id,
execution_logic,
reference_logic='',
count... | class Voiceclient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = '/voice/v1/{}'
def create(self, direction, to, caller_id, execution_logic, reference_logic='', country_iso2='us', technology='pstn', status_callback_uri=''):
api_resource = self.api_re... |
class Solution(object):
def _dfs(self,num,res,n):
if num>n:
return
res.append(num)
num=num*10
if num<=n:
for i in xrange(10):
self._dfs(num+i,res,n)
def sovleOn(self,n):
res=[]
cur=1
for i in xrange(1,n+1):
... | class Solution(object):
def _dfs(self, num, res, n):
if num > n:
return
res.append(num)
num = num * 10
if num <= n:
for i in xrange(10):
self._dfs(num + i, res, n)
def sovle_on(self, n):
res = []
cur = 1
for i in x... |
expected_output = {
"ospf-statistics-information": {
"ospf-statistics": {
"dbds-retransmit": "203656",
"dbds-retransmit-5seconds": "0",
"flood-queue-depth": "0",
"lsas-acknowledged": "225554974",
"lsas-acknowledged-5seconds"... | expected_output = {'ospf-statistics-information': {'ospf-statistics': {'dbds-retransmit': '203656', 'dbds-retransmit-5seconds': '0', 'flood-queue-depth': '0', 'lsas-acknowledged': '225554974', 'lsas-acknowledged-5seconds': '0', 'lsas-flooded': '66582263', 'lsas-flooded-5seconds': '0', 'lsas-high-prio-flooded': '3755689... |
# coding: gbk
"""
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class ADG(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
... | """
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class Adg(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
raise No... |
"""
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
PLANS = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
FREE = Plan(1, 'f... | """
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
plans = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
free = plan(1, 'fre... |
N = int(input())
S = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No')
| n = int(input())
s = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No') |
#!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
# - Task Assistance
#
# Author: Zhuo Chen <zhuoc@cs.cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the... | is_streaming = True
recognize_only = False
task_server_port = 6090
best_engine = 'LEGO_FAST'
check_algorithm = 'table'
check_last_th = 1
master_server_port = 6091
save_image = False
image_height = 360
image_width = 640
blur_kernel_size = int(IMAGE_WIDTH // 16 + 1)
display_max_pixel = 640
display_scale = 5
display_list_... |
class Node():
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueErro... | class Node:
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueError
... |
"""Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
... | """Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
r... |
#def spam():
# eggs = 31337
#spam()
#print(eggs)
"""
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
"""
# Global variables can be read from local scope.
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
"""
"""
# Local and global variables with th... | """
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
'\n# Global variables can be read from local scope.\ndef spam():\n print(eggs)\neggs = 42\nspam()\nprint(eggs)\n'
"\n# Local and global variables with the same name.\n\ndef spam():\n eggs = 'spam local'\... |
# https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
# Explanation: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question
# Source: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/272994/Python-Greedy-Sum-Min*Len
class Solu... | class Solution:
def min_moves(self, nums: List[int]) -> int:
return sum(nums) - min(nums) * len(nums) |
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
... | class Solution:
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
length = la
else:
length = lb
digits = []
addition = 0
for x in rang... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: To find (and fix) two syntax errors
# A program to display Green Eggs and Ham (v4)
def showChorus():
print()
print("I do not like green eggs and ham.")
print... | def show_chorus():
print()
print('I do not like green eggs and ham.')
print('I do not like them Sam-I-am.')
print()
def show_verse1():
print('I do not like them here or there.')
print('I do not like them anywhere.')
print('I do not like them in a house')
print('I do not like them with ... |
_base_ = [
'../_base_/models/repdet_repvgg_pafpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py'
]
# model settings
model = dict(
type='RepDet',
pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth',
backbone=dict(
... | _base_ = ['../_base_/models/repdet_repvgg_pafpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py']
model = dict(type='RepDet', pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth', backbone=dict(type='RepVGG', arch='B1g2', out_stages=[1, 2, 3, 4], a... |
# Holy Stone - Holy Ground at the Snowfield (3rd job)
questIDs = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
hasQuest = False
for qid in questIDs:
if sm.hasQuest(qid):
hasQuest = True
break
if hasQuest:
if sm.sendAskYesNo("#b(A mysterious energy surroun... | quest_i_ds = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
has_quest = False
for qid in questIDs:
if sm.hasQuest(qid):
has_quest = True
break
if hasQuest:
if sm.sendAskYesNo('#b(A mysterious energy surrounds this stone. Do you want to investigate?)'):
... |
class CustomException(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args [1])
class DeprecatedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)... | class Customexception(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args[1])
class Deprecatedexception(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwar... |
class solutionLeetcode_3:
def lengthOfLongestSubstring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
... | class Solutionleetcode_3:
def length_of_longest_substring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
... |
#==============================================================================
# Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 ... | class Builderror(Exception):
"""
Base exception for errors raised while building
"""
pass
class Nosuchconfigseterror(BuildError):
"""
Exception signifying no config error with specified name exists
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
retu... |
#!/usr/bin/env python
# encoding: utf-8
"""
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
"""
| """
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
""" |
def f(x):
if x <= -2:
f = 1 - (x + 2)**2
return f
if -2 < x <= 2:
f = -(x/2)
return f
if 2 < x:
f = (x - 2)**2 + 1
return f
x = int(input())
print(f(x))
| def f(x):
if x <= -2:
f = 1 - (x + 2) ** 2
return f
if -2 < x <= 2:
f = -(x / 2)
return f
if 2 < x:
f = (x - 2) ** 2 + 1
return f
x = int(input())
print(f(x)) |
dnas = [
['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}],
['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}... | dnas = [['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}], ['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}]... |
def createArray(dims) :
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [createArray(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def minDeletionSize(self, A):
... | def create_array(dims):
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [create_array(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def min_deletion_size... |
lista = list(range(0,10001))
for cont in range(0,10001):
print(lista[cont])
for valor in lista:
print(valor) | lista = list(range(0, 10001))
for cont in range(0, 10001):
print(lista[cont])
for valor in lista:
print(valor) |
cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range (1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') | cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range(1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') |
#!/usr/bin/env python3
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i+w]} {(count / w) : .4f}')
| seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i + w]} {count / w: .4f}') |
# Princess No Damage Skin (30-Days)
success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.") |
class HiddenPeople():
"""Class for holding information on people"""
def __init__(self):
self.people = {
'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
... | class Hiddenpeople:
"""Class for holding information on people"""
def __init__(self):
self.people = {'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False, 'glasses': True, 'moustache': False}, 'Richard': {'bald': True, 'beard': True, 'eyes': 'brown', '... |
# 1) count = To count how many time a particular word & char. is appearing
x = "Keep grinding keep hustling"
print(x.count("t"))
# 2) index = To get index of letter(gives the lowest index)
x="Keep grinding keep hustling"
print(x.index("t")) # will give the lowest index value of (t)
# 3) find = To get index of lett... | x = 'Keep grinding keep hustling'
print(x.count('t'))
x = 'Keep grinding keep hustling'
print(x.index('t'))
x = 'Keep grinding keep hustling'
print(x.find('t'))
'\nNOTE : print(x.index("t",34)) : Search starts from index value 34 including 34\n' |
# example of redefinition __repr__ and __str__ of exception
class MyBad(Exception):
def __str__(self):
return 'My mistake!'
class MyBad2(Exception):
def __repr__(self):
return 'Not calable' # because buid-in method has __str__
try:
raise MyBad('spam')
except MyBad as X:
print(X) #... | class Mybad(Exception):
def __str__(self):
return 'My mistake!'
class Mybad2(Exception):
def __repr__(self):
return 'Not calable'
try:
raise my_bad('spam')
except MyBad as X:
print(X)
print(X.args)
try:
raise my_bad2('spam')
except MyBad2 as X:
print(X)
print(X.args)
r... |
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
'''
T: O(n log n) and S: O(1)
'''
n = len(nums)
sorted_nums = sorted(nums)
start, end = n + 1, -1
for i in range(n):
if nums[i] != sorted_nums[i]:
... | class Solution:
def find_unsorted_subarray(self, nums: List[int]) -> int:
"""
T: O(n log n) and S: O(1)
"""
n = len(nums)
sorted_nums = sorted(nums)
(start, end) = (n + 1, -1)
for i in range(n):
if nums[i] != sorted_nums[i]:
start ... |
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# oauth constants
HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site
QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA
HACkATHON_API_ENDPOINT = ... | hostname = 'http://hackathon.chinacloudapp.cn'
qq_oauth_state = 'openhackathon'
ha_ck_athon_api_endpoint = 'http://hackathon.chinacloudapp.cn:15000'
config = {'environment': 'local', 'login': {'github': {'access_token_url': 'https://github.com/login/oauth/access_token?client_id=a10e2290ed907918d5ab&client_secret=5b240a... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or not... | class Solution:
def get_target_copy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or (not cloned):
return None
if target.val == original.val == cloned.val:
return cloned
node = self.getTargetCopy(original.lef... |
class City:
name = "city"
size = "default"
draw = -1
danger = -1
population = [] | class City:
name = 'city'
size = 'default'
draw = -1
danger = -1
population = [] |
# >>> s = set("Hacker")
# >>> print s.difference("Rank")
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(set(['R', 'a', 'n', 'k']))
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(['R', 'a', 'n', 'k'])
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
# set(['a', 'c', 'r... | if __name__ == '__main__':
eng = input()
eng_stu = set(map(int, input().split()))
fre = input()
fre_stu = set(map(int, input().split()))
eng_only = eng_stu - fre_stu
print(len(eng_only)) |
SECRET_KEY = None
DB_HOST = "localhost"
DB_NAME = "kido"
DB_USERNAME = "kido"
DB_PASSWORD = "kido"
COMPRESSOR_DEBUG = False
COMPRESSOR_OFFLINE_COMPRESS = True
| secret_key = None
db_host = 'localhost'
db_name = 'kido'
db_username = 'kido'
db_password = 'kido'
compressor_debug = False
compressor_offline_compress = True |
def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1... | def consolidate(sets):
setlist = [s for s in sets if s]
for (i, s1) in enumerate(setlist):
if s1:
for s2 in setlist[i + 1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
... |
class InterpreterException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class SymbolNotFound(InterpreterException):
pass
class UnexpectedCharacter(InterpreterException):
pass
class ParserSyntaxError(InterpreterException):
... | class Interpreterexception(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class Symbolnotfound(InterpreterException):
pass
class Unexpectedcharacter(InterpreterException):
pass
class Parsersyntaxerror(InterpreterException):
... |
#! /usr/bin/env python
#
# parameters/standard.py
#
# Nick Barnes, Ravenbrook Limited, 2010-02-15
# Avi Persin, Revision 2016-01-06
"""Parameters controlling the standard GISTEMP algorithm.
Various parameters controlling each phase of the algorithm are
collected and documented here. They appear here in approximately... | """Parameters controlling the standard GISTEMP algorithm.
Various parameters controlling each phase of the algorithm are
collected and documented here. They appear here in approximately the
order in which they are used in the algorithm.
Parameters controlling cccgistemp extensions to the standard GISTEMP
algorithm, ... |
#Copyright (c) 2009-11, Walter Bender, Tony Forster
# This procedure is invoked when the user-definable block on the
# "extras" palette is selected.
# Usage: Import this code into a Python (user-definable) block; when
# this code is run, the current mouse status will be pushed to the
# FILO heap. If a mouse button ev... | def myblock(tw, x):
""" Push mouse event to stack """
if tw.mouse_flag == 1:
tw.lc.heap.append(tw.canvas.height / 2 - tw.mouse_y)
tw.lc.heap.append(tw.mouse_x - tw.canvas.width / 2)
tw.lc.heap.append(1)
tw.mouse_flag = 0
else:
tw.lc.heap.append(0) |
can_juggle = True
# The code below has problems. See if
# you can fix them!
#if can_juggle print("I can juggle!")
#else
print("I can't juggle.")
| can_juggle = True
print("I can't juggle.") |
# decompiled-by-hand & optimized
# definitely not gonna refactor this one
# 0.18s on pypy3
ip_reg = 4
reg = [0, 0, 0, 0, 0, 0]
i = 0
seen = set()
lst = []
while True:
i += 1
break_true = False
while True:
if break_true:
if i == 1:
print("1)", reg[1])
if reg[1... | ip_reg = 4
reg = [0, 0, 0, 0, 0, 0]
i = 0
seen = set()
lst = []
while True:
i += 1
break_true = False
while True:
if break_true:
if i == 1:
print('1)', reg[1])
if reg[1] in seen:
if len(lst) == 25000:
p2 = max(seen, key=lamb... |
"""Write a program that allow user enter a file name (path) then content, allow user to save it"""
filename = input("Please input filename")
f= open(filename,"w+")
content = input("Please input content")
f.write(content) | """Write a program that allow user enter a file name (path) then content, allow user to save it"""
filename = input('Please input filename')
f = open(filename, 'w+')
content = input('Please input content')
f.write(content) |
class DxlNmapOptions:
"""
Constants that are used to execute Nmap tool
+-------------+---------+----------------------------------------------------------+
| Option | Command | Description |
+=============+=========+=============================... | class Dxlnmapoptions:
"""
Constants that are used to execute Nmap tool
+-------------+---------+----------------------------------------------------------+
| Option | Command | Description |
+=============+=========+=============================... |
# See
# The configuration file should be a valid Python source file with a python extension (e.g. gunicorn.conf.py).
# https://docs.gunicorn.org/en/stable/configure.html
bind='127.0.0.1:8962'
timeout=75
daemon=True
user='user'
accesslog='/var/local/log/user/blockchain_backup.gunicorn.access.log'
errorlog='/var/l... | bind = '127.0.0.1:8962'
timeout = 75
daemon = True
user = 'user'
accesslog = '/var/local/log/user/blockchain_backup.gunicorn.access.log'
errorlog = '/var/local/log/user/blockchain_backup.gunicorn.error.log'
log_level = 'debug'
capture_output = True
max_requests = 3
workers = 1 |
size = 5
m = (2 * size)-2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
m = m - 1
for j in range(0, i + 1):
if(m%2!=0):
print("*", end=" ")
print("") | size = 5
m = 2 * size - 2
for i in range(0, size):
for j in range(0, m):
print(end=' ')
m = m - 1
for j in range(0, i + 1):
if m % 2 != 0:
print('*', end=' ')
print('') |
__version__ = '2.0.0'
__description__ = 'Sample for calculations with data from the ctrlX Data Layer'
__author__ = 'Fantastic Python Developers'
__licence__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG' | __version__ = '2.0.0'
__description__ = 'Sample for calculations with data from the ctrlX Data Layer'
__author__ = 'Fantastic Python Developers'
__licence__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG' |
__all__ = (
'readonly_admin',
'singleton'
)
| __all__ = ('readonly_admin', 'singleton') |
integer = [
['lld', 'long long', 9223372036854775807, -9223372036854775808],
['ld', 'long', 9223372036854775807, -9223372036854775808],
['lu', 'unsigned long', 18446744073709551615, 0],
['d', 'signed', 2147483647, -2147483648],
['u', 'unsigned', 4294967295, 0],
['hd', 'short', 32767, -32768],
... | integer = [['lld', 'long long', 9223372036854775807, -9223372036854775808], ['ld', 'long', 9223372036854775807, -9223372036854775808], ['lu', 'unsigned long', 18446744073709551615, 0], ['d', 'signed', 2147483647, -2147483648], ['u', 'unsigned', 4294967295, 0], ['hd', 'short', 32767, -32768], ['hu', 'unsigned short', 65... |
#!/usr/bin/env python
#
# Create filter taps to use for interpolation filter in
# clock recovery algorithm. These taps are copied from
# GNU Radio at gnuradio/filter/interpolator_taps.h.
#
# This file includes them in natural order and I want
# them stored in reversed order such that they can be
# used directly.
#
fil... | filters = [[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [-0.0001547, 0.000853777, -0.00276968, 0.00789295, 0.998534, -0.00541054, 0.00124642, -0.000198993], [-0.000309412, 0.00170888, -0.00555134, 0.015884, 0.996891, -0.0107209, 0.00247942, -0.000396391], [-0.000464053, 0.00256486, -0.00834364, 0.0239714, 0.995074, -0.015... |
class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class DoublyLinkedList:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if c... | class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class Doublylinkedlist:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if c... |
class Combo():
def combine(self,n, k):
A = list(range(1,n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
remLst = A[i + 1:]
for p in se... | class Combo:
def combine(self, n, k):
a = list(range(1, n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
rem_lst = A[i + 1:]
for p in ... |
f = open('./day4.py')
for chunk in iter(lambda :f.read(10),''):
print(chunk)
| f = open('./day4.py')
for chunk in iter(lambda : f.read(10), ''):
print(chunk) |
class WebsiteBaseError(Exception):
pass
class TreeTraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
self.tree, self.request, self.segment, self.req = tree, request, segment, req
def __str__(self) -> str:
return f"{self.tree} > {s... | class Websitebaseerror(Exception):
pass
class Treetraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
(self.tree, self.request, self.segment, self.req) = (tree, request, segment, req)
def __str__(self) -> str:
return f"{self.tree} ... |
linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
mov, amount = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep)
| linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
(mov, amount) = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple color picker program."""
BANNER = """ .::::::::::::::::::::::::::::::::::::::::::::::::.
.. .... ..
.. ...... ... ..
... | """Simple color picker program."""
banner = " .::::::::::::::::::::::::::::::::::::::::::::::::.\n .. .... ..\n .. ...... ... ..\n |S .F.Cards.. F.... |
def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["meta"])
for turn, meta in zip(sample["dialogue"],sample["meta"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
... | def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = 'Dialogue:\n'
assert len(sample['dialogue']) == len(sample['meta'])
for (turn, meta) in zip(sample['dialogue'], sample['meta']):
prefix += f'User: {turn[0]}' + '\n'
if with_knowledge:
if len(meta) > 0:
... |
# Test cases that are expected to fail, e.g. unimplemented features or bug-fixes.
# Remove from list when fixed.
xfail = {
"namespace_keywords", # 70
"googletypes_struct", # 9
"googletypes_value", # 9
"import_capitalized_package",
"example", # This is the example in the readme. Not a test.
}
se... | xfail = {'namespace_keywords', 'googletypes_struct', 'googletypes_value', 'import_capitalized_package', 'example'}
services = {'googletypes_response', 'googletypes_response_embedded', 'service', 'service_separate_packages', 'import_service_input_message', 'googletypes_service_returns_empty', 'googletypes_service_return... |
class Settings:
BOT_KEY = ""
HOST_NAME = "127.0.0.1"
USER_NAME = "root"
USER_PASS = "Andrey171200"
SQL_NAME = "moneysaver"
| class Settings:
bot_key = ''
host_name = '127.0.0.1'
user_name = 'root'
user_pass = 'Andrey171200'
sql_name = 'moneysaver' |
{
"targets": [
{
"target_name": "binding",
"sources": [
"native\\winhttpBindings.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"libraries": [
"WinHTTP.lib",
"-DelayLoad:node.exe"
],
"msbuild_settings": {
"ClCompile"... | {'targets': [{'target_name': 'binding', 'sources': ['native\\winhttpBindings.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': ['WinHTTP.lib', '-DelayLoad:node.exe'], 'msbuild_settings': {'ClCompile': {'RuntimeLibrary': 'MultiThreaded'}}}]} |
def open_file():
while True:
file_name = input("Enter input file: ")
try:
measles = open(file_name, "r")
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue # name it re-prompts for a write name
return ... | def open_file():
while True:
file_name = input('Enter input file: ')
try:
measles = open(file_name, 'r')
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue
return measles
def process_file(measles):
... |
def get_obj1():
obj = \
{
"sha": "d25341478381063d1c76e81b3a52e0592a7c997f",
"commit": {
"author": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"committer": {
"name": "Stephen Dolan",
... | def get_obj1():
obj = {'sha': 'd25341478381063d1c76e81b3a52e0592a7c997f', 'commit': {'author': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'committer': {'name': 'Stephen Dolan', 'email': 'mu@netsoc.tcd.ie', 'date': '2013-06-22T16:30:59Z'}, 'message': 'Merge pull request #... |
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'localhost',
instrument = 'ErWIN',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink'],
notifiers = [],
)
modules = ['nicos.commands.standard']
devices = dict(
ErWIN = device('nicos.devices.instrument.Instrument',
... | description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='ErWIN', experiment='Exp', datasinks=['conssink', 'dmnsink'], notifiers=[])
modules = ['nicos.commands.standard']
devices = dict(ErWIN=device('nicos.devices.instrument.Instrument', description='ErWIN instrument', instrument='... |
# -*- coding: utf-8 -*-
"""
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the foll... | """
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the following functions to acces... |
num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3))
| num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3)) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + " -> "
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + ' -> '
... |
def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
keepgoing = True
| def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L) - 1):
if L[i] > L[i + 1]:
(L[i], L[i + 1]) = (L[i + 1], L[i])
keepgoing = True |
# Hydro settings
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
APPLICATION_NAME = 'HYDRO'
SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
# SESSION_TIMEOUT is used in validate_session_active decorator to see if the
# session is active.
SECOND = 1
MINUTE = SECOND * 60
SECONDS_IN_DAY = SECOND*86400
... | time_zone = 'UTC'
language_code = 'en-us'
application_name = 'HYDRO'
secret_key = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
second = 1
minute = SECOND * 60
seconds_in_day = SECOND * 86400
mysql_cache_db = 'cache'
mysql_stats_db = 'stats'
mysql_cache_table = 'hydro_cache_table'
cache_in_memory_key_expire ... |
def load_external_repo():
native.local_repository(
name = "ext_repo",
path = "test/external_repo/repo",
)
| def load_external_repo():
native.local_repository(name='ext_repo', path='test/external_repo/repo') |
'''
Created on May 26, 2012
@author: Charlie
'''
class MainModule01(object):
def __init__(self):
pass | """
Created on May 26, 2012
@author: Charlie
"""
class Mainmodule01(object):
def __init__(self):
pass |
#
# PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7
# Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
"""
User configuration file for the client.
"""
SERVER_ADDRESS = "127.0.0.1"
SERVER_PORT = 50000
| """
User configuration file for the client.
"""
server_address = '127.0.0.1'
server_port = 50000 |
# PROBLEM
#
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print:
#
# 'Longest substring in alphabetical order is: beggh'
#
# In case of ti... | s = 'azcbobobegghakl'
if len(s) > 1:
substring = s[0]
length = 1
bestsubstring = substring
bestlength = length
for num in range(len(s) - 1):
if s[num] <= s[num + 1]:
substring = substring + s[num + 1]
length += 1
if length > bestlength:
bes... |
mandatory = \
{
'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'],
'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inbook' : ['... | mandatory = {'article': ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'], 'book': ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'], 'booklet': ['ENTRYTYPE', 'ID', 'title', 'year'], 'conference': ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'], 'inbook': ['ENTRYTYPE', 'ID', '... |
class ParkingLot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def getS... | class Parkinglot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def get... |
class AnalyticalModelStick(AnalyticalModel,IDisposable):
"""
An element that represents a stick in the structural analytical model.
Could be one of beam,brace or column type.
"""
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAlignmentMethod(self,selector):
"""
GetA... | class Analyticalmodelstick(AnalyticalModel, IDisposable):
"""
An element that represents a stick in the structural analytical model.
Could be one of beam,brace or column type.
"""
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_alignment_method(self, selecto... |
lst1=list()
lst1.append('K')
lst1.append('A')
lst2=['U', 'S', 'H', 'I', 'K']
print(lst1+lst2)
print(lst2[0] +lst2[1]+lst1[1])
for i in lst1+lst2:
print(i)
| lst1 = list()
lst1.append('K')
lst1.append('A')
lst2 = ['U', 'S', 'H', 'I', 'K']
print(lst1 + lst2)
print(lst2[0] + lst2[1] + lst1[1])
for i in lst1 + lst2:
print(i) |
class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal =... | class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal ... |
# addition will takes place after multiplication and addition
num1 = 1 + 4 * 3 / 2;
# same as 5 * 3 /2
num2 = (1 + 4) * 3 / 2;
# same as 1+12/2
num3 = 1 + (4 * 3) / 2;
print("python follow precedence rules");
# this should produce 7.5
print(num1);
print(num2);
print(num3); | num1 = 1 + 4 * 3 / 2
num2 = (1 + 4) * 3 / 2
num3 = 1 + 4 * 3 / 2
print('python follow precedence rules')
print(num1)
print(num2)
print(num3) |
class Fruit:
def __init__(self,name,parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None ## Link to node object in graph
def find_children(self,basket): # basket is a list of Fruit objects
for fruit in basket:
if ... | class Fruit:
def __init__(self, name, parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None
def find_children(self, basket):
for fruit in basket:
if fruit.name is not self.na... |
file = open("text.txt", "r")
file2 = open("text2.txt", "w")
for data in file:
file2.write(data)
file.close()
file2.close()
| file = open('text.txt', 'r')
file2 = open('text2.txt', 'w')
for data in file:
file2.write(data)
file.close()
file2.close() |
animals = ['cat', 'dog', 'pig']
for animal in animals :
print (animal + 'would make a great pet.')
print ('All of those animals would makea great pet')
| animals = ['cat', 'dog', 'pig']
for animal in animals:
print(animal + 'would make a great pet.')
print('All of those animals would makea great pet') |
"""Exceptions of the library"""
class PyConnectError(Exception):
"""Base class for all exceptions in py_connect."""
class InvalidPowerCombination(PyConnectError):
"""Connection of different power pins."""
class MaxConnectionsError(PyConnectError):
"""Interface has exceeded it's max connections limit."... | """Exceptions of the library"""
class Pyconnecterror(Exception):
"""Base class for all exceptions in py_connect."""
class Invalidpowercombination(PyConnectError):
"""Connection of different power pins."""
class Maxconnectionserror(PyConnectError):
"""Interface has exceeded it's max connections limit."""
... |
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /... | genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav\t... |
# Copyright 2020 University of Adelaide
#
# 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 or agreed to ... | def check_inst(inst, mask, match):
return inst & mask == match
def cycles_push(inst):
if check_inst(inst, 65024, 46080):
return 1 + bin(inst & 255).count('1')
return -1
def cycles_pop(inst):
if check_inst(inst, 65024, 48128):
return 1 + bin(inst & 255).count('1')
return -1
def cyc... |
d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
# key1
# key2
# key3
for k in d.keys():
print(k)
# key1
# key2
# key3
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key... | d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
for k in d.keys():
print(k)
keys = d.keys()
print(keys)
print(type(keys))
k_list = list(d.keys())
print(k_list)
print(type(k_list))
for v in d.values():
print(v)
values = d.values()
print(values)
print(type(values))
v_list = list(d.values())
print(v... |
# Testing out some stuff with async and await
async def hello(name):
print ("hello" + name)
return "hello" + name
# We can use the await statement in coroutines to call
# coroutines as normal functions; i.e. what it implies is that
# if we runt return await func(*args) in a courtoune
# is like running r... | async def hello(name):
print('hello' + name)
return 'hello' + name
async def await_hello(func, *args):
return await func(*args)
def run(coro, *args):
try:
g = coro(*args)
g.send(None)
except StopIteration as e:
return e.value
print(run(await_hello, hello, 'wut')) |
number = int(input())
raiz = number/2
for i in range(1,20):
raiz = ((raiz ** 2) + number) / (2 * raiz)
print(raiz) | number = int(input())
raiz = number / 2
for i in range(1, 20):
raiz = (raiz ** 2 + number) / (2 * raiz)
print(raiz) |
class Item:
def __init__(self,weight,value) -> None:
self.weight=weight
self.value=value
self.ratio=value/weight
def knapsackMethod(items,capacity):
items.sort(key=lambda x: x.ratio,reverse=True)
usedCapacity=0
totalValue=0
for i in items:
if usedCapacity+i.weight<=c... | class Item:
def __init__(self, weight, value) -> None:
self.weight = weight
self.value = value
self.ratio = value / weight
def knapsack_method(items, capacity):
items.sort(key=lambda x: x.ratio, reverse=True)
used_capacity = 0
total_value = 0
for i in items:
if used... |
class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present n... | class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present n... |
#LeetCode problem 54: Spiral Matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix)==0 or len(matrix[0])==0):
return []
res=[]
rb=0
re=len(matrix)
cb=0
ce=len(matrix[0])
while(re>rb and ce>cb):
... | class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
res = []
rb = 0
re = len(matrix)
cb = 0
ce = len(matrix[0])
while re > rb and ce > cb:
for j in range(c... |
"""
Non-orthogonal Reflection
by Ira Greenberg.
Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N
is the normal, and L is the incident vector.
"""
# Position of left hand side of floor.
base1 = None
# Position of right hand side of floor.
base2 = None
# A list of subpoints along the floo... | """
Non-orthogonal Reflection
by Ira Greenberg.
Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N
is the normal, and L is the incident vector.
"""
base1 = None
base2 = None
coords = []
position = None
velocity = None
r = 6
speed = 3.5
def setup():
size(640, 360)
fill(128)
base1... |
def isPower(n):
'''
Determine if the given number is a power of some non-negative integer.
'''
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt)+1):
for b in range(2, int(sqrt)+1):
if a ** b == n:
return True
return False | def is_power(n):
"""
Determine if the given number is a power of some non-negative integer.
"""
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt) + 1):
for b in range(2, int(sqrt) + 1):
if a ** b == n:
return True
return False |
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
| fruit = ['apples', 'oranges', 'pears', 'grapes', 'blueberries']
lunch = ['pho', 'timmies', 'thai', 'burgers', 'buffet!', 'indian', 'montanas']
situations = {'fruit': fruit, 'lunch': lunch} |
__author__ = 'Brian Nguyen'
def greeting(msg):
print("We would like to say: " + msg) | __author__ = 'Brian Nguyen'
def greeting(msg):
print('We would like to say: ' + msg) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.