content stringlengths 7 1.05M |
|---|
# add (adiciona), update (atualiza), clear, discard
# union | (une)
# intersection & (todos os elementos presentes nos dois sets)
# difference - (elementos apenas no set da esquerda)
# symmetric_difference ^ (elementos que estão nos dois sets, mas não em ambos)
# diferença entre conjutos e dicionários é que o conjunto... |
# -*- coding: utf-8 -*-
# see LICENSE.rst
"""Test `~astronat.utils.data`."""
# __all__ = [
# # modules
# "",
# # functions
# "",
# # other
# "",
# ]
##############################################################################
# IMPORTS
# BUILT IN
# THIRD PARTY
# PROJECT-SPECIFIC
#####... |
INPUT_RANGE = [382345, 843167]
if __name__ == "__main__":
count = 0
for num in range(INPUT_RANGE[0], INPUT_RANGE[1]):
d1 = num // 100000
d2 = (num // 10000) % 10
d3 = (num // 1000) % 10
d4 = (num // 100) % 10
d5 = (num // 10) % 10
d6 = num % 10
... |
#
# @lc app=leetcode.cn id=15 lang=python3
#
# [15] 3sum
#
None
# @lc code=end |
# -*- coding: utf-8 -*-
__version__ = '0.4.4.4'
request_post_identifier = 'current_aldryn_blog_entry'
app_title = 'News' |
'''
URL: https://leetcode.com/problems/set-matrix-zeroes
Time complexity: O(n^2)
Space complexity: O(1)
'''
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row_zero = Fals... |
# Time: O(k * C(n, k))
# Space: O(k)
# 77
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
#
# For example,
# If n = 4 and k = 2, a solution is:
#
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
class Solution(object):
def combine(self, n, k): ... |
# each user has his own credentials file. Do not share this with other users.
username = "synqs_test" # Put here your username
password = "Cm2TXfRmXennMQ5" # and the pwd
|
#
# PySNMP MIB module POLYCOM-VIDEO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/POLYCOM-VIDEO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:32:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
def netmiko_copy(device, source='', destination='', ckwargs={}, **kwargs):
# Example of a copy subtask
if source and destination:
command = f'copy {source} {destination}'
# For Cisco as long "file prompt" is either alert or noisy this should work
# if "file prompt" is quiet tr... |
n = int(input("Enter the lowe limit : "))
m = int(input("Enter the upper limit : "))
print("The prime numbers between" , n , "and" , m, "are")
for i in range(n,m,1):
a = 0
for j in range (1,i+1,1):
if (i%j==0):
a = a+ 1
if (a==2):
print(j) |
rootDir = 'd:/projects/astronomy/gaia_dr2/'
fp = open(rootDir+'output/release/ranges.csv','r')
regions = set()
region_count = {}
line = fp.readline()
while len(line) != 0:
bits = line.strip().split(',')
if len(bits) > 1:
region,count = bits
regions.add(region)
line = fp.readline()
fp.clo... |
#! python
# Problem # : 231A
# Created on : 2019-01-14 21:19:31
def Main():
n = int(input())
cnt = 0
for i in range(0, n):
if sum(list(map(int, input().split(' ')))) > 1:
cnt += 1
else:
print(cnt)
if __name__ == '__main__':
Main()
|
def longestCommonSubstr(self, S1, S2, n, m):
# code here
dp=[[0 for j in range(m+1)]for i in range(n+1)]
for i in range(1,n+1):
for j in range(1,m+1):
if S1[i-1]==S2[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=0... |
class NonGameScreen:
def __init__(self, screen):
self.screen = screen
def draw_text(self, text, font, color, cntr):
phrase = font.render(text, 0, color)
phrase_rect = phrase.get_rect(center=cntr)
self.screen.blit(phrase, phrase_rect)
|
x = 50
y =2
dolar = 5.63
real = 1
tem_cafe = True
tem_pao = False
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x ** y)
print(x // y)
print(x % y)
print(not tem_cafe)
print(tem_cafe or tem_pao)
print(tem_cafe and tem_pao)
print(dolar > real)
print(dolar < real)
print(dolar >= real)
print(dolar <= real)
prin... |
# -*- coding: utf-8 -*-
# Copyright 2018 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
# License MIT (https://opensource.org/licenses/MIT).
def migrate(cr, version):
# Add temporary credit product column
cr.execute("ALTER TABLE product_template ADD temporary_credit_product int")
# S... |
HIGH = 0x1
LOW = 0x0
INPUT = 0x0
OUTPUT = 0x1
INPUT_PULLUP = 0x2
PI = 3.1415926535897932384626433832795
HALF_PI = 1.5707963267948966192313216916398
TWO_PI = 6.283185307179586476925286766559
DEG_TO_RAD = 0.017453292519943295769236907684886
RAD_TO_DEG = 57.295779513082320876798154814105
EULER = 2.7182818284590452353602... |
"""
Реализовать вывод информации о промежутке времени в зависимости от его продолжительности duration в секундах:
до минуты: <s> сек;
до часа: <m> мин <s> сек;
до суток: <h> час <m> мин <s> сек;
в остальных случаях: <d> дн <h> час <m> мин <s> сек.
"""
sec_in_min = 60
sec_in_hour = sec_in_min * 60 # 3600 секунд в часе... |
# def funkcijas_nosaukums(arguments1, arguments2 ...):
# darbibas, kas tiek veiktas
# iekš funkcijas ar vai bez mainīgajiem
# return atgriezama_vertiba
def sasveicinaties():
print("Labdien cienījamais klient!")
print("Lai jums veiksmīga diena.")
def sasveicinatiesv2(vards):
print("Labdien cie... |
def listUsers(actors, name='azmy', age=20):
raise NotImplementedError()
|
#
# script_globals = dict()
# script_locals = dict()
# exec(open("./npc1.py").read(), script_globals, script_locals)
#
# script_locals['touched']()
#
npc_sprite_path = "./assets/sprites/npc_male_1.png"
palette = (
(248, 112, 32), # primary - orange shirt
(0, 0, 0), # secondary - black hair
(94, 50, 18) ... |
class BaseError(Exception):
pass
class BadRequestError(BaseError):
pass
class UnauthorizedError(BaseError):
pass
class NotFoundError(BaseError):
pass
class MethodNotAllowedError(BaseError):
pass
class ConflictError(BaseError):
pass
class ServerError(BaseError):
pass
class Servi... |
# We generate all the possible powers in the given range, put each value
# into a set, and let the set count the number of unique values present.
def compute():
seen = set(a**b for a in range(2, 101) for b in range(2, 101))
return str(len(seen))
if __name__ == "__main__":
print(compute())
|
kofy = [7,
286,
200,
176,
120,
165,
206,
75,
129,
109,
123,
111,
43,
52,
99,
128,
111,
110,
98,
135,
112,
78,
118,
64,
77,
227,
93,
88,
69,
60,
34,
30,
73,
54,
45,
83,
182,
88,
75,
85,
54,
53,
89,
59,
37,
35,
38,
29,
18,
4... |
def read_properties(path: str) -> dict:
dictionary = dict()
with open(path+".properties", "r") as arguments:
for line in arguments:
temp = line.strip().replace(" ", "").replace("%20", " ").split("=")
if len(temp) == 2:
if temp[1].isdigit():
tem... |
__author__ = 'raca'
'''
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly
believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four ... |
total = 0
tot1000 = 0
menor = 0
cont = 0
barato = ' '
while True:
nome = str(input('Qual o nome do produto: '))
preço = float(input('Qual o preço do produto R$: '))
cont += 1
total += preço
if preço >= 1000:
tot1000 += 1
if cont == 1 or preço < menor:
menor = preço
barato... |
def apply_discound(price, discount):
return price * (100 - discount) / 100
# def discound_product(price):
# pass
basket = [5768.32, 4213.23, 12356, 12456]
basket_sum = sum(basket)
print(basket_sum)
basket_sum_discounted = 0
discount_1 = 7
for product in basket:
basket_sum_discounted += apply_discound(pr... |
__author__ = 'roberto'
def AddNewPlane1Curve(parent, cat_constructor, curve):
pass |
# -*- coding: utf-8 -*-
__all__ = ['get_currency', 'Currency']
_CURRENCIES = {}
def get_currency(currency_code):
"Retrieve currency by the ISO currency code."
return _CURRENCIES[currency_code]
class Currency:
"Class representing a currency, such as USD, or GBP"
__slots__ = ['code', 'name', 'symbol... |
#3Sum closest
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
ans=0
diff=10000000
for i in range(0,len(nums)-2):
#print(i)
left=i+1
right=len(nums)-1
while(left<right):
#print(... |
"""
File: caesar.py
Name:
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic sequence.
... |
class StorageNode:
"""
Filters class represents the filter data
"""
def __init__(self, id, name, location, type):
self.id = id
self.name = name
self.location = location
self.type = type |
# 04. Atomic symbols
#Split the sentence "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can". into words, and extract the first letter from the 1st, 5th, 6th, 7th, 8th, 9th, 15th, 16th, 19th words and the first two letters from the other words. Crea... |
# This comes with no warranty, implied or otherwise
# This data structure was designed to support Proportional fonts
# on Arduinos. It can however handle any ttf font that has been converted
# using the conversion program. These could be fixed width or proportional
# fonts. Individual characters do not have to b... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
if head is None:
return None
if head.next is None:
return head
now = head
_dict = ... |
def ebob_bul(say1,say2):
i=1
ebob=1
while(say1>=i and say2>=i):
if(not(say1 % 1) and not(say2 %i )):
ebob=i
i+=1
return ebob
a= int(input("sayı 1:"))
b= int(input("sayı 2:"))
print(ebob_bul(a,b)) |
tokenizer_special_cases = [
'xxbos',
'xxeos',
]
|
"""Meta Data Categories."""
class Categories:
"""Meta Data Categories."""
BIOSPECIMEN = "Biospecimen"
DEMOGRAPHICS = "Demographics"
SC_RNA_SEQ_LEVEL_1 = "ScRNA-seqLevel1"
SC_RNA_SEQ_LEVEL_2 = "ScRNA-seqLevel2"
SC_RNA_SEQ_LEVEL_3 = "ScRNA-seqLevel3"
SC_RNA_SEQ_LEVEL_4 = "ScRNA-seqLevel4"
... |
def int_exp_sin(a, w):
""" Finds the primitive integral of the function,
f(t | a, w) := C e^(at + b) sin(wt + p)
where C, b, and p are arbitrary constants. Said primitive integral, hencforth 'A_f', has the general form:
A_f = Ce^(at + b)(A sin(wt + p) + B cos(wt + p)).
Returns 'A' and 'B' found in the above ide... |
# Space : O(n)
# Time : O(n)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
hashmap = {numbers[i]: (i+1) for i in range(n)}
for i in range(n):
if target - numbers[i] in hashmap:
return [i+1, hashmap[target - num... |
# coding: utf-8
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def __init__(self):
self.dict = {} # 存放已复制的节点
def cloneGraph(self, node):
if not node:
return None
# write your code here
if node in self.dict:
... |
"""
Problem 14
==========
"""
def collatz_sequence(n):
u = n
c = 1
while u != 1:
c += 1
if u % 2 == 0:
u = u // 2
else:
u = 3 * u + 1
return c
def collatz_list_naive(N):
L = [0, 1]
for i in range(2, N):
L.append(collatz_sequence(i))
... |
GUEST_USER = {
"Properties": {
"highvalue": False,
"name": "GUEST@DOMAIN_NAME.DOMAIN_SUFFIX",
"domain": "DOMAIN_NAME.DOMAIN_SUFFIX",
"objectid": "DOMAIN_SID-501",
"distinguishedname": "CN=Guest,CN=Users,DC=DOMAIN_NAME,DC=DOMAIN_SUFFIX",
"description": "Built-in acco... |
# -*- coding: utf-8 -*-
"""
Config
"""
SECRET_KEY = 'your-secret-key'
GITLAB_URL = 'http://my-gitlab'
GITLAB_APP_ID = 'my-app-id'
GITLAB_APP_SECRET = 'my-app-secret'
|
# Define silly phrases
items = [
'Пръсни им главите, пич!',
'"ДНЕС" КЪДЕ Е?!?',
'Хедшот, хедшооот!',
'Направи ги меки!',
'Скочи им на ушите!',
'В главата, в главата!',
'Не им давай "втори шанс"!',
'Голяма "енергия"!',
'Хвани ги "натясно"!',
'Покажи им "най-доброто в мен"!',
'А уж бяха "силни, силниии"...',
... |
# -*- coding: utf-8 -*-
# @Author : ydf
# @Time : 2019/8/8 0008 9:46
"""
并发池 包括
有界队列线程池 加 错误提示
eventlet协程
gevent协程
自定义的有界队列线程池 加 错误提示,同时线程数量在任务数量少的时候可自动减少。项目中默认使用的并发方式是基于这个。
""" |
expected_output = {
"location": {
"R0 R1": {
"auto_abort_timer": "inactive",
"pkg_state": {
1: {"filename_version": "10.106.1.0.277", "state": "I", "type": "IMG"},
2: {"filename_version": "10.106.1.0.277", "state": "C", "type": "IMG"},
},
... |
#!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
# tsne
TSNE_N_COMPONENTS = 2
TSNE_DEFAULT_KEY = '2'
TSNE_DEFAULT_PERPLEXITY = 30
TSNE_THETA = 0.5
RANDOM_STATE = 0
TSNE_MAX_ITER = 1000
TSNE_STOP_LYING_ITER = 250
TSNE_MOM_SWITCH_ITER = 250
ANALYSIS_H5_TSNE_GROUP = 'tsne'
# cluster... |
if body== True:
force_vec = ass.loadasem(loads, IBC, neq) + aux.body_forces(elements, nodes, neq, DME , force_y=aux.force_y )
else:
force_vec = ass.loadasem(loads, IBC, neq) + aux.body_forces(elements, nodes, neq, DME )
UG = sol.static_sol(mat_rigidez, force_vec)
UC = pos.complete_disp(IBC, nodes, UG)
|
#!/usr/bin/python
# Filename: print_tuple.py
age = 22
myempty = ()
print(len(myempty))
a1 = ('aa',)
print(len(a1))
a2 = ('abcd')
print(len(a2),a2[3])
name = ('Swaroop')
print ('%s is %d years old' % (name, age))
print ('Why is %s playing with that python?' % name)
|
"""converted from ..\fonts\ami-ega__8x14.bin """
WIDTH = 8
HEIGHT = 14
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x18\x18\x18\x18\x18\x18\x00\x18\x18\x00\x00\x00'\
b'\x00\xcc\xcc\xcc\x48\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x36\x6c\x6c\xfe\x6c\x... |
cashed_results = {}
def calc_costs(i):
"""Memoization of the function to store results and not have to calculate them multiple times. """
global cashed_results
if i not in cashed_results:
cashed_results[i] = ((i**2) + i) / 2
return cashed_results[i]
# Parse data
with open('data.txt') as f:
... |
"""Global options for the Interactive Tables"""
"""Show the index? Possible values: True, False and 'auto'. In mode 'auto', the index is not shown
if it has no name and its content is range(N)"""
showIndex = "auto"
"""Default styling options. See https://datatables.net/manual/styling/classes"""
classes = ["display"]
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date : 2018-01-02 11:33:15
# @Author : YeHarold (1174484433@qq.com)
# @Link : https://github.com/Yeharold
def add(a,b):
c = a + b
return c
|
num = list()
while True:
valor = int(input('Digite um valor: '))
if valor not in num:
print('Valor adicionado com sucesso...')
num.append(valor)
else:
print('Valor duplicado! Não vou adcionar...')
while True:
res = str(input('Quer continuar ? [S/N] ')).upper().strip()[0] ... |
# -*- encoding:utf8 -*-
class BaseEvaluator:
def evaluate(self, candidate):
# Develop your evaluation functions
return 0
def select_best(self, candidates):
if not candidates:
return None
scored = [(c, self.evaluate(c)) for c in candidates]
best = sorted(score... |
"""Write a function that takes in a Binary Tree and returns its diameter.
The diameter of a binary tree is defined as the length of its longest path,
even if that path doesn't pass through the root of the tree.
A path is a collection of connected nodes in a tree, where no node is connected
to more than two other node... |
#
# PySNMP MIB module CISCO-WAN-MODULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-MODULE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:20:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
entrada = input('Digite qualquer coisa: ')
print(type(entrada))
print(entrada.isnumeric())
print(entrada.isalnum())
print(entrada.isalpha())
|
s = list(input())
s.pop()
sans = []
for i, char in enumerate(s):
if (i + 1) % 2:
sans.insert( len(sans) // 2,char)
else:
sans.insert( (len(sans) + 1) // 2,char)
print(''.join(sans)) |
nums = input().split()
reverse = []
while nums:
reverse.append(nums.pop())
print(" ".join(reverse)) |
article_body = "1. I thought of putting pen into book, turning dark ink\
into colorful, rainbow letters of love to express my feelings for you.\
But I figured I'd write the longest book in history. So, I thought\
to show off my love for you, then, I imagined, I'll have to bring\
the worl... |
while True:
highSchoolGrade=float(input("Please enter your highschool grade : "))
QudaratGrade= float(input("Please enter your Qudarat grade : "))
TahsiliGrade= float(input("Please enter your Tahsili grade : "))
if (highSchoolGrade > 100 or QudaratGrade > 100 or TahsiliGrade > 100):
... |
"""
Functions for computing merit of particular positions
"""
def BoundingBox(newPart, candidatePositionIndex, sheet):
candidatePosition = sheet.extremePoints[candidatePositionIndex]
X = candidatePosition[0] + newPart.Dim[0]
Y = candidatePosition[1] + newPart.Dim[1]
for i in range(len(sheet.currentPart... |
# Tic Tac Toe 보드 라인 디자인
def board(tictactoe, dimension):
for i in range(dimension):
print(' _', end = '')
for i in range(dimension):
print()
print('|', end = '')
for j in range(dimension):
print(tictactoe[i][j] + '|', end = '')
print()
# Tik Tac Toe 게임 보드의 크기 지정(... |
def bubble(arr):
for i in range(0, len(arr) - 1):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j] , arr[j+1] = arr[j+1], arr[j]
print(arr)
if __name__ == '__main__':
bubble([32,43,54,54,45,3,2,4,1,56, 9]) |
# coding=utf-8
"""
Tests for Algorithms running RL models.
"""
|
"""
Variable Assignment : we assign a value to the variable using the "=" operator.
In python we need not declare the variable before assigning to it unless like other IDEs
We needn't tell Python what type of value variable is going to refer to. In fact we can refer the variable to a different sort of thing like a st... |
Cta=650*1.10/4
print("\n\n\n 5. Paco, Diego, Joel y Anuar fueron a comer al ta’corte todos "
"consumieron lo mismo, la cuenta fue de 650 y deciden dividir la cuenta,"
"¿Cuánto deberá pagar cada uno? Tomando en cuenta que van a dejar un 10% "
"de propina por su consumo.\n")
print ("La cantidad a pagar po... |
class Node():
def __init__(self, data):
self.data = data
self.next = None
class Add():
def __init__(self):
print('Add class initialized')
# Append a node
def append(self, data):
if data is None:
print('No data received')
return
node = Nod... |
# Network Delay Time
# There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i] = (u, v, w),
# where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
# Now send a signal from node K. How long will it ta... |
DESCRIPTION = 'multiplica por 3'
def get_query():
""" Retorna um objeto query das coisas que precisam ser migradas """
raise Exception("Deu pau na query")
def migrate_one(entity):
""" Executa a migracao pra um elemento retornado pela query """
raise Exception("Deu pau na migracao")
|
Lidar = {
"LocationX": -64.0,
"LocationY": 7.0,
"LocationZ": 3.74,
"Pitch": 0,
"Yaw": 0,
"Roll": 0
}
Lidar_Town03 = {
"LocationX": -95,
"LocationY": 120,
"LocationZ": 2.74,
"Pitch": 0,
"Yaw": 0,
"Roll": 0
}
Lidar_KITTI = {
"LocationX": -93,
"... |
'''from math import trunc
num = float(input('Escreva um número: '))
print(f'O valor digitado foi {num} e a sua porção inteira é {trunc(num)}')'''
#Outra maneira:
num = float(input('Digite um número:'))
print(f'O valor digitado foi {num} e a sua porção inteira é {int(num)}')
|
n = int(input())
okay = [int(x) for x in input().split()]
a = set()
a.add(0)
counter = n
for i in range(n):
k = okay[i]
if not k in a:
counter -= 1
a.add(k)
print(counter) |
h = int(input())
cnt = 0
while h > 1:
h //= 2
cnt += 1
print(2 ** (cnt + 1) - 1)
|
'''
For your reference:
class TreeNode:
def __init__(self):
self.children = []
'''
# Perform a DFS but at each leaf perform max
# Pass along the level in recursive calls
def find_height(root):
def dfs_helper(node, level, hmax):
if not node.children:
if level >... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: 560.py
@time: 2019/6/17 23:21
@desc:
'''
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
self.count = 0
def dfs(idx, residual):
... |
def _openssl_dgst_sign_impl(ctx):
ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.executable,
substitutions = {
"{{SRC}}": ctx.file.src.short_path,
},
is_executable = True,
)
return [DefaultInfo(
runfiles = ctx.run... |
#!/bin/python
def getName(t, i):
if "location" in i:
t = t + "_"
t = t + i["location"]
if "name" in i:
t = t + "_"
t = t + i["name"]
if "unit" in i:
t = t + "_"
t = t + i["unit"]
return t
def parse(spacename,r):
lat = r["location"]["lat"]
lon... |
class InvalidBetException(Exception):
"""
Exception raised when player places an
invalid set of bets.
"""
pass |
# Databricks notebook source
# MAGIC %md
# MAGIC ## Rubric for this module
# MAGIC - Using the silver delta table(s) that were setup by your ETL module train and validate your token recommendation engine. Split, Fit, Score, Save
# MAGIC - Log all experiments using mlflow
# MAGIC - capture model parameters, signature, t... |
class Bird:
def fly(self):
raise NotImplementedError
class Eagle(Bird):
def fly(self):
print("very fast")
if __name__ == "__main__":
eagle = Eagel()
eagle.fly()
|
fib = [0, 1]
for x in range(60):
b = fib[-2] + fib[-1]
fib.append(b)
vzs = int(input())
i = [int(input()) for x in range(vzs)]
[print(f'Fib({x}) = {fib[x]}') for x in i] |
# Author: James Tam
# Version: November 2016
# Exercise 1: modifying list elements
def start():
list = [1,2,3,4]
print(list)
index = int(input("Enter index of element to change: "))
while((index<0) or (index>3)):
index = int(input("Invalid index! Enter again: ")) #here we check if the in... |
lst = ["A", "B", "C"]
item = {"key": "value"}
print(item["key"])
item2 = {"name": "Drew"}
print(item2["name"])
#dictionary can contain multiple pair of information
hero = {"name": "Iron Man", "nationality": "United States", "type": False}
item3 = {"bag": ["laptop", "usb", "food"], "pocket": [5.00, 1.00, 'gum'],
... |
"""
=== Big O Notations Rules - Drop Non Dominants ===
Drop non dominants terms since these aren't going to change significantly
the amount of operations according to the input size
In Big O, our main concern is scalability and as the input size gets larger,
then we should analyze the operations that are going to ... |
# Calculate the score for each word
# 4 letter word = 1 pt
# For a word longer than 4 letters:
# 1 pt for each letter
# A 5 letter word receives 5 pts.
# Panagrams receive 7 extra pts.
def get_word_points(word, letters):
word_len = len(word)
if word_len == 4:
points = 1
else:
points ... |
def maxSubArraySum(a,size):
max_so_far = -1000000000000000000000
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_h... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
"""
422 / 422 test cases passed.
Runtime: 28 ms
Memory Usage: 37.9 MB
"""
class Solution:
def findTarget(self, root: Option... |
WAVAX = "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"
PNG = "0x60781c2586d68229fde47564546784ab3faca982"
WETH = "0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab" # WETH.e
DAI = "0xd586e7f844cea2f87f50152665bcbc2c279d8d70" # DAI.e
USDC = "0xa7d7079b0fead91f3e65f86e8915cb59c1a4c664" # USDC.e
USDT = "0xc7198437980c041c805a1edcb... |
class Hero:
#private class variabel
__jumlah = 0;
def __init__(self,name):
self.__name = name
Hero.__jumlah += 1
# method ini hanya berlaku untuk objek
def getJumlah(self):
return Hero.__jumlah
# method ini tidak berlaku untuk objek tapi berlaku untuk class
def getJumlah1():
return Hero.__jumlah
# ... |
"""List of repositories to check."""
repolist = []
class Repositories():
"""Class representing list of repositories."""
def __init__(self, config):
"""Load list of repositories from the provided config object."""
self._repolist = config.get_repolist()
@property
def repolist(self):
... |
# TODO: přemístit do k8s configu
OAREPO_OAI_PROVIDERS = {
"nusl": {
"description": "NUŠL",
"synchronizers": [
{
"name": "marcxml",
"oai_endpoint": "http://invenio.nusl.cz/oai2d/",
"set": "global",
"metadata_prefix": "marcxml... |
'''
0, 1, 2, n-1这n个数字排成一个圆环, 从数字0开始每次从这个圆圈里删除第m个数字
求这个圆圈中最后剩下的一个数字
'''
class Solution(object):
def LastRemain(self, n, m): # 0~n-1
if n<1 or m<1:
return None
last=0
for i in range(2, n+1):
last=(last+m)%i
return last
s=Solution()
print(s.LastRemain(5, 1))
... |
class SVC:
"""C-Support Vector Classification.
The implementation is based on libsvm. The fit time scales at least
quadratically with the number of samples and may be impractical
beyond tens of thousands of samples. For large datasets
consider using :class:`sklearn.svm.LinearSVC` or
:class:`skle... |
l1 = [1,4,5,6]
l2 = l1[:]
l1.append('gern')
print(l1)
print(l2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.