content stringlengths 7 1.05M |
|---|
def f():
print("this is the f() function")
return 0
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
def fib_not_recursive(n):
x = 0
y = 1
if n == 0:
return x
elif n == 1:
return y
while n-2 >= 0:
x,y = y,x+y
n -= 1
return y
if __name__ == '__main__':
fib_generated_by_recurse = [fib(i)... |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BTreeData:
def __init__(self, n: Node, isTarget: bool):
self.n = n
self.isTarget = isTarget
class Solution:
def findSecondLargest(self, root: Node) -> Node:
return self._helper(root).n
... |
numeros = []
while True:
numeros.append(float(input("\nDigite um valor: ")))
if numeros[-1].is_integer(): numeros[-1] = int(numeros[-1])
while True:
op = input("\nQuer continuar [S/N]? ").strip().upper()
if op in ['S','N']: break
if op == 'N': break... |
__all__ = ['ImgFormat']
class ImgFormat():
JPEG = 'jpeg'
PNG = 'png'
|
#!usr/bin/env python3
# Use standard library functions to search strings for content
sample_str = "The quick brown fox jumps over the lazy dog"
# startsWith and endsWith functions
print(sample_str.startswith("The"))
print(sample_str.startswith("the"))
print(sample_str.endswith("dog"))
# the find function starts sea... |
self.description = "Install a package with an existing file matching a negated --overwrite pattern"
p = pmpkg("dummy")
p.files = ["foobar"]
self.addpkg(p)
self.filesystem = ["foobar*"]
self.args = "-U --overwrite=foobar --overwrite=!foo* %s" % p.filename()
self.addrule("!PACMAN_RETCODE=0")
self.addrule("!PKG_EXIST=... |
# @Title: 课程表 (Course Schedule)
# @Author: KivenC
# @Date: 2020-08-04 09:43:58
# @Runtime: 52 ms
# @Memory: 14.3 MB
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# 拓扑排序
# 考虑排在栈的最底层的元素,是没有任何先决条件的
# [a, b] 可用有向图表示 a <- b
# 也就是在栈的最底层, 该元... |
config_DMLPDTP2_linear = {
"lr": 0.0000001,
"target_stepsize": 0.0403226567555006,
"feedback_wd": 9.821494271391093e-05,
"lr_fb": 0.0022485520139920064,
"sigma": 0.06086642605203958,
"out_dir": "logs/STRegression/DMLPDTP2_linear",
"network_type": "DMLPDTP2",
"recurrent_input": False,
... |
'''
#list1 = ["Jiggu","JJ","gg","GG"]
tuple = ("Jiggu","JJ","gg","GG")
#for item in list1:
#print(item)
for item in tuple:
print(item)
'''
|
class DisplayUnitType(Enum,IComparable,IFormattable,IConvertible):
"""
The units and display format used to format numbers as strings. Also used for unit conversions.
enum DisplayUnitType,values: DUT_1_RATIO (182),DUT_ACRES (7),DUT_AMPERES (69),DUT_ATMOSPHERES (54),DUT_BARS (55),DUT_BRITISH_THERMAL_UNIT_PER... |
# program for check two strings are anagram or not
# https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/
# time complexity is O(n) and space is O(1)
def isAnagram(str1, str2):
if(len(str1) != len(str2)):
return False
count = 0
# sum up all the chars ascii va... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# interfaceLabels : Save and delete labels for interfaces
def get_all_interface_labels(
self,
active: bool = None,
) -> dict:
"""Get all configured interface labels. Can filter response for
active labels or inactive labels... |
''' Provides one variable __version__.
Caution: All code in here will be executed by setup.py. '''
__version__ = '0.2.2'
|
def my_name():
print("name")
# calls my_name
my_name()
def square(x):
# devuelve el valor
return x * x
n = square(5)
print(n)
# declarandro función power
# que recibe dos paramatros y los
# llamo "x" y "n".
def power(x, n):
p = 1
for i in range(n):
# p = p * x
p *= x
return p... |
class Pipe(object):
def __init__(self, function):
self.function = function
def __ror__(self, other):
return self.function(other)
def __call__(self, *args, **kwargs):
return Pipe(lambda x: self.function(x, *args, **kwargs)) |
def cprint(c):
r, i = c.real, c.imag
if r != 0:
if i > 0:
print('{:.2f} + {:.2f}i'.format(r, i))
elif i < 0:
print('{:.2f} - {:.2f}i'.format(r, abs(i)))
else:
print('{:.2f}'.format(r))
else:
if i != 0:
print('{:.2f}i'.format(i))... |
# this is the content of the HTML file which might be better
# used as a simple open.read but we need to put in the bs4....
SRC_HTML = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test Source HTML</title>
<style type="text/css">
a, b... |
"""October 5th, 2020: Write a Python function called counts that takes a list as input
and returns a dictionary of unique items in the list as keys
and the number of times each item appears as values.
So, the input ['A', 'A', 'B', 'C', 'A'] should have output {'A': 3, 'B': 1, 'C': 1} .
Your code should not depend o... |
#"__bases__" es una tupla, contiene clases (no nombres de clases)
# que son superclases directas para la clase.
#Nota: solo las clases tienen este atributo - los objetos no.
#Nota: una clase sin superclases explícitas apunta al objeto
# (una clase de Python predefinida) como su antecesor directo
class SuperUno:
pas... |
ei = 3
suu1 = int(ei)
suu2 = int(ei*ei)
suu3 = int(ei*ei*ei)
print(suu1 + suu2 + suu3)
|
# -*- coding: utf-8 -*-
# 商户会员卡服务
class CardService:
__client = None
def __init__(self, client):
self.__client = client
def upload_image(self, image_base_6_4):
"""
上传图片
:param imageBase64:上传图片
"""
return self.__client.call("eleme.card.uploadImage", {"imag... |
# Write your frequency_dictionary function here:
def frequency_dictionary(words):
freqs = {}
for word in words:
if word not in freqs:
freqs[word] = 0
freqs[word] += 1
return freqs
# Uncomment these function calls to test your function:
print(frequency_dictionary(["apple", "apple", "cat", 1]))
# sho... |
a = {}
a["ad ad asd"] = 4
b = 4
if (b is a["ad ad asd"]):
print("jaka")
else:
print ("luka")
print (str([[0, 0, 0], [0, 0, 0], [0, 0, 0]])) |
def calc_percentage_at_k(test, pred, k):
# sort scores, ascending
pred, test = zip(*sorted(zip(pred, test)))
pred, test = list(pred), list(test)
pred.reverse()
test.reverse()
# calculates number of values to consider
n_percentage = round(len(pred) * k / 100)
# check if predicted is ... |
print("Enter elements:")
arr=list(map(int,input().split()))
for i in range(1, len(arr)):
val=arr[i]
j=i-1
while j>=0 and val<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=val
print(arr)
|
class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
dp = [[0] * (m + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for left in range(i, -1, -1):
mult = multipliers[i]
... |
HOST = 'localhost'
PORT = 27017
# -- HTTP-SESSION Settings --
HTTP_SESSION_TOKEN_TIMEOUT = 0
HTTP_SESSION_TOKEN_SIZE = 24
# -- Existing Commands --
COMMANDS_UNKNOWN = ['login', 'me', 'asset', 'user', 'plugin']
COMMANDS_USER = ['login', 'user', 'me', 'asset', 'logout', 'plugin', 'document', 'following', 'followers', 'fo... |
# -*- coding: utf-8 -*-
# Scrapy settings for book_spider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/la... |
# Time: O(n)
# Space: O(n)
# mono stack, prefix sum, optimized from solution2
class Solution(object):
def totalStrength(self, strength):
"""
:type strength: List[int]
:rtype: int
"""
MOD = 10**9+7
curr = 0
prefix = [0]*(len(strength)+1)
for i in xran... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if p ... |
class CommodityModel:
def __init__(self, cid=0, name="", price=0, cm=0):
self.cid = cid
self.name = name
self.price = price
self.cm = cm
def __str__(self):
return f"商品名称是{self.name},编号是{self.cid},价格是{self.price},识别码是{self.cm}"
def __eq__(self, other):
return... |
sentence = "What is the Airspeed Velocity of an Unladen Swallow?".split()
count = {word:len(word) for word in sentence}
print(count)
|
"""Day 2 funcs"""
def interpret_instructions(instructions: str) -> list[tuple[str, int]]:
"""Reads instructions and returns a list of directions and numbers"""
ret: list[tuple[str, int]] = []
instruction_list = instructions.split("\n")
for instruction in instruction_list:
instruction_tokens = ... |
skaitli = [1, 5, 3, 9, 7, 11, 4]
skaitli2 = [5, 8, 12, 77, 44, 13]
print(skaitli)
print(skaitli[4])
sajauts_saraksts = ["Maris", 1, 2, 3, "Liepa", ["burkani", 12]]
print(sajauts_saraksts)
skaitli_kopa = skaitli + skaitli2
skaitli_kopa.sort()
print(skaitli_kopa) |
"""
Helper to get relation to extractors, questions and their weights
"""
def weight_to_string(extractor, weight_index, question: str = None):
"""
naming for a weight
:param extractor:
:param weight_index:
:return:
"""
if extractor == 'action':
if weight_index == 0:
ret... |
TIME_FORMAT = "%Y-%m-%d, %H:%M:%S"
FILE_TRAIN_DATA_STATS = "train_data_stats.txt"
FILE_EVAL_DATA_STATS = "eval_data_stats.txt"
FILE_PREV_EVAL_DATA_STATS = "prev_eval_data_stats.txt"
FILE_DATA_SCHEMA = "schema.txt"
FILE_EVAL_RESULT = "eval_result.txt"
VALIDATION_SUCCESS = "success"
VALIDATION_FAIL = "fail"
|
class Color(object):
def __init__(self, r : float, g : float, b : float):
self.r = r
self.g = g
self.b = b
def tuple(self):
return (self.r, self.g, self.b)
class Gray(Color):
# intensity bet
def __init__(self, intensity : float):
self.r = self.g = self.b = intensity
self.intensity = int... |
#
# PySNMP MIB module MPLS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:04:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
def RC(value, tolerance=5.0, power=None, package="0603",pkgcode="07"):
res = {"manufacturer": "Yageo"}
suffix = ['R', 'K', 'M']
digits = 3 if tolerance < 5 else 2
while value >= 1000:
value = value/1000.
suffix.pop(0)
suffix = suffix[0]
whole = str(int(value))
decimal = str(... |
class Animal(object):
def run(self):
print('Animal is running...')
def eat(self):
print('Animal is eating...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def __init__(self):
self.name = 'Tom'
def __str__(self):
ret... |
x = [15 ,12, 8, 8, 7, 7, 7, 6, 5, 3]
y = [10 ,25, 17, 11, 13, 17, 20, 13, 9, 15]
n = len(x)
xy = [x[i] * y[i] for i in range(n)]
x_square = [x[i] * x[i] for i in range(n)]
avg_x = sum(x) / n
avg_y = sum(y) / n
avg_xy = sum(xy) / n
avg_xsqr = sum(x_square) / n
m = ((avg_x * avg_y) - avg_xy) / (avg_x ** 2 - avg_xsqr)
c =... |
#MenuTitle: Activate all Bold instances
# -*- coding: utf-8 -*-
__doc__="""
Activate all Bold instances (and deactivates all others)
Ignores instances where custom parameter "familyName" == "Master Condensed" or "Master Wide"
"""
thisFont = Glyphs.font
Glyphs.clearLog()
Glyphs.showMacroWindow()
for instance in th... |
"""
Sorting the array into a wave-like array.
For eg: arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
"""
def convertToWave(length,array):
for i in range(0, length - length%2, 2): #swapping alternatively
temp=array[i]
array[i]=array[i+1]
array[i+1]=temp
return array
arr = list(map... |
filename_prefix = 'Rebuttal-SawyerLift-ADR'
xlabel = 'Environment steps (3M)'
ylabel = "Average Discounted Rewards"
mopa_cutoff_step = 1000000
others_cutoff_step = 2000000
max_step = 3000000
max_y_axis_value = 110
legend = False
data_key = "train_ep/rew_discounted"
bc_y_value = 34.77
plot_labels = {
"Ours": [
... |
class Credential:
"""
Class that generates new instances of users.
"""
credential_list = []
def __init__(self,credential_name,user_name,password,email):
self.credential_name = credential_name
self.user_name = user_name
self.password = password
self.email = email
... |
def say_hello():
print('Hello')
def say_goodbye():
print('Goodbye') |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# Write a program that reads the names of the two primary
# colors for mixing. If the user enters anything other than
# red, blue, or yellow, the program should display an error
# message. Otherwise, the ... |
_base_ = "./ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10_ape.py"
OUTPUT_DIR = "output/self6dpp/ssLM/ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10/glue"
DATASETS = dict(
TRAIN=("lm_real_glue_train",), TRAIN2=("lm_pbr_glue_train",), TRAIN2_RATIO=0.0, TEST=("lm_real_glue_test",)
)
MODEL = dict(
WEIGHTS="output/gd... |
class DefaultConfigurations:
@staticmethod
def get():
return {}
|
freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/asyn.py')
freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/core.py')
freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/__init__.py')
freeze('../../../../../../Micropython-Library-Development/lib... |
# Sistemas de perguntas e respostas com dicionários Python.
perg = {
'Pergunta 1': {
'pergunta':'Quanto é 2+2?',
'respostas': {'a':'1','b':'4','c':'5',},
'resposta_certa':'b',
},
'Pergunta 2': {
'pergunta':'Quanto é 3+2?',
'respostas': {'a':'4','b':'10','c':'6',},
... |
name = "Bob"
greeting = "Hello, Bob"
print(greeting)
name = "Rolf"
print(greeting)
greeting = f"Hello, {name}"
print(greeting)
# --
name = "Anne"
print(
greeting
) # This still prints "Hello, Rolf" because `greeting` was calculated earlier.
print(
f"Hello, {name}"
) # This is correct, since it uses `nam... |
"""
Brian Kerninghan - Count the number of set bits in an integer
Time Complexity - O(log n)
Key idea: n & (n-1)
"""
def count(n):
count = 0
while (n != 0):
n = n & (n-1)
count += 1
return count
#n = int(raw_input("Enter any interger \n"))
#print brian_kerninghan(n)
|
class Player:
def __init__(self, player_id: int, nickname: str, websocket, is_vip: bool = False):
self.player_id = player_id
self.nickname = nickname
self.is_vip = is_vip
self.websocket = websocket
def __repr__(self):
return 'Player({}, {})'.format(self.player_id, self.n... |
Word = "Hello"
Letters = []
for w in Word:
print(w)
if w == "e":
print("Funny")
Letters.append(w)
print(Letters)
Numbers = [1,2,3,4,5]
for l in Numbers:
print(l)
Numbers1 = []
# for num in range(10):
for num in range(-1, 13, 3):
Numbers.append(num)
prin... |
def ROTRIGHT(i: int, bits: int) -> int:
return i >> bits | i << 32 - bits
# Two Extreme Bits (8 bits)
def TEB(i: int) -> int:
return ((i & 0x80) >> 6) | (i & 1)
# Two Extreme Bits Reversed (8 bits)
def TEBR(i: int) -> int:
return (i & 0xFF) >> 7 | (i & 1) << 1
# Middles Extreme Bits (32 bits)
def MEB(... |
game = [[0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' ']]
frame_counter = 0
# Ask score for frames
for frame in game:
if frame_counter < 4:
shot_number = 0
for shot in range(2):
game[frame_counter][shot_number] = int(input(f'Score for frame {frame_counter ... |
# Prime Numbers, Sieve of Eratosthenes
def prime_list(min_num, max_num):
sieve = [True] * (max_num + 1) # Sieve of Eratosthenes
m = int(max_num ** 0.5) # sqrt(n)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i+i, max_num+1, i):
sieve[j] = False
siev... |
class Status(object):
"""This encapsulates the Twitter reply to a tweet."""
def __init__(self, status):
"""This initializes the object storing metadata."""
self._status = status
@property
def id(self):
return self._status.id
@property
def username(self):
"""Thi... |
letters = ['o', 's', 'h', 'a', 'd', 'a']
print(letters.index('h'))
print(letters.index('d'))
print(max(letters))
print(min(letters))
print(letters.count('a'))
print(letters.remove('h'))
#after remove r from the list
print(letters)
#reverse the whole list
print(letters.reverse())
print(letters) |
# DESAFIO 051
# Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostra os 10 primeiros
# termos dessa progressão.
print('=' * 30)
print(f'{"10 TERMOS DE UMA PA":^30}')
print('=' * 30)
n1 = int(input('Digite o primeiro termo da PA: '))
rz = int(input('Digite a razão da PA: '))
pr = 1
for... |
def isPalindromeLinkedList(self, head: ListNode) -> bool:
arr = []
while head:
arr.append(head.val)
head = head.next
return arr == arr[::-1] |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1020/A
def f(l):
dist = lambda a,b:a-b if a>b else b-a
global a,b
ta,fa,tb,fb = l
ht = dist(ta,tb)
if (fa>=a and fa<=b) or (fb>=a and fb<=b) or ht==0:
return ht + dist(fa,fb)
return ht + min(dist(fa,a)+dist(fb,a),dist(f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 目的: 条件分岐について学ぶためのサンプルコード
# 説明文を表示
print("0時から24時までの任意の時間を入力してみよう")
# 変数 "time" に説明文のあとに入力された文字を数値として入れる(代入)
time = int(raw_input("時間(0〜24の範囲の数字)を入力: "))
# 区切りを表示
print("------------------------------------------")
# 「変数 "time" が12より小さい」かつ「変数 "time" が0以上」のとき,「AMです!」と表... |
#!/usr/bin/env python
data = [
[
7,
[
3.50016331673, 7.37909364700, 8.02381229401, 8.01285839081,
9.77704334259, 9.15692901611, 8.73682498932, 7.93067312241
],
],
[
4.202,
[
2.06499981880, 2.08285713196, 2.18571448326, 2.1921432018... |
def solution(string, markers):
output = []
for line in string.split("\n"):
containsCommentIndicator = ""
for c in line:
if c in markers:
containsCommentIndicator = c
break
if containsCommentIndicator != "":
line = line[:line.find(containsCommentIndicator)]
line = line.rstrip(" ")
output.appe... |
__author__ = 'The dashQC_fmri developers'
__copyright__ = 'Copyright 2018, The SIMEXP lab'
__credits__ = [
'Jonathan Armoza', 'Pierre Bellec', 'Yassine Benhajali', 'Sebastian Urchs'
]
__license__ = 'MIT'
__maintainer__ = 'Sebastian Urchs'
__email__ = 'sebastian.urchs@mail.mcgill.com'
__status__ = 'Prototype'
__url... |
# -*- coding: utf-8 -*-
print("""***************
xxxxx Atmsine Hoşgeldiniz.
İşlemler;
1. Bakiye Sorgulama
2. Para Yatırma
3. Para Çekme
Kart iadesi için 'q' basın
***************
""")
bakiye = 4000
while True:
islem = input("İşlemi seçiniz: ")
if (islem == "q"):
print("Yine Bekleriz")
... |
__title__ = 'fipeapi'
__description__ = 'Python Extra Oficial API for REST Request to consult Vehicles Prices.'
__url__ = 'https://github.com/deibsoncarvalho/tabela-fipe-api'
__version__ = '0.1.0'
__author__ = 'Deibson Carvalho'
__author_email__ = 'eu@deibsoncarvalho.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Cop... |
def _update_Spr(Gp, Gr, Rpr, Spr_shape, I, B, t):
# F Reconstruction
F = np.zeros(Spr_shape)
F += np.linalg.multi_dot((Gp.T, Rpr[0], Gr))
Gk = Gp * I[:, t][:, np.newaxis]
Ik = np.reshape(I[:, t], (len(I[:, t]), 1))
bk = np.reshape(B[t, :], (1, len(B[t, :])))
F += 2*np.linalg.multi_dot((Gk.T,... |
with open("vocab_origin.txt", "r") as f:
lines = f.readlines()
for i in range(185):
lines.append("<s_{}>".format(i))
with open("vocab.txt", "w") as f:
for line in lines:
f.write(line.strip() + "\n")
|
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you
API_KEY = ""
API_SECRET_KEY = ""
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
|
# Copyright 2016 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.
UNTRIAGED = 0
TRIAGED_INCORRECT = 1
TRIAGED_CORRECT = 2
TRIAGED_UNSURE = 3
TRIAGE_STATUS_TO_DESCRIPTION = {
UNTRIAGED: 'Untriaged',
TRIAGED_INCORRE... |
#!/usr/bin/env python
Nmp = 345
nbound = [0]*1037
step = 0
for l in open('test'):
step += 1
for i in range(Nmp):
if int(l[i]) > 0:
nbound[i] += 1
for i in range(Nmp):
print ('%i %i %f' % (i+1, nbound[i], nbound[i] / float(step)))
|
def file_upload(f):
with open('static/upload/'+f.name,'wb+') as destination:
for i in f.chunks():
destination.write(i)
|
def calculate_s(data_counts, qubit_indices, pauli_bases):
number_of_data_points = 0
s = 0
#print("qubit_indices", qubit_indices)
#print("pauli_bases", pauli_bases)
#print("data_counts", data_counts.items())
# loop through indices and read measurments
for key, value in data_counts.i... |
def longest_linked_list_chain(keys, buckets, loops=10):
"""
Rolls `keys` number of random keys into `buckets` buckets
and counts the collisions.
Run `loops` number of times.
"""
for i in range(loops):
key_counts = {}
for i in range(buckets):
key_counts[i] = 0
... |
lisi = 1
lisi1 = 1
lisi2 = 2
zhangsan3 = 3
lisi3 = 3
dev = 1
|
####################################################################
# ### k8s_resource_keys.py ###
####################################################################
# ### Author: SAS Institute Inc. ###
############################################... |
'''
Create a tuple with all teams of the Brazilian Championship, in classification order.
After the show the following:
1 - The first 5 teams.
2 - The last 4 teams.
3 - A list with the teams in alphabetical order.
4 - In which position is the Chapecoense team.
'''
table = (
'RB Bragantino'... |
decimal = int(input("Decimal: "))
binary = ""
while decimal != 0:
rest = decimal % 2
binary = str(rest) + binary
decimal = decimal // 2
print ("Binary: %s" % binary) |
def swap_in_place(arr, idx1, idx2):
new_arr = arr[:]
if idx1 > len(arr) - 1 or idx2 > len(arr) - 1:
return arr
new_arr.insert(idx1, new_arr.pop(idx2))
#print(new_arr)
new_arr.insert(idx2, new_arr.pop(idx1 + 1))
return new_arr
def test_case(arr, idx1, idx2, solution, test_func):
out... |
"""
This file provides a library of music exception types that are used throughout the project to better report errors to the user.
Exception Types:
TabException - general exception type for the project used to report general errors in the tab that cannot be reported more specifically
MeasureException - caused by the... |
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
# The strategy is to iterate through the string, putting each character onto
# a specific stack, depending on its type.
# A, When we put the character onto the stack, we check to see if the one before it
# is an opposite - eg. { then }... |
""" Functions for positioning geometry """
def CheckFeasibility(newPart, candidatePositionIndex, sheet):
candidatePosition = sheet.extremePoints[candidatePositionIndex]
check = True
for i in range(2): # check if violate sheet limits
if newPart.Dim[i] + candidatePosition[i] > sheet.useableSize[i]:
check =... |
def prepare(base_class, engine):
"""
Reflect base class to current database engine.
"""
base_class.prepare(engine, reflect=True)
|
class Pattern_Twenty_Three:
'''Pattern twenty_three
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
oooo
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
... |
expected_output = {
'chassis_feature': 'V2 AC PEM',
'clei': 'IPMUP00BRB',
'desc': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM',
'device_family': 'ASR',
'device_series': '9006',
'num_line_cards': 4,
'pid': 'ASR-9006-AC-V2',
'rack_num': 0,
'sn': 'FOX1810G8LR',
'top_assy_num... |
# -*- coding: utf-8 -*-
# Busca em Largura(sem nós repetidos)
def busca_largura(tab_inicial):
fila = [tab_inicial]
filaRepet = [tab_inicial] # usada para verificar expanção de repetidos
nos_exp = 0 # numero de nós expandidos
while (len(fila) > 0):
nodoTemp = fila.pop(0) # retira do início ... |
directions_2 = [
[ 1, 0 ], [ 0, 1 ],
[ 2, 0 ], [ 0, 2 ],
[ 1, 1 ], [ 1, -1 ],
[ 3, 0 ], [ 0, 3 ],
[ 1, 2 ], [ 2, 1 ],
[ 1, -2 ], [-2, 1 ],
[ 4, 0 ], [ 0, 4 ],
[ 1, 3 ], [ 3, 1 ],
[ 1, -3 ], [-3, 1 ],
[ 2, 2 ], [ 2, -2 ],
[ 5, 0 ], [ 0, 5 ],
[ 1, 4 ... |
ALL_NODES_TYPE = '<all>'
ALL_PRIMITIVES_TYPES = '<all-primitives>'
ALL_REGION_TYPES = '<all-regions>'
ALL_CONDITIONS_TYPES = '<all-conditions>'
LOCATION_OR_WAYPOINT = '<location-or-waypoint>'
STRING_TYPE = '<string>'
NUMBER_TYPE = '<number>'
BOOLEAN_TYPE = '<boolean>'
ENUM_TYPE = '<enum>'
ARBITRARY_OBJ_TYPE = '<arbit... |
# 2021-02-08
# Emma Benjaminson
# Implementation of Linked List
# for ch2-p1 (at least)
# need init, delete methods (possibly traverse?)
# singly linked list for now
# class Node
# this will contain init method
# attribute is next which is pointer to the next node
class Node:
def __init__(self, data):
s... |
#To find first index of an element in an array.
def firstIndex(arr, si, x):
l = len(arr) #length of array.
if l == 0: #base case
return -1
if arr[si] == x: #if element is found at start index of an array then return that index.
return si
return firstIndex(arr, si+1, x) #recursive call... |
rest_api_version = 99
extensions = dict(
required_params=['training_frame', 'x'],
validate_required_params="",
set_required_params="""
parms$training_frame <- training_frame
if(!missing(x))
parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore
""",
with_model="""
model@model$aggreg... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Akumatic
#
#https://adventofcode.com/2020/day/12
def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line.strip() for line in f.readlines()]
def part1(input: list) -> int:
x, y = 0, 0
dirs = ((1,0), (0, ... |
print("Please inser the following")
print()
adjective = input("adjetive: ")
animal = input("animal: ")
verb1 = input("verb: ")
exclamation = input("exclamation: ")
verb2 = input ("verb: ")
verb3 = input("verb: ")
print()
print()
print("Your story is: ")
print()
print(f"The other day, I was really in trouble. It all sta... |
# JS console is having a very hard time running my logic,
# so I rewrote it in Python to ensure I was on the right track.
# Still trying to get JS to run the one-linerized code.
def run(input, turns):
input = input.split(',')
last = {int(n): i + 1 for (i, n) in enumerate(input)}
spoken = int(input[-1])
... |
#
# PySNMP MIB module DMTF-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DMTF-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:36:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: 15-03-for.py
@time: 18-7-1 下午10:48
@version: v1.0
"""
for i in range(10):
print("Hello, I'm little {i}.".format(i=i))
else:
print("I'm else.") # 执行完for循环后运行
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.