content stringlengths 7 1.05M |
|---|
#Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
#
#For example,
#Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
mx=... |
class Animal:
def __init__(self, name1, age1):
self.name = name1
self.age = age1
def eat(self):
print("The {} can eat".format(self.name))
def run(self):
print(self.age)
def active(self):
print("All animals are active")
mamal = Animal("Dog", [34,5,2])
mamal.... |
class Solution:
def nearestValidPoint(self, x: int, y: int, points) -> int:
# not a good idea to iniatilze prev_min this way.
prev_min, index = 10 << 10, -1
abs_ = abs
for i, (xi, yi) in enumerate(points):
if xi == x:
dst = y - yi
elif yi == y:... |
'''
modifier: 01
eqtime: 12
'''
def main():
info('Jan microbone blank analysis')
if analysis_type=='blank':
info('is blank. not heating')
close(name="L", description="Microbone to Minibone")
close(name="A", description="CO2 Laser to Jan")
open(name="T", description="Mi... |
n = 1
while n < 5:
print(n * "*")
n = n + 1
while n > 0:
print(n * "*")
n = n - 1 |
'''
Notas básicas sobre escalas:
I II III IV V VI VII - Gaus
Do Re Mi Fa Sol La Si - Escala de Do Maior
0 1 2 3 4 5 6 - FoxDot
Notas sobre Acordes:
Acorde de Dó: Dó + Mi + Sol == (0, 2, 4)
Acorde de Ré: Ré + Fá + Si == (0, 2, 4)
'''
# Básico sobre os sintetizadores
print(SynthDefs) # Mostra... |
### Cell class for 2-D maze module
### Author: gdgrant
### Date: 11/6/2018
class Cell:
""" Unit cell for a square grid graph """
def __init__(self, id, adj, acc):
""" Set the cell's ID, adjacent cells, and accessible cells """
self.id = id # Number of this cell
... |
'''
@Date: 2019-12-02 20:59:38
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-12-02 21:34:50
'''
class Account:
def __init__(self, id=0, balance=100.0, annualInterestRate=0.0):
self.__id = id
self.__balance = balance
self.__annua... |
'''
列表常用操作
- 列表连接
- 获取长度
- 遍历列表
- 列表切片
- 列表排序
- 列表反转
- 查找元素
'''
def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# 循环遍历列表元素
for fruit in fruits:
print(fruit.title(), end=' ')
print()
# 列表切片
fruits2 = fruits[1:4]
print(fruits... |
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
ans = 0
maxDepth = 0
def dfs(root: Optional[TreeNode], depth: int) -> None:
nonlocal ans
nonlocal maxDepth
if not root:
return
if depth > maxDepth:
maxDepth = depth
ans = root.v... |
nome = input('Digite seu nome: ').strip()
print('Nome MAIÚSCULAS: {}'.format(nome.upper()))
print('Nome minúsculas: {}'.format(nome.lower()))
print('Qte letras sem espaços: {}'.format(len(nome)-nome.count(' ')))
print('Qte letras no primeiro nome: {} '.format(len(nome.split()[0])))
|
MESSAGE_CONTENTS_FILENAME = "text_messages/message.txt"
ORDERS_FILENAME = "user_data/orders.csv"
API_KEY = ""
ORDER_NUMBER_ROW = "Order Number"
ORDER_STATUS_ROW = "Order Status"
FIRST_NAME_ROW = "First Name (Billing)"
ORDER_ITEM_ROW = "Item Name"
NUMBER_OF_ITEMS_ROW = "Quantity"
PHONE_NUMBER_ROW = "Phone (Billing)"
wi... |
@auth.requires_login()
@auth.requires_membership('Super-Administrator')
def audit_academic():
db.academic_log.id_period.readable = False
db.academic_log.id_academic.readable = False
query = ((db.academic_log))
grid = SQLFORM.grid(query, exportclasses = None, orderby=db.academic_log.date_log... |
####
# FOR
# for iterador in range(inicio, fim, passo):
###
"""
for number in range(1, 11, 1):
print(number)
"""
for i in range (1, 11, 1):
idade = float (input ( "informe uma idade: "))
if idade >= 18:
print ("voce ja pode beber")
else:
print(" voce nao pode beber")
|
#!/usr/bin/env python
# encoding:utf8;
"""
* Author:ChenJun
* Time:2020/12/24
* description:
"""
class LRC:
@classmethod
def LRC(cls, check_str,ascii=False):
global bytes
if ascii: # 传入参数为字符串
try:
bytes = [ord(item) for item in check_str]
e... |
def replace_element(iterable_object: (list, dict),
old_value: (str, int, float, list, tuple, dict),
new_value: (str, int, float, list, tuple, dict)
) -> (list, dict):
'''
This function takes an iterable object and two values, and returns
the ... |
# Given a binary search tree (BST), find the lowest common ancestor (LCA)
# of two given nodes in the BST.
#
# According to the definition of LCA on Wikipedia: “The lowest common
# ancestor is defined between two nodes p and q as the lowest node in T
# that has both p and q as descendants (where we allow a node to be a... |
n = int(input())
s = input()
t = list(s)
s1 = []
s2 = []
for i in range(n):
s1.append([])
s2.append([])
for i in range(n):
for j in range(n):
if j < i:
s1[i].append(t[j])
else:
s2[i].append(t[j])
count = 0
com = []
slv = []
for i in range(n):
for j in range(i... |
def for_n():
"""printing small 'n' using for loop"""
for row in range(6):
for col in range(4):
if col==0 or col==3 and row not in (0,1) or row==1 and col!=3:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_n():
... |
def selection_sort(arr, n):
for i in range(0, n - 1):
min_idx = i
for j in range(i, n):
if (arr[min_idx] > arr[j]):
min_idx = j
if min_idx != i:
arr[min_idx], arr[i] = arr[i], arr[min_idx]
def print_array(arr, n):
for i in range(0, n):
pr... |
BEST_PARAMS = {
"boosting_type": "dart",
"learning_rate": 0.2,
"num_leaves": 64,
"min_child_samples": 5,
"n_estimators": 5000,
"drop_rate": 0.015,
"feature_fraction": 0.7,
"bagging_fraction": 0.8,
"n_jobs": -2,
}
|
print("The code point of symbol И = ",ord('И') )
# 1048
print("The symbol, represented by code point 1048 = ", chr(1048) )
# print("Symbols, represented by code points 9745 - 9750")
# for i in range(9745, 9751):
# print( chr(i), end=" " )
# U+0488
print("\u0418") |
def pega_id(*args):
try:
telaAtualizarProdutos = args[0]
telaErro = args[1]
cursor = args[2]
id = telaAtualizarProdutos.cod_atualizar.text()
if telaAtualizarProdutos.broto_atualizar.isChecked():
cursor.execute("select * from broto where id = %s" % id)
... |
class PetrolPump(object):
def __init__(self, petrol, distance):
self.petrol = petrol
self.distance = distance
self.nextPP = None
class CyclicLinkedList(object):
def __init__(self):
self.list = []
def add(self, petrol, distance):
newPP = PetrolPump(petrol, distance)
... |
# coding=utf-8
__author__ = 'litao'
class stockltgscore(object):
#股票代码
code = ''
#统计时间
scoredate = ''
#价格因子
priceitem = 0
#流通盘因子
ltpitem = 0.0
#业绩因子
yjitem = 0.0
#净资产因子
jzcitem = 0.0
#总股本因子
zgbitem = 0.0
#得分
score = 0.0
#所属行业
sshy = ''
#流通盘分类
... |
def greet(name):
print(f'Hello, {name}!')
def test_prints(capsys):
# call the function
greet('Escape School 2021')
# test that it wrote what we expect to stdout
captured = capsys.readouterr()
# .err would be the stderr output
assert captured.out == 'Hello, Escape School 2021!\n'
|
# -*- coding: utf-8 -*-
# Tests for the contrib/localflavor/se form fields.
tests = r"""
# Monkey-patch datetime.date
>>> import datetime
>>> class MockDate(datetime.date):
... def today(cls):
... return datetime.date(2008, 5, 14)
... today = classmethod(today)
...
>>> olddate = datetime.date
>>> datet... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
A prepared statement for optimization purpose, retrieves 'installations' based upon a 'ComInsee'
"""
def installationsParActivite():
return """
SELECT
s.ComInsee as "N° Insee",
s.ComLib as "Nom Commune",
s.ActLib as 'Activité',
s.EquNom... |
major = "0"
minor = "0"
patch = "0"
release = "dev0"
if release != "":
__version__ = f"{major}.{minor}.{patch}.{release}"
else:
__version__ = f"{major}.{minor}.{patch}"
|
"""
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
"""
__a... |
def test_features(api, wiki):
assert len(api.features) == 9
assert len(api.features['GB021'].domain) == 2
f = api.features['GB021']
assert f.description
assert f.name
assert f.patrons
assert f.id
assert 'Documentation' in api.features['GB020'].description
def test_bib(api):
assert... |
'''
Description:
Your task is to construct a building which will be a pile of n cubes.
The cube at the bottom will have a volume of n^3,
the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building.
Being given m can you find ... |
def binarySearch(arr, target):
# 在[l,r]的范围里寻找target
l, r = 0, len(arr) - 1
# 当 l = r 时,区间[l,r]依然是有效的
while l <= r:
# mid = (l + r) // 2
mid = l + (r - l) // 2
if arr[mid] == target:
return mid
elif target > arr[mid]:
l = mid + 1 # target在[mid+1,r... |
class TaskStates(object):
ENQUEUED = 'enqueued'
SUCCEEDED = 'succeeded'
FAILED = 'failed'
DELETED = 'deleted'
CHOICES = (
(ENQUEUED, 'Enqueued'),
(SUCCEEDED, 'Succeeded'),
(FAILED, 'Failed'),
(DELETED, 'Deleted'),
)
class QueueType(object):
SNS = 'sns'
... |
names = ['H','E','L','L','O']
message = f"hello {names[0]}"
print(message)
message = f"hello {names[1]}"
print(message)
message = f"hello {names[2]}"
print(message)
message = f"hello {names[3]}"
print(message)
message = f"hello {names[4]}"
print(message) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class State(object):
def __init__(self):
self.states = ['search_enemy_distance', 'get_time_left', 'get_enemy_pose','get_nearest_target',
'search_near_target','get_highest_target','go_to_target','escape']
self.transitions = [
{'t... |
class Solution:
# O(n) time | O(n) space
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
originalColor = image[sr][sc]
if originalColor == newColor:
return image
self.dfs(image, sr, sc, originalColor, newColor)
return i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 13:32:57 2020
@author: furkanaydin
"""
#starting with some tryings => this is a comment
#print() => writes anythink you want in console
#type() => give us to type of the object
# "a"+"b" = "ab" => '+' string concatanetion operators.
# two srtrin... |
ctx.addWire(name="BEL_A0", type="WIRE", x=0, y=0)
ctx.addWire(name="BEL_A1", type="WIRE", x=0, y=0)
ctx.addWire(name="BEL_Q", type="WIRE", x=0, y=0)
ctx.addPip(name="Q->A0", type="PIP", srcWire="BEL_Q", dstWire="BEL_A0", delay=ctx.getDelayFromNS(0.05), loc=Loc(0, 0, 0))
ctx.addPip(name="Q->A1", type="PIP", srcWire="BE... |
# asciiコード変換では 文字->数字 = ord() 数字->文字 = chr()
a, b = map(str, input().split())
if a == b:
print("=")
elif ord(a) < ord(b):
print("<")
else:
print(">")
|
def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
i = 0
while i < 3:
print("Works with while too")
for x in rang... |
# -*- coding: utf-8 -*-
name = 'ic_shared'
version = '1.1.9'
description = 'Icarus Shared Libraries'
authors = ['mjbonnington']
requires = [
'python-2.7+',
'plyer',
]
build_requires = [
'rezlib',
]
build_command = 'python -m build {install}'
def commands():
env.PYTHONPATH.append('{root}')
|
m=int(input())
ms=set(map(int,input().split()))
n=int(input())
ns=set(map(int,input().split()))
mns=sorted((ms.difference(ns)).union((ns.difference(ms))))
print(*mns,sep='\n') |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 如果子项目是列表和元组就展开
def list_or_tuple(item):
if isinstance(item,(list,tuple)):
return True
else:
return False
# 如果子项目是非字符串的可迭代项目则展开
def no_string_iter(item):
try:
iter(item)
except TypeError:
return False
else:
retu... |
"""Settings for the of_lldp NApp."""
FLOW_VLAN_VID = 3799
FLOW_PRIORITY = 1000
TABLE_ID = 0
POLLING_TIME = 3
FLOW_MANAGER_URL = 'http://localhost:8181/api/kytos/flow_manager/v2'
# Prefix this NApp has when using cookies
COOKIE_PREFIX = 0xab
|
def save_queens(board, col, size):
if col >= size:
return True
for i in range(size):
if is_safe(board, i, col, size):
board[i][col] = 1
if save_queens(board, col+1,size):
return True
#backtrack
board[i][col] = 0
return Fa... |
class Solution:
def minPartitions(self, n: str) -> int:
'''
32 = 11
22 = 11
11 =
82734 = 11111
71623 = 11111
60512 = 10111
50401 = 10101
40300 = 10100
30200 = 10100
20100 = 10100
10000 = 10000
'''
# coun... |
# Exercicios Listas https://wiki.python.org.br/ExerciciosListas
# Marcelo Campos de Medeiros
# Aluno UNIFIP ADS 2020
# Patos-PB, maio de 2020.
'''
13 - Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Após isto, calcule a média anual das temperaturas e mostre todas as temp... |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Using Boyer-Moore Majority Vote Algorithm
# Since we only use equality comparison, and cnt_a and cnt_b are initialized to 0
# thus initializing a and b t... |
def BF_iszscored(x):
numericThreshold = 2.2204E-16
iszscored = ((np.absolute(np.mean(x)) < numericThreshold) & (np.absolute(np.std(x)-1) < numericThreshold))
return(iszscored)
|
# terrascript/resource/poseidon/ct.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:14:51 UTC)
__all__ = []
|
#Author: ahmelq - github.com/ahmedelq
#License: MIT
def compareTriplets(a, b):
"""Rate two tuples, if a[i] > b[i] give a 1 point, b[i] > a[i] give b 1 point, give 0 otherwise"""
cmp = lambda x,y: x > y
return [sum(map(cmp, a,b)), sum(map(cmp, b, a))]
def compareTripletsSFW(a, b):
"""Same as compareTr... |
def getResNet50Init():
string = '\
layer {\n\
bottom: "image"\n\
top: "conv1"\n\
name: "conv1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 7\n\
pad: 3\n\
stride: 2\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: ... |
favorite_places = {
'znn': ['chengdu', 'shanghai', 'hangzhou'],
'yl': ['chengdu', 'huang montains'],
'other': ['xian', 'xinjiang', 'nanji']
}
for name, places in favorite_places.items():
print("\n" + name.title() + " likes the following places:")
for place in places:
print("- " + place.... |
"""Provides an indirection layer to bazel cc_rules"""
load(
"//tensorflow/core/platform/default:rules_cc.bzl",
_cc_binary = "cc_binary",
_cc_import = "cc_import",
_cc_library = "cc_library",
_cc_shared_library = "cc_shared_library",
_cc_test = "cc_test",
)
cc_binary = _cc_binary
cc_import = _c... |
def _get_method(method):
router = globals()['router']
if method.lower() == 'get':
return router.get
elif method.lower() == 'post':
return router.post
elif method.lower() == 'put':
return router.put
elif method.lower() == 'delete':
return router.delete
def register_e... |
#
# PySNMP MIB module CISCO-TAP2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TAP2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:49:44 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... |
fibo = [1, 1]
indices = range(2,10,1)
print("indices elements manquants", list(indices))
for indice in indices:
element = fibo[indice - 1] + fibo[indice - 2]
fibo.append(element)
print("suite fibonacci : " , fibo)
#affichage
indice = 0
for elem in fibo:
print("U" + str(indice), "=", elem)
indice += 1 |
"""Python code/sdk/common/constants.py."""
DEFAULT_DOMAIN = "https://api.fyndx0.de"
APPLICATION_MIN_TOKEN_LENGTH = 5
HTTP_TIMEOUT = 15
TIMEZONE = "Asia/Kolkata"
|
# @desc Evaluate the overengineered XOR gate. By Benji '24
def XOR(bool1, bool2):
value1 = bool1 or bool2
value2 = not (bool1 and bool2)
return value1 and value2
def main():
print(XOR(False, False))
print(XOR(False, True))
print(XOR(True, False))
print(XOR(True, True))
if __name__ == '_... |
# list in python
item1 = "python"
item2 = "go"
item3 = "kotlin"
item4 = "java"
myList = [item1, item2, item3, item4]
print(myList[2])
print(len(myList))
print(len(myList) -1)
isKotlinInList = "kotlin" in myList
print(isKotlinInList)
print("---------------")
myRange = range(30)
print(list(myRa... |
pkgname = "rhash"
pkgver = "1.4.2"
pkgrel = 0
build_style = "configure"
configure_args = [
"--prefix=/usr", "--sysconfdir=/etc",
"--enable-openssl", "--disable-openssl-runtime",
"--enable-lib-static", "--enable-lib-shared",
]
make_build_target = "all"
make_build_args = ["lib-shared"]
make_install_target = "... |
class FileHandler:
"""Class for handling all IO/file handling tasks."""
@staticmethod
def read_file(file_path):
"""Reads a specified file.
Args:
file_path (string): The path to the input file.
Raises:
FileNotFoundError: If file not found.
IsADi... |
class Solution:
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
acc = collections.Counter()
acc[0] = 1
total = 0
res = 0
for num in nums:
total += num
need = total - k
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
collect_ignore = ['setup.py']
|
## Configuration data
config = {
"cvs_sites": [ 'ABINGTON',
'ACTON',
'AGAWAM',
'ALLSTON',
'AMHERST',
'ARLINGTON',
'ASHLAND',
'ATHOL',
'ATTLEBORO',
... |
#
# PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-BLADES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-BLADES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. 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 License at
#
# http://www.apache... |
#This script takes a "Guide sequence" generated by CRISPR Design Tool (http://tools.genome-engineering.org)
#and generates the oligos needed for their cloning into a pX-series vector.
#Input variable: sequence_list - Is a list o tuples of strings.
#Each tuple contains the name of the sequence and the sequence.
#For mor... |
irint("Hello NYC")
print("Hello NYC")
print("Hello NYC")
print("Hello NYC")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
print("Ola Mira")
|
# https://leetcode.com/problems/reverse-linked-list/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p1 = None
while head != None:
p2 = ListNode(head.val, p1)
... |
#Faça um algoritmo que converta uma velocidade expressa em
#km/h para m/s e vice versa. Você deve criar um menu com as
#duas opções de conversão e com uma opção para finalizar o
#programa. O usuário poderá fazer quantas conversões desejar,
#sendo que o programa só será finalizado quando a opção de
#finalizar for escol... |
# for optimization
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
elif arr[mid] < x and arr[mid + 1] > x:
return mid
elif arr[mid] > x and arr[mid + 1] <= x:
return mid + 1
elif arr[mid] > x:... |
#Leia o peso de 5 pessoas e qual foi o maior e o menor peso
print('-='*10)
print('{:=^20}'.format('Desafio 55'))
print('-='*10)
maior=float(0)
menor=float(0)
for c in range (0,5):
peso=float(input('Insira o peso da {}ª pessoa: '.format(c+1)))
if c==0:
maior=peso
menor=peso
elif peso>maior:
... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
class Descriptor:
"""
Place holders for the token specifications
Descriptors are harvested by {Lexer}, the metaclass of {Scanner} subclasses, and converted
into subclasses of {Token}
"""
# pub... |
"""
74.
Write a effective algorithm that search for a target value in an m x n matrix. the matrix has the following properties.
1. Integers in each row are sorted in ascending from left to right.
2. Integers in each column are sorted in ascending from top to bottom.
Example 1:
1 4 7 11 1... |
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
def run():
number = int(input('Type ... |
def likes(names):
# your code here
textToReturn = ""
if (len(names) == 0):
textToReturn = "no one likes this"
elif (len(names) == 1):
textToReturn = str(names[0]) + " likes this"
elif (len(names) > 1 and len(names) < 4):
for name in range(0, len(names) - 1):
tex... |
d = int(input('Digite o dia que em que você nasceu: '))
m = input('Agora digite o mês: ').strip()
a = int(input('E o ano: '))
print(f'Você nasceu no dia \033[36m{d} \033[mde \033[33m{m} \033[mde \033[34m{a}!')
resposta = input('\033[30mEstá correto? ')
print('Que bom! :D') |
# -*- coding: utf-8 -*-
# Copyright 2018 Google Inc. 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
# Databricks notebook source
# MAGIC %run ./_utility-methods $lesson="6.3L"
# COMMAND ----------
DA.cleanup()
DA.init()
DA.paths.checkpoints = f"{DA.paths.working_dir}/_checkpoints"
DA.conclude_setup()
sqlContext.setConf("spark.sql.shuffle.partitions", spark.sparkContext.defaultParallelism)
|
class BaseData(object):
def __init__(self, unit):
self.unit = unit
def change_units(self, new_units):
self.unit = new_units |
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
n = len(nums)
self.sum = nums
for i in range(1, n):
self.sum[i] = self.sum[i - 1] + nums[i]
def sumRange(self, i, j):
"""
:type i: int
:type j: int... |
# User values
mock_user_id = 'u1'
mock_manager_id = 'ma1'
mock_member_id = 'me1'
# Project Values
mock_project_title = 'test project'
mock_project_description = 'this is a test project'
mock_project_tags = ['test', 'project']
# Bug Values
mock_bug_title = 'test bug'
mock_bug_description = 'this is a test bug'
mock_bu... |
# ------------------------------------------------------------------
#
# Module for testing household structure
#
# ------------------------------------------------------------------
def print_houses_and_age(fname, agents):
''' Outputs house ID | age of every agent that lives there '''
# Dict with house ID vs. a l... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 John J. Rofrano <rofrano@gmail.com>
# 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 License at
#
# https://www.apache.org/licenses/L... |
"""
Image/shape pixel constants
"""
DIM = 64
X_MIN, X_MAX = (8, 56)
ONE_QUARTER = (X_MAX - X_MIN) // 3
X_MIN_34, X_MAX_34 = (X_MIN + ONE_QUARTER, X_MAX - ONE_QUARTER)
BUFFER = 8
SIZE_MIN, SIZE_MAX = (2, 5)
MAX_PLACEMENT_ATTEMPTS = 20
MAX_DISTRACTOR_PLACEMENT_ATTEMPTS = 100
MAX_INVALIDATE_ATTEMPTS = 100
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Submission file for the python anagram exercise.
#
# v1: use sorted strings, and append anagrams to a pre-defined list
def detect_anagrams(word, candidates):
"""
Return all correct anagrams of a given word from a list of words.
Anagrams are case insensiti... |
text_file = open("test.txt", "w")
text_file.write("Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n")
text_file.close()
|
# Class ccontaining parsed input for a command
class CmdInfo:
def __init__(self, name, args, instream, outstream, background):
self.name = name
self. args = args
self.instream = instream
self.outstream = outstream
self.background = background
|
class Config(object):
DEBUG = True
# Define the database
SQLALCHEMY_DATABASE_URI = '{}://{}:{}@{}'.format('mysql+pymysql', 'root', '1234',
'192.168.10.22:3306/boilerplate')
DATABASE_CONNECT_OPTIONS = {}
SQLALCHEMY_TRACK_MODIFICATIONS = False
... |
# You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawn... |
# Automatically generated by pb2py
# fmt: off
UnexpectedMessage = 1
ButtonExpected = 2
DataError = 3
ActionCancelled = 4
PinExpected = 5
PinCancelled = 6
PinInvalid = 7
InvalidSignature = 8
ProcessError = 9
NotEnoughFunds = 10
NotInitialized = 11
PinMismatch = 12
FirmwareError = 99
|
def compoundInterest(principle, time, rate):
print("Principle is : ",principle)
print("Time is : ",time)
print("Rate is : ",rate)
A=principle*pow((1+rate/100),time)
CI=A-principle
print("compound Interest is : ",CI)
compoundInterest(1200,2,5.4)
|
# 1/17/2020
# Double LinkedList 双链表
class Node(object):
def __init__(self, item):
self.item = item
self.prev = None
self.next = None # node 属性 ==》 next ; 链接区;下一个节点的位置; node.next ;
# node1.next = node2 等号 等价于 把两个节点串联起来 ; node1.next 区域指向 node2 这个节点
# 所有的 next 区域 和 prev 区... |
def slowest(orders):
brokers_second = []
for i in range(len(orders)):
b_second = [orders[i][0]]
if i == 0:
time = orders[i][1]
b_second.append(time)
else:
time = orders[i][1] - orders[i-1][1]
b_second.append(time)
brokers_second.app... |
"""
Structures of the Shell Link Binary File Format can define strings in
fixed-length fields, strings MUST be null-terminated. If a string is smaller
than the size of the field that contains it, the bytes in the field following
the terminating null character are undefined and can have any value. The
undefined bytes MU... |
class Writer:
"""
Abstract class that encapsulates a writing a row to an output.
Subclasses should implement the "write_row" method.
"""
def write_row(self):
raise NotImplementedError |
class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
d = {}
for i in edges:
head, tail = min(i[0],i[1]), max(i[0],i[1])
if head not in d:
d[head] = deque()
d[head].append(tail)
print(d)
... |
width = int(input())
while width % 2 == 0:
text = input()
totalDots = chr(46) * (width - len(text))
halfDots = int(width / 2)
halfLen = len(text) / 2
firstDots = chr(46) * (halfDots - int(halfLen))
secondDots = chr(46) * (halfDots - int(halfLen))
if text == "END":
break
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.