content stringlengths 7 1.05M |
|---|
class Node:
def __init__(self, x: int, next: "Node" = None, random: "Node" = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: "Node") -> "Node":
if not head:
return None
node = head
new_nod... |
"""This module contains classes.
"""
class AnObject:
"""Defines an object
Args:
a (bool): This is param `a` description.
b (np.array): This is param `b` description.
Attributes:
a (bool): An attribute.
b (np.array): Another attribute.
Notes:
There's a little ... |
__all__ = ['ADMIN']
ADMIN = """from django.contrib import admin
from . import models
{% for model in fields_dict %}
@admin.register(models.{{model.name}})
class {{ model.name }}Admin(admin.ModelAdmin):
list_display = [{% for field in model.fields %}{% if field == 'id' %}'pk'{% else %}'{{field}}'{% endif %}, {% e... |
SELECT_NOTICES_FOR_RE_PACKAGE_AND_RESET_STATUS_TASK_ID = "select_notices_for_re_package_and_reset_status"
TRIGGER_WORKER_FOR_PACKAGE_BRANCH_TASK_ID = "trigger_worker_for_package_branch"
def test_selector_repackage_process_orchestrator(dag_bag):
assert dag_bag.import_errors == {}
dag = dag_bag.get_dag(dag_id="... |
def taylor(val,precision):
next = 1
total = 0
for i in range(0,precision):
posorneg = (-1) ** i
top = val ** (2 * i + 1 ) * posorneg
final = 1
for i in range(next):
final = final * (next -i)
next +=2
total += top/final
print(top,final)
... |
class Page(object):
def __init__(self, url: str, path: str, links: list, pars: list, title: str, typo: str):
self.url = url
self.path = path
self.links = links
self.pars = pars
self.title = title
self.typo= typo
def set_url(self,url):
self.url = url
d... |
# -*- coding: utf-8 -*-
"""Project metadata
Information to describe this project.
NOTE:
Be sure to "not" include any dependency here, otherwise they will need to be added to
`setup.py` as well.
To import it to `setup.py`, use `imp.load_source()` method to directly load it as a module.
"""
# The package... |
class MathUtils:
@staticmethod
def average(a, b):
return (a + b)/2
if __name__ == '__main__':
print(MathUtils.average(1, 2))
|
# Copyright (c) 2018, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
# SD-WAN vManager username and password
vManager_USERNAME = "devnetuser"
vManager_PASSWORD = "Cisco123!"
# DNA Center username and password
DNAC_USER = "devnetuser"
DNAC_PASSWORD = "Cisco123!"
# Meraki API key
MERAKI_API_KEY = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0"
# E-mail username and password
EMAIL_USERNAME =... |
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums: return []
window,res=[],[]
#window stores indices,and res stores result
for i,x in enumerate(nums):... |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
def divide_conquer(low, high, nums, target):
mid = int(low+high)/2
if nums[mid] == target:
return mid
elif nums[mid] < target:
divide_conquer(mid+1, high, nums, ta... |
class TestLogicReset:
def __init__(self,ctx):
self.ctx_=ctx
def advance(self, tms, tdi):
if ( tms ):
return self
else:
return self.ctx_.RunTestIdle
class RunTestIdle:
def __init__(self,ctx):
self.ctx_=ctx
def advance(self, tms, tdi):
if ( tms ):
return self.ctx_.SelectDR... |
# 模块的调试等级
class BFLog():
# class variable
debugLevel = 0
def __init__(self, arg):
self.arg = arg
@classmethod
def bfecho(cls, message):
if cls.debugLevel == 1:
print(message)
else:
pass
|
class Node:
def __init__(self, doc):
self.doc = doc
|
def emojiconverter(message):
words=message.split(" ")
emoji_dict={
":)":"😊",
":(":"☹️",
";)":"😉"
}
op= ""
for word in words:
op+=emoji_dict.get(word,word) + " "
return op
print("welcome to return value with function and dictionary of emoji")
message=input("> ... |
class Images:
@staticmethod
def save(data,filename):
result=""
for i in data:
result+=chr(i);
saveBytes(filename,result)
@staticmethod
def visualize(data,height,width,offsetH=0,offsetW=0,scale=1):
x=0
y=0
for elem in data:
pixel=ord... |
class printerClass():
def print_table(self, data, header):
data = list(data)
MaxLength = 0
data.insert(0, header)
for i in range(0, len(data)):
for x in data[i]:
MaxLength = len(str(x)) if MaxLength < len(str(x)) else MaxLength
print("-" * MaxL... |
class SVG_map:
"""
This class generates the svg for the API response
This class initializes itself with title, total range and progress.
It calculates the necessary measurements from these info to generate
the SVG.
Attributes
----------
__title__ : str
title of the progress-bar... |
class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longestIncreasingPath(self, matrix):
# write your code here
m = len(matrix)
if m == 0:
return 0
cache = {}
n = len(matrix[0])
ma... |
class Solution:
def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]:
lo, hi = 0, 1
n = len(A)
while True:
mid = (lo + hi) / 2
idxes = [bisect.bisect(A, num / mid) for num in A]
cnt = sum(n - idx for idx in idxes)
if cnt < K:
... |
# Search directories (list is searched downward until file is found)
# cwd is searched first by default
# Set to get resolver messages through stderr
# (helpful for observing and debugging path resolution)
# setting _more lists every path resolution attempt
resolver_debug = False
resolver_debug_more = False
fhs_dirs ... |
class Graph:
def __init__(self, vertexes: int) -> None:
self.vertexes = vertexes
self.graph = [[float("inf") for _ in range(self.vertexes)] for _ in range(self.vertexes)]
def connect(self, u: int, v: int, w: int) -> None:
self.graph[u][v] = w
def show(self, matrix: list) -> None:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 15:40:19 2018
@author: User
"""
class Airlines(object):
''' Fields: code(Str), dates(Int), price(Nat)'''
allAirlines = []
allCodes = []
allDates = []
allPrices = []
registry = []
def addAir(self, name, code, dates, price):... |
# Runtime: 40 ms, faster than 91.18% of Python3 online submissions for Find Peak Element.
# Memory Usage: 13.9 MB, less than 5.88% of Python3 online submissions for Find Peak Element.
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < righ... |
__author__ = "Lukhnos Liu and The McBopomofo Authors"
__copyright__ = "Copyright 2022 and onwards The McBopomofo Authors"
__license__ = "MIT"
HEADER = '# format org.openvanilla.mcbopomofo.sorted\n'
def convert_vks_rows_to_sorted_kvs_rows(vks_rows):
"""Converts value-key-score rows to key-value-score rows, sorte... |
# _SequenceManipulation.py
__module_name__ = "_SequenceManipulation.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
class _SequenceManipulation:
"""
Get the complement or reverse compliment of a DNA sequence.
Parameters:
-----------
sequence... |
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
new = sorted(nums1 + nums2)
if len(new)%2 == 0:
return (new[len(new)/2-1]+new[len(new)/2])/2.0
else:... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 14 00:56:21 2021
@author: Alexis
"""
perm_dict = {
"newbie":[
"/bq_user help",
"/bq_user refresh",
"/help",
"/tell",
"/chant (witchery)",
"/afk",
"/back",
"/bal (see your money)",
"/balancetop (sh... |
rows, cols = [int(x) for x in input().split()]
matrix = [[x for x in input().split()] for _ in range(rows)]
squares_found = 0
for row in range(rows - 1):
for col in range(cols - 1):
if matrix[row][col] == \
matrix[row][col + 1] == \
matrix[row + 1][col] == \
... |
str_year = input("what is your birth year:")
year = int(str_year)
age = 2020-year-1
print(f"hello, your age is {age}")
|
"""
Demonstrates a try...except statement with else and finally clauses
"""
#Prompts the user to enter a number.
line = input("Enter a number: ")
try:
#Converts the input to an int.
number = int(line)
except ValueError:
#This statement will execute if the input could not be
#converted to an int (raised a Va... |
# -*- coding: utf-8 -*-
description = 'Detector data acquisition setup'
group = 'lowlevel'
display_order = 25
includes = ['counter']
excludes = ['virtual_daq']
sysconfig = dict(
datasinks = ['kwsformat', 'yamlformat', 'binaryformat', 'livesink'],
)
tango_base = 'tango://phys.kws2.frm2:10000/kws2/'
devices = di... |
#!/usr/bin/env python3
with open('27985_B.txt') as f:
nums = list([int(x) for x in f.readlines()][1:])
r2, r7, r14 = 0, 0, 0
for num in nums:
if num % 14 == 0:
r14 = max(r14, num)
if num % 2 == 0:
r2 = max(r2, num)
if num % 7 == 0:
r7 = max(r7, num)
print(max(r2 * r7, r14 * max(nums)))
|
l = float(input('Largura da parede: '))
h = float(input('Altura da parede: '))
print('Sua parede tem a dimensão de {} x {} e área de {}{}{}m².'.format(l, h, '\033[1;4m', l*h, '\033[m'))
print('Para pintar essa parede, você precisará de {}{:.2f}{}L de tinta.'.format('\033[1;4;34m', (l*h)/2, '\033[m'))
|
# -*- coding: utf-8 -*-
"""Registry keeping track of all registered pluggable components"""
# Dictionary storying all cache policy implementations keyed by ID
CACHE_POLICY = {}
# Dictionary storying all repo storage policy implementations keyed by ID
REPO_POLICY = {}
# Dictionary storying all strategy implementation... |
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
def create_files_start_length_list(
files, func_get_nevents_in_file=None,
max_events=-1, max_events_per_run=-1,
max_files=-1, max_files_per_run=1):
files = _apply_max_files(files, max... |
# time complexity O(n^2)
def find3Numbers(A, arr_size, sum):
A.sort()
# Now fix the first element
# one by one and find the
# other two elements
for i in range(0, arr_size-2):
# To find the other two elements,
# start two index variables from
# two corners of the a... |
r = input()
s = input()
a = r.split(",")
b = s.split(",")
count = 0
k = 0
for i in range(len(b)):
count = count + int(b[k])
k += 1
for j in a:
n = j.split(":")
if count == int(n[0]):
count = int(n[1])
if count>= 100:
print("Yes"... |
# Get a list of space-separated input ints. Multiply a new input
nums = input().split()
multiplier = int(input())
result = [int(item) * multiplier for item in nums]
for item in result:
print(item, end = ' ')
print()
|
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
def win( c ):
col = [0]*3
row = [0]*3
right = 0
left = 0
total = 0
for i in range(3):
for j in range(3):
... |
def square(number):
answer = number * number
return answer # note: this is not an eror, return an answer
# main code starts here :
useNumber = input("Enter a number: ")
useNumber = float(useNumber) # convert to float
numberSquarred = square(useNumber) # call the function and save the result
print("The sequ... |
class Constants:
def __init__(self):
self.D20 = 20
self.D4 = 4
self.D6 = 6
self.D8 = 8
self.D10 = 10
self.D12 = 12
self.D100 = 100
self.CRITICALROLL = 20
self.CRITICAL = 100
self.FAILROLL = 1
self.FAIL = -100
self.ITEMAT... |
'''This is a custom layout for the WordClock widget.
Custom layouts can be created for the widget by creating a new file in the
"qtile_extras.resources.wordclock" folder.
Each layout must have the following variables:
LAYOUT: The grid layout. Must be a single string.
MAP: The mappin... |
dummy_dict = {"Yes": 1, "No": 0}
internet_dict = {"No": 0, "No internet service": 1, "Yes": 2}
train_yesno_cols = [
"Partner",
"Dependents",
"PhoneService",
"PaperlessBilling",
"Churn",
]
inference_yesno_cols = ["Partner", "Dependents", "PhoneService", "PaperlessBilling"]
internet_cols = [
"Onli... |
OKBLUE = '\033[94m'
ENDC = '\033[0m'
def search_playlist(spotifyObject, deviceID):
print()
searchQuery = input("Ok, what's their name?: ")
print()
# Get search results
searchResults = spotifyObject.search(searchQuery,50,0,"playlist")
i = 0
print(f'{OKBLUE}{"-"*126}{ENDC}')
print("{3... |
"""
06 - Faça um programa que receba do usuário um vetor com 10 posições. Em seguida deverá
ser impresso o maior e o menor elemento do vetor.
"""
vetor = []
for i in range(10):
vetor.append(int(input(f'Digite o {i} º número: ')))
print(f'Valores digitados: {vetor}')
print('Maior valor digitado:', max(vetor))
print(... |
# Um programa que converte o valor do real para dólar e vice-versa #
dol = 5.04
n = float(input('Vamos agora converter o real em dólar, me informe o valor em real: R$ '))
x = n/dol
print(f'Parabéns agora você possue: ${x:.2f} dólar(es)')
print("-.-" * 50)
w = float(input('Vamos agora converter o dólar em real, me in... |
expected_output = {
"instance": {
"65109": {
"areas": {
"0.0.0.8": {
"interfaces": {
"Loopback0": {
"ip_address": "10.169.197.254/32",
"cost": 1,
"state... |
datasetFile = open("datasets/rosalind_ba1d.txt", "r")
pattern = datasetFile.readline().strip()
genome = datasetFile.readline().strip()
def findInText(pattern, genome):
indices = []
for i in range(len(genome) - len(pattern) + 1):
if genome[i:i+len(pattern)] == pattern:
indices.append(i)
... |
#f
row=0
while row<9:
col =0
while col<10:
if (col==4 and row!=0)or (row==0 and col==5)or (row==0 and col==6)or (row==0 and col==7)or (row==4):
print("*",end=" ")
else:
print(" ",end=" ")
col +=1
row +=1
print()
|
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
default_sim_settings = {
# settings shared by example.py and benchmark.py
"max_frames": 1000,
"width": 640,
"height": 480,
... |
"""
# SINGLE NUMBER II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Exa... |
n = input('Informe seu nome\n: ')
v = float(input('\nInforme o valor da casa\n: '))
s = float(input('\nInforme sua renda\n: '))
t = int(input('\nEm quantos anos deseja fazer o financiamento\n: '))
f = v / (t*12)
if s*30/100 >= f:
print('{} informamos que:\n:Financiamento aprovado!'.format(n))
else:
print('{} i... |
class AssertRaises(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeErro... |
x=5
y=2
print('Soma')
print(x+y)
print('subtraçao')
print(x-y)
print('Multiplição')
print(x*y)
print('Divisão')
print(x/y) |
# Demo Python Dictionaries - Dictionary
'''
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a ... |
"""
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, ... |
#!/usr/bin/env python3.10
#FILE = 'test_0.txt' # sol: 1384
#FILE = 'test.txt' # sol: 4140
FILE='input.txt' # sol: 3647
def parse_input(file):
lines = []
with open(file, 'r') as f:
for line in f:
lines.append(line.rstrip())
#print(f'lines: {lines}')
return lines
def to_string(n)... |
__author__ = 'rolandh'
INFORMATION = 0
OK = 1
WARNING = 2
ERROR = 3
CRITICAL = 4
INTERACTION = 5
STATUSCODE = ["INFORMATION", "OK", "WARNING", "ERROR", "CRITICAL",
"INTERACTION"]
|
"""
Create a variable called
compnum and set the value
to 50. Ask the user to enter a
number. While their guess
is not the same as the
compnum value, tell them if
their guess is too low or too
high and ask them to have
another guess. If they enter
the same value as
compnum, display the
message “Well done, you
took [cou... |
INF = 10**9
class Edge:
def __init__(self, _source, _target, _weight):
self.source = _source
self.target = _target
self.weight = _weight
def BellmanFord(s):
dist = [INF] * n
dist[s] = 0
for i in range(n - 1):
for edge in graph:
u, v, w = edge.source, edge.target, edge.weight
if dist[u] != INF and d... |
"""
@author: acfromspace
"""
def better_fibonacci(n):
n1, n2 = 0, 1
for index in range(n):
n1, n2 = n2, n1 + n2
return n1
n = int(input("Input an integer: "))
print("better_fibonacci():", better_fibonacci(n))
|
def generate_rule_nums():
base1 = 3
base2 = 5
my_sum = 0
my_max = 10000
for i in range(1, 10000):
if i%base1 == 0 or i%base2 == 0:
my_sum += i
print(my_sum)
generate_rule_nums()
|
"""
[REF] https://docs.python.org/3/tutorial/modules.html#packages
Este arquivo nao deve ser apagado
Ele serve para que o python interprete a pasta atual como
um modulo, isto eh, uma biblioteca python. Entao podemos
importar os arquivos que estao aqui dentro como pacotes da biblioteca
usando o comando 'import'.
""" |
class Solution:
def isAlienSorted(self, words, order):
for i in range(20):
tmp = [-1 if len(word) <= i else order.index(word[i]) for word in words]
if tmp != sorted(tmp): return False
if tmp == sorted(tmp) and len(tmp) == len(set(tmp)): return True
return True
|
#!/usr/bin/python
#coding:utf8
def GC_content(s):
'''
Calculate GC content of DNA.
'''
s = s.upper()
G_content = s.count('G')
C_content = s.count('C')
ratio = (G_content + C_content) / float(len(s))
return format(ratio, '.2%')
def r_complement(s):
s = s.upper()
d... |
# Insertion sorting Algorithm
# @python
def insertion_sort(list_):
for x in range(1, len(list_)):
cursor = list_[x]
pos = x
while pos > 0 and list_[pos - 1] > cursor:
list_[pos] = list_[pos - 1]
pos = pos - 1
list_[pos] = cursor
return list_
array = [1... |
s={'A',"A",99,96.5}
print(s)
#{96.5, 99, 'A'}
print(type(s))
#<class 'set'>
#print(s[2])
#'set' object does not support indexing
#s[0]="ASIT"
#'set' object does not support item assignment
print(id(s))
s.add("ASIT")
print(s)
print(id(s))
|
dig = input('Digite algo para analisar: ')
print('O dado digitado foi {}'.format(dig))
print('Ele é do tipo {}'.format(type(dig)))
print('Só tem espaços? ', dig.isspace())
print('Ele é um numero? {}'.format(dig.isnumeric()))
print('Ele é alfanumérico? ', dig.isalnum())
print('Ele é um número decimal? {}'.format(dig.isd... |
#!/usr/bin/env python3
# Example: 1 Factorial (Recursion)
# i.e. n! = n⋅(n−1)⋅(n−2) ⋯ 3⋅2⋅1
def rec_factorial(n):
# print('n =', n)
if n == 1:
return 1 # base case of factorial
else:
return n*rec_factorial(n-1) # recursive call
print(rec_factorial(1000)) |
"""
Custom errors used by PrivacyPanda
"""
class PrivacyError(RuntimeError):
def __init__(self, message):
super().__init__(message)
|
class Solution:
def rotate(self, nums, k):
k %= len(nums)
self.reverseArray(nums, 0, len(nums)-1)
self.reverseArray(nums, 0, k-1)
self.reverseArray(nums, k, len(nums)-1)
def reverseArray(self, nums, start, end):
while start < end:
nums[start], nums[end] = num... |
def add_native_methods(clazz):
def nOpen__int__(a0, a1):
raise NotImplementedError()
def nClose__long__(a0, a1):
raise NotImplementedError()
def nGetPortCount__long__(a0, a1):
raise NotImplementedError()
def nGetPortType__long__int__(a0, a1, a2):
raise NotImplementedEr... |
# -*- coding: utf-8 -*-
"""
Implementation of simple database containing some values (coordinates and intensity - like 2D image)
@author: ssklykov
"""
class ImageDict():
"""Base class - containing a list with points (dictionary): coordinates of a point and its intensity"""
point = {} # initializer for single... |
class NetworkSegmentInterface:
def build_network_segment(self, input_nodes):
raise Exception("Not implemented error")
|
#! python3
# -*- coding: UTF-8 -*-
'''
list.py
Basics of list object.
'''
# リスト宣言 JavaScriptと同じ
squares = [1, 4, 9, 16, 25]
print(squares)
# 文字列や他シーケンスオブジェクト同様の添え字アクセスが可能。
print(squares[0])
print(squares[-1])
print(squares[-3:])
# 全リスト要素をスライスした場合は新しいリストコピーを返却する。
newSqu = squares[:]
print("Ori... |
# https://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-application
# https://dzone.com/articles/design-patterns-singleton
# https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htm
# https://code.google.com/archive/p/google-singleton-detector/... |
def rek(n):
if n == 1: return 1
if n == 0: return 1
return 4*rek(n-1)+5
print(rek(2))
print(rek(23)) |
class Camera:
@staticmethod
def take_a_picture():
print('take a picture of the view')
class Wheel:
@staticmethod
def rotate(deg):
print(f'rotate {deg}°')
@staticmethod
def move():
print('move forward')
class CuriosityFacade:
""" https://en.wikipedia.org/wiki/Curi... |
# -*- coding: utf-8 -*-
"""
@author: JulienWuthrich
"""
width = 28
height = 28
show_n_images = 5 # number of images to show during the training
batch_size = 32
z_dim = 100 # the dimension of z
learning_rate = .005
beta1 = .4 # the exponential decay rate for the 1st moment in the optimizer
epochs = 100
alpha = .01
... |
dnas = [
['pX3Eo\\]', 38, 146, 1069.71, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 253, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema_slow': 40}],
['k[3Eo\\]', 38, 146, 1030.13, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 267, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'em... |
# циклы for
i = 0
for i in range(10):
print(i)
if i == 5: break
answer = None
for i in range(10):
answer = input('Какая лучше марка автомобиля?')
if answer == 'Volvo':
print('Вы абсолютно правы')
break
for i in range(10):
if i == 9: break
if i < 3: continue
else: print(i) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Yeolar
#
class DAGNode(object):
def __init__(self, name):
self.name = name
self.nexts = set()
self.prevs = set()
self.self_dep = False
self.done = False
class DAG(object):
def __init__(self):
sel... |
# -*- coding: utf-8 -*-
description = 'TOFTOF radial collimator'
group = 'optional'
tango_base = 'tango://tofhw.toftof.frm2:10000/toftof/'
devices = dict(
rc_onoff = device('nicos.devices.tango.NamedDigitalOutput',
description = 'Activates radial collimator',
tangodevice = tango_base + 'rc/_rc_o... |
def series_ele(n):
pattern = []
for i in range(1,n):
next_element = (i**3) + i*2
pattern.append(next_element)
return pattern
if __name__ == "__main__":
input_number = int(input("Enter a number upto which you want to print the patter: "))
print(series_ele(input_number))
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Dependencies and Setup\n",
"from bs4 import BeautifulSoup\n",
"from splinter import Browser\n",
"import pandas as pd\n",
"import datetime as dt\n",
"\n",
"\n",
"# ... |
'''Faça um algoritmo que leia o nome de uma pessoa e digite "É um prazer te conhecer!". '''
nome = input('Digite o seu nome? ')
print('É um prazer te conhecer, {}!'.format(nome))
|
#! python3
# __author__ = "YangJiaHao"
# date: 2018/2/24
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cu... |
CORS_ALLOW_ORIGINS = '*' # fixme!
CORS_ALLOW_METHODS = ['GET', 'POST', 'PATH', 'DELETE']
CORS_ALLOW_HEADERS = ['*'] # fixme!
DATABASE = {
'uri': 'mongodb://localhost:27017',
'max_pool_size': 10,
'db_name': 'uaberdb',
}
|
lar = 0
sm = 0.0
while True :
st = input ('Enter a number: ')
if st == 'done':
break
try:
ft = int(st)
except:
print("Invalid input")
continue
print(ft)
num = num + 1
tot = tot + ft
print('All Done')
print(tot,num,tot/num)
|
class StateChange:
VFX = 'vfx_state'
VFX_STATE = 'vfx_state_state'
AUDIO_STATE = 'audio_state'
AUDIO_EFFECT_STATE = 'audio_effect_state'
AUTONOMY_MODIFIERS = 'autonomy_modifiers'
AWARENESS = 'awareness'
BROADCASTER = 'broadcaster'
ENVIRONMENT_SCORE = 'environment_score'
PAINTING_REV... |
"""
Author: Nathan Do
Email: nathan.dole@gmail.com
Description: Hooks for Opencart API app
"""
app_name = "opencart_api"
app_title = "Opencart API"
app_publisher = "Nathan (Hoovix Consulting Pte. Ltd.)"
app_description = "App for connecting Opencart through APIs. Updating Products, recording transactions"
app_icon = "... |
# -*- coding: utf-8 -*-
__author__ = """Chancy Kennedy"""
__email__ = 'kennedychancy+fuzzyjoin@gmail.com'
__version__ = '0.5.2'
|
class User:
"""
a class for new users and login data
"""
user_list=[]
# created instance variables to take up email,name,username and password of user
def __init__(self,email,name,username,password):
self.email=email
self.name=name
self.username=username
self.pas... |
n = int(input())
a = list(map(int, input().split()))
histogram = {}
res = 0
for i in range(n-1):
for j in range(i+1, n):
s = a[i] + a[j]
if s not in histogram:
histogram[s] = 0
histogram[s] += 1
res = max(res, histogram[s])
print(res)
|
"""
Minimum Add to Make Parentheses Valid
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a... |
# definition of U and V
class Direction(object):
def __init__(self, direction):
self.direction = direction
U = Direction('u')
V = Direction('v')
# definition of U0, U1, V0, V1 as the edges of surfaces
class Edge(object):
def __init__(self, direction, value):
self.direction = direction
... |
# -*- coding:utf-8
# 首先,創建一個待驗證用戶列表
# 和一個用於儲存已驗證用戶的空列表。
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 驗證每個用戶,直到沒有未驗證用戶為止
# 將每個經過驗證的列表都移到已驗證用戶列表中
while unconfirmed_users:
current_users = unconfirmed_users.pop()
print("Verifying user: " + current_users.title())
confirmed_users.ap... |
class TextFeaturizer(object):
"""文本特征器,用于处理或从文本中提取特征。支持字符级的令牌化和转换为令牌索引列表
:param vocab_filepath: 令牌索引转换词汇表的文件路径
:type vocab_filepath: str
"""
def __init__(self, vocab_filepath):
self._vocab_dict, self._vocab_list = self._load_vocabulary_from_file(
vocab_filepath)
def featur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.