content stringlengths 7 1.05M |
|---|
# Escreva um programa que leia um valor em metros e o exiba convertido em
# centimetros e milimetros.
n = float(input('Valor em metros: '))
cm = n * 100
mm = n * 1000
print('\033[7mCentimetros:{}cm\033[m\n\033[7mMilimetros:{}mm\033[m'.format(cm,mm)) |
"""
This file contains the paths to store the data and models
Must have a dataPath and resPath defined
"""
PATH = {'data': r'/hdd/ersa',
'model': r'/hdd6/Models',
'eval': r'/hdd/Results'}
|
class Node:
"""
This class represents the nodes of the different networks on the map.
"""
def __init__(self, index, edges=None, is_taxi_stop=False, is_bus_stop=False, is_metro_stop=False,
is_ferry_stop=False):
"""
Init-function of the Node-class.
:param index: Un... |
x = [1,2,3]
dict = {'name': 'Victoria', 'sister': 1, 'states': ['Texas','California', 'Nevada']}
"""
for key in dict.keys():
... print('{k}: {v}'.format(k=key, v=dict[key]))
...
states: ['Texas', 'California', 'Nevada']
sister: 1
name: Victoria
for key, value in dict.items():
... if key == 'name':
... ... |
OCTICON_UNMUTE = """
<svg class="octicon octicon-unmute" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.563 2.069A.75.75 0 018 2.75v10.5a.75.75 0 01-1.238.57L3.472 11H1.75A1.75 1.75 0 010 9.25v-2.5C0 5.784.784 5 1.75 5h1.723l3.289-2.82a.75.75 0 01.801-.111... |
# config.py
cfg_mnet = {
'name': 'mobilenet0.25',
'in_channels': 3,
'min_sizes': [[16, 32], [64, 128], [256, 512]],
'steps': [8, 16, 32],
'variance': [0.1, 0.2],
'clip': False,
'loc_weight': 2.0,
'gpu_train': True,
'batch_size': 64,
'ngpu': 1,
'epoch': 200,
'decay1': 190... |
l = list(map(int, input().split()))
minT = l[0]
maxT = l[0]
maxI = 0
minI = 0
for i in range(0, len(l)):
if minT > l[i]:
minT = l[i]
minI = i
for i in range(0, len(l)):
if maxT < l[i]:
maxT = l[i]
maxI = i
t = l[maxI]
l[maxI] = l[minI]
l[minI] = t
print(' '.join(map(str, l)))
|
def is_prime(number):
"""
>>> is_prime(3)
True
>>> is_prime(90)
False
>>> is_prime(67)
True
"""
if number <= 1:
return False
for i in range(2, number - 1):
if number % i == 0:
return False
return True
def prime_numbers(number):
"""
>>> ... |
"""
The negamax agent from the kaggle source code.
Runs faster if we turn down max_depth (originally 4, but too slow).
A very lazy reimplementation of negamax.py for depth 1,
but the kaggle env is tricky so I'm letting myself off.
"""
def negamax_agent(obs, config, depth=1):
columns = config.columns
rows = co... |
# Didn't event attempt pt 2. Here's a solution cribbed from https://www.reddit.com/r/adventofcode/comments/7irzg5/2017_day_10_solutions/dr1095j/
f = "165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153"
lengths1 = [int(x) for x in f.strip().split(",")]
lengths2 = [ord(x) for x in f.strip()] + [17, 31, 73, 47, 23]
de... |
def getMoneySpent(keyboards, drives, b):
keyboards.sort(reverse = True)
drives.sort(reverse = True)
cost = -1
for k in keyboards:
for d in drives:
_cost = k + d
if _cost <= b:
if _cost > cost:
cost = _cost
break... |
# Python - 2.7.6
Test.describe('Basic Tests')
Test.assert_equals(my_first_kata(3, 5), (3 % 5 + 5 % 3))
Test.assert_equals(my_first_kata('hello', 3), False)
Test.assert_equals(my_first_kata(67, 'bye'), False)
Test.assert_equals(my_first_kata(True, True), False)
Test.assert_equals(my_first_kata(314, 107), (107 % 314 + 3... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
r... |
DOMAIN = 'api.dkc.ru'
VERSION_API = 'v1'
URL_DOMAIN = f"https://{DOMAIN}/{VERSION_API}"
DEFAULT_HEADERS = {
"Accept": "*/*",
} |
def strip_react(polymer_fn):
polymer = polymer_fn()
result = {}
letters = list(set(polymer.lower()))
for letter in letters:
stripped = polymer.replace(letter, "").replace(letter.upper(), "")
result[letter] = react(stripped)
return min(result.values())
def react(stripped):
i ... |
'''
Author: ZHAO Zinan
Created: 14-Nov-2018
144. Binary Tree Preorder Traversal
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
"... |
# one object multiple reference example
"""
The below program shows that if there is changes in reference
variable, it gets also reflected in another variable too!
because there is only one object and we are creating multiple
reference variable for same object.
"""
class Mobile:
def __init__(self, price, brand):
... |
''' twitter API keys '''
API_KEY = ''
API_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_SECRET = ''
|
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
count = collections.Counter(words)
count_i = collections.defaultdict(list)
for c in count:
count_i[count[c]].append(c)
large = list( sorted(count_i.keys()) )
... |
name='green'
def get_line(in_f,num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
[T,n] = get_line(in_f,2)
LJ = True
LJ1 = True
for i in range(T):
L = get_line(in_f,n)
... |
#
# PySNMP MIB module INNOVX-DTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INNOVX-DTE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:42:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# Copyright 2019 Trend Micro.
#
# 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 to in writing,... |
chinese = {
"human": {
"country_of_citizenship": "国籍",
"ethic_group": "民族",
"religion": "信仰",
"occupation": "职业",
"member_of_political_party": "政党"
},
"organization": {
"employees": "组织员工数",
"political_ideology": "意识形态",
"type": "组织类型"
},
... |
# 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
class Solution:
summ = 0
def helper(self, root: TreeNode) -> TreeNode:
if not root: return None
root.r... |
class Parent1:
def __call__(self):
return 'parent1'
class Parent2:
def foo(self):
return 'parent2'
class Child1(Parent1):
pass
|
print('\033[32;1mDESAFIO 26 - Ocorrência de uma String\033[m')
print('\033[32;1mALUNO:\033[m \033[36;1mJoaquim Fernandes\033[m')
frase = str(input('Digite uma Frase: ')).strip().upper()
print(f'A letra \033[33;1mA\033[m aparece {frase.count("A")} vezes na Frase.')
print(f'A primeira letra \033[33;1mA\033[m apareceu na ... |
class PyCharm:
def execute(self):
print("Compiling")
print("Running")
class MyCharm:
def execute(self):
print("Spell Check")
print("Convention Check")
print("Compiling")
print("Running")
class Laptop:
def code(self, ide):
ide.execute()
ide = PyCh... |
def load_data(file_name: str = "sample"):
file = open(file_name)
data, result = [], []
try:
for line in file.read().splitlines():
data.append(line.split(" "))
except Exception as e:
print(e)
finally:
file.close()
for line in data:
result.append([i for ... |
"""Organizações Tabajara
As Organizações Tabajara irão atribuir um aumento de salário aos seus colaboradores e lhe
contrataram para desenvolver o programa que irá calcular os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte
critério, baseado no salário atual:
- sa... |
coordinates = (1, 2, 3)
# coordinates[0] * coordinates[1] * coordinates[2]
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
# x * y * z
# better way
x, y, z = coordinates
# works with lists too
|
def centered_average(nums):
"""
Return the "centered" average of an array of ints,
which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array.
If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the la... |
class TargetDensityError(Exception):
def __init__(self, target_density, current_density, target_metric):
p1 = f"""Target Density of {target_density} {target_metric} """
p2 = f"""is greater than Stand Total of {round(current_density, 1)} {target_metric}. """
p3 = f"""Please lower Target Densi... |
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root ... |
"""
This program prints a variable saved in a function.
"""
def print_something():
x = 10
print(x)
print_something() |
# Time: O(n)
# Space: O(1)
class Solution(object):
def minCostToMoveChips(self, chips):
"""
:type chips: List[int]
:rtype: int
"""
count = [0]*2
for p in chips:
count[p%2] += 1
return min(count)
|
"""
Revision Date: 2021.08.15
SPDX-License-Identifier: BSD-2-Clause
Copyright (c) 2021 Stuart Nolan. All rights reserved.
heatOfRxn(dictionary comp, dictionary db, float T):
Parameters:
comp, dictionary of components keys
values: dictionary {stoic: [+,-] float,
... |
s1 = "This is Sample String1"
s2 = "this string Is Only for ß Testing purpose"
s3 = "this Is for ß testing"
s4 = "I am a cyberpunk"
s5 = "I\tam\ta\tsoftware\ttester\nalso \rI am a \tdeveloper"
s6 = " I love python "
s7 = "I love python,java,ruby,scala"
s8 = "python,java,ruby,scala"
s9 = "python\njava\rruby... |
class Character:
def __init__(self, gear: int, name: str, relic: int = 0) -> None:
self.__gear: int = gear
self.__relic = relic
self.__name: str = name
@property
def gear(self) -> int:
return self.__gear
@property
def relic(self):
return self.__relic
@p... |
# Grant Gallagher
# Matchmaker
# Constants
INTRODUCTION = '''
<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
Matchmaker
Find the Perfect One for You
ProgrammersOnly.com
<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3<3
This foolproof program will determine your
... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
num = list()
while True:
num.append(int(input('Digite um valor : '))) #poderia receber o valor em um variável simpler
if num.count(num[len(num)-1]) != 2: # verificar se está na lista
print('Valor adicionado com sucesso...') # if n not in num: para add ou não
else:
num.pop()
... |
'''Example Lambda package file'''
def lambda_handler(event, context):
'''Example lambda function'''
return 'Hello from Cloudify & Lambda'
|
def foo():
bar("some string", s2="another_string")
def bar(s: str, s2: str):
print("bar(s) here: ", s)
a = 1 + 2
return
|
if __name__ == "__main__":
f = open('val_files.txt', 'w')
for i in range(108):
f.writelines(['2011_09_26/2011_09_26_drive_0001_sync ', str(i).zfill(10), ' l\n'])
f.close()
print('done') |
atletas = []
jogador = {}
while True:
jogador['nome'] = input('Nome do jogador: ').strip().upper()
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
gols = []
total = []
for g in range(0, partidas):
gols.append(int(input(f'Quantos gols, {jogador["nome"]} fez na {g + 1}° pa... |
# TODO: оптимизировать функции конвертации в таблицы и перенести в другой файл
def convert_data_to_dict(option_algo):
out = []
for i in option_algo:
dic = {'id_task': i.task_id, 'initial_timetable_second_alg': i.initial_timetable_second_alg,
'initial_timetable_first_alg': i.initial_timeta... |
# 使用滚动数组可以保证到O(n)的空间复杂度, 每一层加出来的结果存一个数组即可
class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
ret = []
ret1 = []
i = 0
for line in triangle:
if i == 0:
for key in range(0, le... |
print('-=-' * 30)
termo = int(input('Termo: '))
razao = int(input('Razao '))
c = 1
while c <= 10:
print('{}'.format(termo), end=' -> ')
termo += razao
c += 1
print('Fim')
|
# Created by MechAviv
# Map ID :: 931050940
# Classified Lab : Silo
OBJECT_1 = sm.sendNpcController(2159377, -700, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
OBJECT_2 = sm.sendNpcController(2159378, -800, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_2, "summon", 0)
sm.setSpeakerID(2159383)
sm.removeEs... |
train_1 = [[[('AUTHOR_FIRST_NAME', u'J.D.'), ('AUTHOR_LAST_NAME', u'Adams'), ('AUTHOR_FIRST_NAME', u'T.L.'), ('AUTHOR_LAST_NAME', u'Herter'), ('AUTHOR_FIRST_NAME', u'G.E.'), ('AUTHOR_LAST_NAME', u'Gull'), ('AUTHOR_FIRST_NAME', u'J.'), ('AUTHOR_LAST_NAME', u'Shoenwald'), ('AUTHOR_FIRST_NAME', u'C.P.'), ('AUTHOR_LAST_N... |
# numbers
assert 2+2==4
assert (50-5*6)/4 == 5.0
assert 8/5 == 1.6
assert 7//3 == 2
assert 7//-3 == -3
width=20
height=5*9
assert width*height == 900
x=y=z=0
assert x == 0
assert y == 0
assert z == 0
assert 3 * 3.75 / 1.5 == 7.5
assert 7.0 / 2 == 3.5
# complex numbers
x = 8j
y = 8.3j
z = 3.2e6j
a = 4+2j
b = 2-3j
c = ... |
# OBJECT_TYPES
VIPREQUEST_OBJ_TYPE = 'VipRequest'
SERVERPOOL_OBJ_TYPE = 'ServerPool'
VLAN_OBJ_TYPE = 'Vlan'
|
class Header:
def __init__(self, opcode, src_addr="127.0.0.1", dest_addr="127.0.0.1"):
self.opcode = str(opcode)
self.src_addr = src_addr
self.dest_addr = dest_addr
def encrypt(self, cipher):
return type(self)(
opcode=cipher.encrypt(self.opcode),
src_addr... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - diff3 algorithm
@copyright: 2002 by Florian Festi
@license: GNU GPL, see COPYING for details.
"""
def text_merge(old, other, new, allow_conflicts=1,
marker1='<<<<<<<<<<<<<<<<<<<<<<<<<\n',
marker2='=========================\n',
... |
#!/usr/bin/python
ROS_VISION_NODE_NAME = 'vision'
ROS_BRIDGE_ENCODING = "bgr8"
ROS_CONFIG_FILE_PATH = '/vision/config_folder'
ROS_IS_RECONFIGURE = '/vision/reconfigure'
ROS_SUBSCRIBER_WEBCAM_TOPIC_NAME = "/usb_cam/image_raw"
ROS_SUBSCRIBER_MOUSE_EVENT_TOPIC_NAME = "/ui/mouse_event"
ROS_SUBSCRIBER_CONFIG_START_TOPIC_... |
n = int(input())
s = 0
for i in range(1,n+1):
if i%3 !=0 and i%5 !=0:
s += i
print(s) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-10 15:18:29
# @Author : Lewis Tian (taseikyo@gmail.com)
# @Link : github.com/taseikyo
# @Version : Python3.7
# https://projecteuler.net/problem=6
# (1 + 2 + ... 100)^2 - (1^2 + 2^2 + ... 100^2) =
# 2 * [(1*2 + 1*3 + ... 1*100) + (2*3 + 2*4 + ... 2... |
# Copyright 2020 Google
#
# 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 to in writing, softw... |
"""
This script adds MQTT discovery support for Shellies devices.
"""
ATTR_MANUFACTURER = "Allterco Robotics"
ATTR_SHELLY = "Shelly"
ATTR_MODEL_SHELLY1 = "Shelly 1"
ATTR_MODEL_SHELLY1PM = "Shelly 1PM"
ATTR_MODEL_SHELLY2 = "Shelly 2"
ATTR_MODEL_SHELLY25 = "Shelly 2.5"
ATTR_MODEL_SHELLY3EM = "Shelly 3EM"
ATTR_MODEL_SHEL... |
class RedshiftSchema(object):
def schema_exists(self, schema):
sql = f"select * from pg_namespace where nspname = '{schema}'"
res = self.query(sql)
return res.num_rows > 0
def create_schema_with_permissions(self, schema, group=None):
"""
Creates a Redshift schema (if it... |
"""Module containing the `NodeOrigin` class used to store node origin info."""
class NodeOrigin:
"""
Class representing the origin of an AST node.
Attributes:
file {string} -- Source file from which the node originates.
start {int|None} -- starting line number at which the node was found.... |
# Write a Python program to test whether a number is within 100 of 1000 or 2000.
n = int(input("Enter a number: "))
def near_thousand(x):
return ((abs(1000 - x) <= 100) or (abs(2000 - x) <= 100))
print(near_thousand(n))
|
frase = str(input('Digite uma frase para ver se ela é um PALÍNDROMO! : ')).strip().lower().replace(' ', '')
invertido = frase[::-1]
if frase == invertido:
print('A sua frase é SIM um PALÍNDROMO!')
else:
print('A sua frase NÃO é um PALÍNDROMO!')
|
class Char:
def __init__(self):
self.name = ""
self.max_health = 100
class Attributes:
def __init__(self):
self.str = 0
self.agi = 0
self.dex = 0
self.lck = 0
self.chr = 0
self.end = 0
self.spr = 0
self.wis = 0
|
class app:
def __init__(self):
print('test')
if __name__ == '__main__':
app() |
class InvalidRequestMethodErr(Exception):
pass
class InvalidDownloadMiddlewareErr(Exception):
pass
class InvalidMiddlewareErr(Exception):
pass
class QueueEmptyErr(Exception):
pass
class InvalidDownloaderErr(Exception):
pass
class UnhandledDownloadErr(Exception):
pass
|
# Proszę zaproponować algorytm, który w czasie liniowym sortuje tablicę A zawierającą n liczb
# ze zbioru 0, ..., n**2−1.
def counting_sort(T, f):
count = [0] * len(T)
result = [0] * len(T)
for i in range(len(T)):
count[f(T[i])] += 1
for i in range(1, len(T)):
count[i] += count[i - 1]
... |
load("@bazel_skylib//lib:unittest.bzl", "asserts", "analysistest")
load("cppwinrt.bzl", "cppwinrt")
def _test_impl(ctx):
env = analysistest.begin(ctx)
target_under_test = analysistest.target_under_test(env)
actions = analysistest.target_actions(env)
header_output = actions[0].outputs.to_list()[0]
a... |
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
while nums[i] > 0 and nums[i] <= len(nums) and nums[i] != nums[nums[i]-1]:
t = nums[i] - 1
nums[t], n... |
(day, month, year) = input().strip().split()
day = int(day); month = int(month); year = int(year)
if month < 3:
month += 12
year -= 1
c = year / 100
k = year % 100
day + 26 * (m + 1) / 10 + k + k/4
week_day_name = ''
# 1. Follow from flowchart
if 0 == week_day:
week_day_name = 'SAT'
elif 1 == week_day... |
#using strings
myString ="my time is longer"
myInteger= 23
int =455
print(int)
print(myString.upper()) #all in capital letters
print(myString.lower()) #all in lowercase
print(myString.capitalize()) # the first letter is in capital letter
print(myString.swapcase()) #change all in capital letters because the original s... |
class Animal():
def __init__(self,name):
self.name =name
#a = Animal("dog")
#print(a.name)
|
#
# Copyright 2022 Embedded Systems Unit, Fondazione Bruno Kessler
#
# 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
#
# Unl... |
def save_color_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result'])
def save_depth_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result'])
|
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
r = []
for row in range(len(matrix)):
m = min(matrix[row])
i = matrix[row].index(m)
flag = True
for k in range(len(matrix)):
if matrix[k][i]>m:
... |
## scale and fit on the scaled data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pred = KMeans(4).fit_predict(X_scaled)
# plotting
xmin,ymin,xmax,ymax = *X_scaled.min(0), *X_scaled.max(0) # the "*" just unpacks the values, not multiplication
plt.scatter(X_scaled[:,0],X_scaled[:,1], c=pred)
plt.xlim(xm... |
class BreakoutException(Exception):
pass
class FunctionThrownException(Exception):
def __init__(self, outer, step):
self.outer = outer
self.step = step
def o_add(input_list, position, param1, param2, param3):
param3(input_list, input_list[position+3], True, param1(input_list, input_lis... |
"""
A full binary tree is a tree which has either 0 children or 2 children
"""
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check(root):
if not root:
return True
if not root.left and not root.right:
return True
i... |
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's static settings"""
# Screen settings
self.screen_width = 1280
self.screen_height = 720
self.bg_color = (230, 230, 230)
# Ship Settin... |
for i in range(0, 9):
if i == 5:
continue
print(i)
print("Loop is end.") |
# -*- coding: utf-8 -*-
def factorial_func(n: int):
if isinstance(n, int) and n < 0:
raise ValueError('Number n must be an integer and n is not an negative!')
res = 1
while n >= 2:
res *= n
n -= 1
return res
def fib_func(n):
if isinstance(n, int) and n < 1:
raise... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Constants for batch tests (tests with multiple actions)."""
# number of objects in a batch
COUNT = 2
# number of try operations
TRY_COUNT = 2
|
fuel_type = input()
fuel_amount = float(input())
club_card = input()
gasoline_price = 2.22
diesel_price = 2.33
gas_price = 0.93
if fuel_type == "Gas":
if club_card == "Yes":
if 20 <= fuel_amount <= 25:
fuel_price = fuel_amount * (gas_price - 0.08)
fuel_price = fuel_price - (fuel_pr... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Complete The Pattern #6 - Odd Ladder
#Problem level: 7 kyu
def pattern(n):
return "\n".join(str(i)*i for i in range(1, n+1) if i%2)
|
# -*- coding:utf-8 -*-
data = """
# Step 1: 預浸
預浸需要 60 度 20ml 的水,注水結束之後等待 20 秒
## 定點注水
在原點 (0, 0) 注水 20 ml
每次以 0.01 ml 的水量擠出
``` fixed_point
Coordinates: (0, 0)
High: 170 mm to 160 mm
Total Water: 20 ml
Extrudate: 0.2 ml/step
```
"""
|
def power_iteration(A, m0=1, u0=None, eps=1e-8, max_steps=500, verbose=False):
m = m0
u = u0
for k in range(int(max_steps)):
if verbose:
print(k, m, u)
m_prev = m
v = dot(A, u)
mi = argmax(abs(v))
m = v[mi]
u = v / m
... |
try:
pass
except:
pass
|
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def freeGLUT():
http_archive(
name="FreeGLUT" ,
build_file="//bazel/deps/FreeGLUT:build.BUILD" ,
sha256="90828907e... |
def comb(bam_file,fq_start,fq_end):
fq={}
with open(fq_start) as f:
lines = f.readlines()
for i in range(1,len(lines),4):
l = len(lines[i].strip())
name = lines[i-1].strip()[1:]
fq[name]=[str(l)]
with open(fq_end) as f:
lines = f.readlines()
for i in range(1,l... |
__author__ = """
Forzend Mainer
https://github.com/0Kit/
"""
__version__ = '1.0'
|
# TODO: *3
@task
def setupNetwork(ifaces):
interfaces = '''auto lo
iface lo inet loopback
'''
for iface, config in ifaces.items():
interfaces += '''
auto %s
iface %s inet static
address %s
netmask %s
''' % (iface, iface, config[0], config[1])
if iface == 'eth1':
interfaces ... |
# Guyon Morée
# http://gumuz.looze.net/
def split_seq(seq,size):
""" Split up seq in pieces of size """
return [seq[i:i+size] for i in range(0, len(seq), size)]
|
OCTICON_SHARE = """
<svg class="octicon octicon-share" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.823.177L4.927 3.073a.25.25 0 00.177.427H7.25v5.75a.75.75 0 001.5 0V3.5h2.146a.25.25 0 00.177-.427L8.177.177a.25.25 0 00-.354 0zM3.75 6.5a.25.25 0 00-.25.2... |
#pylint: disable=invalid-name,missing-docstring
# Basic test with a list
TEST_LIST1 = ['a' 'b'] # [implicit-str-concat]
# Testing with unicode strings in a tuple, with a comma AFTER concatenation
TEST_LIST2 = (u"a" u"b", u"c") # [implicit-str-concat]
# Testing with raw strings in a set, with a comma BEFORE concatena... |
class LexpyError(Exception):
pass
class InvalidWildCardExpressionError(LexpyError):
def __init__(self, expr, message):
self.expr = expr
self.message = message
def __str__(self):
return repr(': '.join([self.message, self.expr]))
|
# Python program to create a bytearray from a list
nums = [10, 20, 56, 35, 17, 99]
values = bytearray(nums)
for x in values:
print(x)
|
#!/usr/bin/env python3
x = 0
y = (-1/4)*(x-1)+3
print(y)
|
# Validando expressões matemáticas
'''Crie um programa onde o usuário digite
uma EXPRESSÃO qualquer que use PARÊNTESES.
Seu aplicativo deverá analisar se a expressão
passada está com os parênteses abertos e fechados
na ORDEM CORRETA'''
expressao = str(input('Digite a expressão: '))
pilha = []
for simbolo in expressao:... |
"""Constants for Camera component."""
DOMAIN = "camera"
DATA_CAMERA_PREFS = "camera_prefs"
PREF_PRELOAD_STREAM = "preload_stream"
|
"""
EXISTE DIVERSAS FORMAS DE DOCUMENTAR O SEU CÓDIGO. DENTRE ELAS, PODE-SE SE ENCONTRAR DOCSTRINGS PARA FUNÇÕES, MÉTODOS,
CLASSES, ETC. CASO TENHA ALGUMA DÚVIDA, CONSULTAR O MATERIAL NO SITE.
VERIFICAR TYPEHINTS
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.