content stringlengths 7 1.05M |
|---|
def calculation(filepath,down,across):
with open(filepath) as file:
rows = [x.strip() for x in file.readlines()]
end = len(rows)
currentrow = 0
currentcolumn = 0
count = 0
while currentrow < (end-1):
currentrow = currentrow+down
currentcolumn = (currentcolumn+acr... |
class Student:
def __init__(self, firstname, lastname, major, gpa):
self.firstname = firstname
self.lastname = lastname
self.major = major
self.gpa = gpa
@property # property decorator # access this method as an attribute
def fullname(self):
return f'{self.firstname} {self.lastname}'
@fullname.setter # ... |
{
"targets": [
{
"target_name": "simpleTest",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest2",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest3",
"sources": [ "simpleTest.cc" ]
}
]
} |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12700.py
# Description: UVa Online Judge - 12700
# =============================================================================
def run():... |
# -*- coding: utf-8 -*-
TITLE = "SUUUUPPPEEERRR Paper Plane v01"
HOME_OPTION_PLAY = "Jouer"
HOME_OPTION_PLAY_LVL = "Niveau"
HOME_OPTION_PLAY_SHORT_LVL = "NIV"
HOME_OPTION_OPTIONS = "Options"
HOME_OPTION_OPTIONS_COLOR = "Couleur"
HOME_OPTION_OPTIONS_COLOR_BLUE = "Bleu"
HOME_OPTION_OPT... |
DEBUG = True
PORT = 5000
UPLOAD_FOLDER = 'sacapp/static/tmp'
MODEL_FOLDER = 'model/'
DRUG2ID_FILE = 'model/drug2id.txt'
GENE2ID_FILE = 'model/gene2idx.txt'
IC50_DRUGS_FILE = 'model/ic50_drugid.txt'
IC50_DRUG2ID_FILE = 'model/ic50_drug2idx.txt'
IC50_GENES_FILE = 'model/ic50_genes.txt'
PERT_DRUGS_FILE = 'model/pert_drugi... |
"""Advent of Code 2019 Day 1."""
def main(file_input='input.txt'):
masses = [int(num.strip()) for num in get_file_contents(file_input)]
needed_fuel = get_needed_fuel(masses, module_fuel)
print(f'Fuel requirement: {needed_fuel}')
needed_fuel_with_fuel_mass = get_needed_fuel(masses, module_fuel_with_fue... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Sales/Point of Sale',
'sequence': 40,
'summary': 'User-friendly PoS interface for shops and restaurants',
'description': "",
'depend... |
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
STORIES_URL = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
STORIES_UA = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.0... |
class Problem(Exception):
"""
User-visible exception
"""
def __init__(self, message, code=None, icon=':exclamation:'):
"""
:param message: The error message
:type message: str
:param code: An internal error code, for ease of testing
:type code: str|None
:... |
"""
Binary search in list.
List must be sorted.
speed - O(log2N)
"""
def binary_search(a, key):
"""
a - sorted list
key - value for search
returs: index or None
"""
left = 0
right = len(a)
while left < right:
middle = (left + right) // 2
if key < a[middle]:
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Dexter Scott Belmont"
__credits__ = [ "Dexter Scott Belmont" ]
__tags__ = [ "Maya", "Virus", "Removal" ]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Dexter Scott Belmont"
__email__ = "dexter@kerneloid.com"
__status__ = "alpha"
#jobs = cmds.sc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 17:21:13 2018
@author: gykovacs
"""
__version__= '0.3.0' |
__all__ = ['Mine']
class Mine(object):
'''A mine object.
Attributes:
x (int): the mine position in X.
y (int): the mine position in Y.
owner (int): the hero's id that owns this mine.
'''
def __init__(self, x, y):
'''Constructor.
Args:
x (in... |
INVALID_EMAIL = "invalid_email"
INVALID_EMAIL_CHANGE = "invalid_email_change"
MISSING_EMAIL = "missing_email"
MISSING_NATIONALITY = "missing_nationality"
DUPLICATE_EMAIL = "unique"
REQUIRED = "required"
INVALID_SUBSCRIBE_TO_EMPTY_EMAIL = "invalid_subscribe_to_empty_email"
|
#ARGUMENTOS OPCIONAIS
def somar(a = 0, b = 0, c = 0): #INICIALIZA COM ZERO PARA SER OPCIONAL
"""
-> Faz a soma de três valores e mostra o resultado na tela
:param a: primeiro valor
:param b: segundo valor
:param c: terceiro valor
"""
s = a + b + c
print(f'A soma vale {s}')
somar(3, 2, ... |
min_temp = None
max_temp = None
# factor = 2.25
factor = 0
HUE_MAX = 240 / 360
HUE_MIN = 0
HUE_GOOD = 120 / 360
HUE_WARNING = 50/360
HUE_DANGER = 0
#comfort ranges
TEMP_LOW = 16
TEMP_HIGH = 24
HUMIDITY_LOW = 30
HUMIDITY_HIGHT = 60 |
# C100--- python classes
class Student(object):
"""
blueprint for Student
"""
def __init__(self, nameInput, ageInput, genderInput, levelInput, gradesInput):
self.name = nameInput
self.age = ageInput
self.gender = genderInput
self.level = levelInput
self.grade... |
"""Constants for terminal formatting"""
colors = 'dark', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray'
FG_COLORS = dict(list(zip(colors, list(range(30, 38)))))
BG_COLORS = dict(list(zip(colors, list(range(40, 48)))))
STYLES = dict(list(zip(('bold', 'dark', 'underline', 'blink', 'invert'), [1,2,4,5,7])))
... |
# BEGIN LINEITEM_V2_PROP_FACTORY_FUNCTION
def quantity(storage_name): # <1> 이 argument가 프로퍼티를 어디에 저장할 지 결정
def qty_getter(instance): # <2> instance는 LineItem 객체를 가르킴
return instance.__dict__[storage_name] # <3> 그 객체에서 attribute를 직접 가져온다
def qty_setter(instance, value): # <4> instance는 LineItem 객체를... |
MAX_PIXEL_VALUE = 255
LAPLAS_FACTOR = 0.5
LAPLAS_1 = [[0,1,0],[1,-4,1],[0,1,0]]
LAPLAS_2 = [[1,1,1],[1,-8,1],[1,1,1]]
LAPLAS_3 = [[0,-1,0],[-1,4,-1],[0,-1,0]]
LAPLAS_4 = [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]
LAPLAS_5 = [[0,-1,0],[-1,5,-1],[0,-1,0]]
LAPLAS_6 = [[-1,-1,-1],[-1,9,-1],[-1,-1,-1]]
LAPLAS_7 = [[0,-1,0],[-1,LAPL... |
class ListExtension(object):
@staticmethod
def split_list_in_n_parts(my_list, number_chunks):
k, m = len(my_list) / number_chunks, len(my_list) % number_chunks
return list(my_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(number_chunks))
@staticmethod
def convert_l... |
# Violet Cube Fragment
FRAGMENT = 2434125
REWARD1 = 5062009 # red cube
REWARD2 = 5062010 # black cube
q = sm.getQuantityOfItem(FRAGMENT)
if q >= 10:
if sm.canHold(REWARD2):
sm.giveItem(REWARD2)
sm.consumeItem(FRAGMENT, 10)
else:
sm.systemMessage("Make sure you have enough space in your inventory..")
elif q >... |
num = {}
for i in range(97,123):
num[chr(i)] = i-96
L = int(input())
data = list(input().rstrip())
res = 0
M = 1234567891
for idx,val in enumerate(data):
res += (31**idx)*num[val]
res %= M
print(res) |
class f:
def __init__(self,s,i):
self.s=s;self.i=i
r=""
for _ in range(int(__import__('sys').stdin.readline())):
n=int(__import__('sys').stdin.readline())
a=__import__('sys').stdin.readline().split()
b=__import__('sys').stdin.readline().split()
o=[-1]*n
for i in range(n):
for j i... |
n = int(input())
even = 0
odd = 0
for i in range(1, n + 1):
number = int(input())
if i % 2 == 0:
even += number
else:
odd += number
if even == odd:
print(f"Yes\nSum = {even}")
else:
print(f"No\nDiff = {abs(even - odd)}")
|
def diff():
print("Diff Diff")
def patch():
print("Patch")
|
# 和 518 题相同
class Solution:
def waysToChange(self, n: int) -> int:
dp = [1] + [0] * n
coins = [25, 10, 5, 1]
for coin in coins:
for col in range(coin, n + 1):
dp[col] += dp[col - coin]
return dp[-1] % (10**9 + 7)
|
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'userprofile',
]
USER_PROFILE_MODULE = 'userprofile.Profile'
|
class Solution:
def equalSubstring(self, s: str, t: str, mx: int) -> int:
i = 0
for j in range(len(s)):
mx -= abs(ord(s[j]) - ord(t[j]))
if mx < 0:
mx += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CompressionPolicyVaultEnum(object):
"""Implementation of the 'CompressionPolicy_Vault' enum.
Specifies whether to send data to the Vault in a
compressed format.
'kCompressionNone' indicates that data is not compressed.
'kCompressionLow'... |
'''
Problem:
Given an array A of n integers, in sorted order, and an integer x,
design an O(n)-time complexity algorithm to determine whether there
are 2 integers in A whose sum is exactly x.
'''
def sum(target, x):
lookup = set()
# Build a lookup table.
for item in target:
lookup.add(x - item)
... |
# QUANTIDADE DE TINTA EMUMA DETERMINADA PAREDE
largura = float(input("Largura da parede: "))
altura = float(input("Altura da parede: "))
area_da_parede = largura * altura
tinta_em_litros = area_da_parede * 2
print("A quantidade de tinta em litros será: {:.1f}L".format(tinta_em_litros)) |
class Televisao():
def __init__(self, c):
self.ligada = False
self.canal = c
self.marca = 'SAMSUNG'
self.tamanho = '43'
def muda_canal_cima(self):
if self.canal < 50:
self.canal += 1
else:
self.canal = 1
def muda_canal_baixo(self):
... |
def test_numbers():
assert 1234 == 1234
def test_hello_world():
assert "hello" + "world" == "helloworld"
def test_foobar():
assert True
|
"""Quiz: List Indexing
Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
Remember to account for zero-... |
'''
SPDX-License-Identifier: Apache-2.0
Copyright 2021 Keylime Authors
'''
async def execute(revocation):
try:
value = revocation['hello']
print(value)
except Exception as e:
raise Exception(
"The provided dictionary does not contain the 'hello' key")
|
# local scope
def my_func():
x = 300
print(x)
def my_inner_func():
print(x)
my_inner_func()
my_func()
|
# OpenWeatherMap API Key
weather_api_key = "8915eee544f1c9b3ef5fa102f5edeb66"
# Google API Key
g_key = "AIzaSyDgD7ZgpyA4MuuVfr3Ep8G2-uCEx37joSE"
|
"""
Entradas
valor_mercancia-->float-->valor_mercancia
Salidas
cantidad_extraida_de_fondos-->float-->cantidad_fondos
cantidad_credito-->float-->cantidad_credito
banco_prestamo-->float-->banco_prestamo
"""
valor_mercancia=float(input("Digite el costo de los insumos "))
if(valor_mercancia>=5000001):
cantidad_fondos=val... |
def to_polar(x, y):
'Rectangular to polar conversion using ints scaled by 100000. Angle in degrees.'
theta = 0
for i, adj in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if y < 0 else -1
x, y, theta = x - sign*(y >> i) , y + sign*(x >> i), theta - si... |
# -*- coding: utf-8 -*-
description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(
timer = device('nicos.devices.generic.VirtualTimer',
description = 'QMesyDAQ timer',
lowlevel = True,
unit = 's',
fmtstr = '%.1f',
),
mon1 = device('nic... |
def arrayMap(f):
def app(arr):
return tuple(f(e) for e in arr)
return app
|
"""
LeetCode 163. Missing Ranges
# https://www.goodtecher.com/leetcode-163-missing-ranges/
Description
https://leetcode.com/problems/missing-ranges/
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missin... |
'''show=[]
for cont in range(0,3):
show.append(input('Digite os shows que mais gosta: ').upper())
for c,v in enumerate(show):
print(f'Artista....',(c+1))
print('=-'*30)
print(f'Os shows que mais gosta é \033[0;31m{v}\033[m')
print('=-'*30)
print('Cheguei ao final da lista')'''
#Exercicio feito para ... |
n = int(input())
arr = [int(e) for e in input().split()]
for inicio in range(1, n):
i = inicio
while i >= 1 and arr[i] < arr[i-1]:
arr[i], arr[i-1] = arr[i-1], arr[i]
i -= 1
for i in range(8):
print(arr[i], end=" ")
print()
|
def area_for_polygon(polygon):
result = 0
imax = len(polygon) - 1
for i in range(0, imax):
result += (polygon[i][1] * polygon[i + 1][0]) - (polygon[i + 1][1] * polygon[i][0])
result += (polygon[imax][1] * polygon[0][0]) - (polygon[0][1] * polygon[imax][0])
return result / 2.
def centroid_f... |
def square(): # function header
new_value=4 ** 2 # function body
print(new_value)
square()
|
num1 = int(input("Digite um número:"))
num2 = int(input("Digite outro número:"))
if num1 > num2 :
print("O número {} é maior que o {}".format(num1, num2))
elif num1 == num2:
print(("Os dois números são iguais!!"))
else:
print("O número {} é maior que o {}" .format(num2, num1)) |
#!/usr/bin/python
#-*- coding: utf-8 -*-
'''
'''
__author__ = 'wpxiao'
class Page(object):
def __init__(self,user_data,current_page,per_page_row,page_num,base_url):
'''
current_page 当前页
per_page_row 每页显示的条数
page_num 分页显示的页码数
'''
self.user_data = use... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 00:25:26 2017
@author: Roberto Piga
"""
# Paste your code into this box
# define variables like in the example, below
balance = 3329; annualInterestRate = 0.2
minimumFixed = 0
f = True
initialBalance = balance
while balance > 0:
balance = initialBa... |
class MockDbQuery(object):
def __init__(self, responses):
self.responses = responses
def get(self, method, **kws):
resp = None
if method in self.responses:
resp = self.responses[method].pop(0)
if 'validate' in resp:
checks = resp['validate']['che... |
# Dividindo valores em várias listas
'''Crie um programa que vai ler VÁRIOS NÚMEROS
e colocar em uma LISTA. Depois disso, crie DUAS
LISTAS EXTRAS que vão conter apenas os valores
PARES e os valores ÍMPARES digitados, respectivamente.
Ao final, mostre o conteúdo das TRÊS LISTAS geradas'''
numeros = []
pares = []
impare... |
_tol = 1e-5
def sim(a,b):
if (a==b):
return True
elif a == 0 or b == 0:
return False
if (a<b):
return (1-a/b)<=_tol
else:
return (1-b/a)<=_tol
def nsim(a,b):
if (a==b):
return False
elif a == 0 or b == 0:
return True
if (a<b):
return (1-a/b)>_tol
else:
return (1-b/a)>_tol
def gsim(a,b):
if ... |
class ContextMixin(object):
"""Defines a ``GET`` method that invokes :meth:`get_rendering_context()`
and returns its result to the client.
"""
def get_rendering_context(self, *args, **kwargs):
raise NotImplementedError("Subclasses must override this method.")
|
class BaseModel:
def __init__(self):
pass
def predict(self, data):
"""
Get prediction on the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
... |
# Exercício Python 087: Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna.
# C) O maior valor da segunda linha.
somap = somat = maior = 0
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for c in range(0, 3):
for j in range(0, 3):
... |
'''
Globals that are used throughout CheckAPI
'''
# Whether to output debugging statements
debug = False
# The model's current working directory
workingdir = "/"
|
#!/usr/bin/env python
"""
Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four mill... |
class SuperPalmTree:
def __init__(self, a: int, b: int, c: float):
self.a = a
self.b = b
self.c = c
def __call__(self, x):
return (self.a + self.b) * x / self.c
def unpack(self):
yield self.a
yield self.b
yield self.c
def param_tuple(self):
... |
# functions
def yes_or_no(): # Returns 'yes' or 'no' based on first letter of user input.
while True:
item = input()
if not item or item[0] not in ['y', 'n']:
print('(y)es or (n)o are valid answers')
continue
elif item[0].lower() == 'y':
return 'yes'
... |
'''
Author : MiKueen
Level : Medium
Problem Statement : Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"... |
# flake8: noqa
RESPONSE_NO_DEPS = """
{
"category": "storage",
"changelog": "created",
"created_at": "2019-05-31T20:06:53.963000Z",
"description": "Extra slots in inventory.",
"downloads_count": 4110,
"homepage": "",
"license": {
"description": "A permissive license that is short a... |
class BinaryTreeNode:
"""
This class represents a node which can be used to create a Binary Tree.
:Authors: pranaychandekar
"""
def __init__(self, data, left=None, right=None, parent=None):
"""
This method initializes a node for Binary Tree.
:param data: The data to be sto... |
# selection sorting is an in-place comparison sort
# O(N^2) time, inefficient for large datasets
# best when memory is limited
def selection_sort(lst):
''' Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other... |
def list_to_string(lst):
string = ''
for item in lst:
string = string + item
return string
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in r... |
"""
==============
Output Metrics
==============
Currently, ``vivarium`` uses the :ref:`values pipeline system <values_concept>`
to produce the results, or output metrics, from a simulation. The metrics
The component here is a normal ``vivarium`` component whose only purpose is
to provide an empty :class:`dict` as th... |
t = int(input())
for _ in range(t):
s = input()
c = 0
for i in range(len(s)-1):
if abs(ord(s[i]) - ord(s[i+1])) != 1:
c += 1
print (c)
|
# -*- coding: utf-8 -*-
""" Collection of validator methods """
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise ValueErr... |
class CheckResult:
msg: str = ""
def __init__(self, msg) -> None:
self.msg = msg
class Ok(CheckResult):
pass
class Warn(CheckResult):
pass
class Err(CheckResult):
pass
class Unk(CheckResult):
pass
class Probe:
def __init__(self, **kwargs):
for k, v in kwargs.items(... |
load(":testing.bzl", "asserts", "test_suite")
load("//maven:sets.bzl", "sets")
def new_test(env):
set = sets.new()
asserts.equals(env, 0, len(set))
set = sets.new("a", "b", "c")
asserts.equals(env, 3, len(set))
asserts.equals(env, ["a", "b", "c"], list(set))
def equality_test(env):
a = sets.ne... |
#Write a function that accepts a filename as input argument and reads the file and saves each line of the file as an element
#in a list (without the new line ("\n")character) and returns the list. Each line of the file has comma separated values
# Type your code here
def list_from_file(file_name):
# Make a connec... |
# Instruction opcodes
_CHAR = 0
_NEWLINE = 1
_FONT = 2
_COLOR = 3
_SHAKE = 4
_WAIT = 5
_CUSTOM = 6
class Graph:
def __init__(self, default_font):
self.instructions = []
self.default_font = default_font
def string(self, s):
'''Adds a string of characters to the passage.'''... |
class DummyField(object):
def __init__(self, value, **kwargs):
self.value = value
for k_, v_ in kwargs.items():
setattr(self, k_, v_)
|
class TempProps:
def __init__(self, start_temperature, grad_temperature, temperature_coefficient):
self.start_temp = start_temperature
self.grad_temp = grad_temperature
self.temp_coeff = temperature_coefficient
def __str__(self):
out_str = ""
out_str += "start temp: " +... |
def loss_gen(disc, x_fake):
"""Compute the generator loss for `x_fake` given `disc`
Args:
disc: The generator
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
ndarray: The generator loss
"""
# Loss for fake data
label_fake = 1
loss_fake = label_fake * torch.l... |
"""
2104. Sum of Subarray Ranges
Medium
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Examp... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/armor"
# docs_base_url = "https://[org_name].github.io/armor"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Armor"
|
class SmallArray():
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0 |
class ValidationError(Exception):
pass
class empty(Exception):
pass
|
# 1 and 9
TERMINAL_INDICES = [0, 8, 9, 17, 18, 26]
# dragons and winds
EAST = 27
SOUTH = 28
WEST = 29
NORTH = 30
HAKU = 31
HATSU = 32
CHUN = 33
WINDS = [EAST, SOUTH, WEST, NORTH]
HONOR_INDICES = WINDS + [HAKU, HATSU, CHUN]
FIVE_RED_MAN = 16
FIVE_RED_PIN = 52
FIVE_RED_SOU = 88
AKA_DORA_LIST = [FIVE_RED_MAN, FIVE_RED... |
# #class
class user:
def __init__(self,first_name,last_name,birth,sex): # this is the main class's (attribute)function , self is the main v
self.first_name=first_name
self.last_name=last_name
self.birth=birth
self.sex=sex
def grit(self):
print (f"name: {self.first_name}... |
class BaseCSSIException(Exception):
"""The base of all CSSI library exceptions."""
pass
class CSSIException(BaseCSSIException):
"""An exception specific to CSSI library"""
pass
|
#$Id$
class ExchangeRate:
"""This class is used to create object for Exchange rate."""
def __init__(self):
"""Initialize parameters for exchange rate."""
self.exchange_rate_id = ''
self.currency_id = ''
self.currency_code = ''
self.effective_date = ''
self.rate =... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATIC_DEBUG = DEBUG
CRISPY_FAIL_SILENTLY = not DEBUG
ADMINS = (
('Dummy', 'dummy@example.org'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'NAME': 'sdemo.db',
'ENGINE': 'django.db.backends.sqlite3',
'USER': '',
'PASSWORD': ''
}
}
#... |
"""
Reference values for the nwchem test calculations within ExPrESS
All nwchem output values are in hartrees. ExPrESS converts units to eV.
All reference energies are in eV.
"""
TOTAL_ENERGY = -2079.18666382721904
TOTAL_ENERGY_CONTRIBUTION = {
"one_electron": {
"name": "one_electron",
"value": -33... |
# -*- coding: utf-8 -*-
"""
Python implementation of Karatsuba's multiplication algorithm
"""
def karatsuba_mutiplication(x, y):
xstr = str(x)
ystr = str(y)
length = max(len(xstr), len(ystr))
if length > 1:
xstr = "0" * (length - len(xstr)) + xstr
ystr = "0" * (length - len(ystr)) +... |
def path(current, visited_small_caves, cmap):
if current == 'end':
return [[current]]
next_caves = cmap[current]
paths = []
for next_cave in next_caves:
if next_cave in visited_small_caves:
continue
if next_cave.islower():
next_visited_small_caves = visite... |
# -*- coding: utf-8 -*-
"""
Package Description.
"""
__version__ = "0.0.1"
__short_description__ = "Numpy/Pandas based module make faster data analysis"
__license__ = "MIT"
__author__ = "fuwiak"
__author_email__ = "poczta130@gmail.com"
__maintainer__ = "unknown maintainer"
__maintainer_email__ = "maintainer@example.c... |
def func1(a):
a += 1
def funct2(b):
val = 1+b
return val
return funct2(a)
print(func1(5)) |
"""
第一步 安装包 >pip install hokuyolx
运行下面示例 输出数据如下
(array([2853, 2854, 2853, ..., 147, 143, 139], dtype=uint32), 1623898425874, 0)
array中包含1080个数据0 到1079 对应-135度到135度 值为mm 0 2853对应为 -135度方向障碍物距离为2.853m
示例
###########
from hokuyolx import HokuyoLX
import matplotlib.pyplot as plt
DMAX = 10000
laser = HokuyoLX()
times... |
# You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
# The letters in J are guaranteed distinct, and all characters in J and S are letters. ... |
#identify cycles in a linked list
def has_cycle(head):
taboo_list = list()
temp = head
while temp:
if temp not in taboo_list:
taboo_list.append(temp)
temp = temp.next
else:
return 1
return 0
|
# CAN controls for MQB platform Volkswagen, Audi, Skoda and SEAT.
# PQ35/PQ46/NMS, and any future MLB, to come later.
def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled):
values = {
"SET_ME_0X3": 0x3,
"Assist_Torque": abs(apply_steer),
"Assist_Requested": lkas_enabled,
"Assis... |
#
# gambit
#
# Configuration file for gravity inversion for use by planeGravInv.py
# mesh has been made with mkGeoWithData2D.py
#
# Inversion constants:
#
# scale between misfit and regularization
mu = 1.e-14
#
# used to scale computed density. kg/m^3
rho_0 = 1.
#
# IPCG tolerance *|r| <= atol+rtol*|r0|*... |
"""Initialisation des modulesce
ce fichier est nécessaire pour pouvoir importer
directement l'ensemble des modules contenu dans ce paquet
"""
__all__ = ["fibonacci"]
|
def countWaysToChangeDigit(value):
result = 0
for i in str(value):
result += 9 - int(i)
return result
|
def product(x):
t = 1
for n in x:
t *= n
return t
|
"""
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def countRankings(arr):
# Gets initial rankings
count = 1
if len(arr) == 1:
return count
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.