content stringlengths 7 1.05M |
|---|
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
list_before = db.get_contact_list()
contact.id_contact = app.contact.get_next_id(list_before)
app.contact.create(contact)
assert len(list_before) + 1 == len(db.get_contact_list())
list_after = db.get_contact_list()
... |
# solution 1: Brute Force
# time complexity: O(n^2)
# space complexity: O(1)
def twoNumberSum(arr, n):
for i in range(len(arr) - 1):
firstNum = arr[i]
for j in range(i + 1, len(arr)):
secondNum = arr[j]
if firstNum + secondNum == n:
return [first... |
# 005 印出菱形
while(1):
level = int(input())
if(level <= 0):
break
L = 2*level-1
mid = int((L - 1) / 2)
inspa = mid * 2 - 1
for i in range(L):
spa = level - i - 1
if spa >= 0:
print(" " * spa, end='')
print('*', end='')
if spa < 0... |
class InvalidMovementException(Exception):
pass
class InvalidMovementTargetException(InvalidMovementException):
pass
class InvalidMovimentOriginException(InvalidMovementException):
pass |
FORM_CONTENT_TYPES = [
'application/x-www-form-urlencoded',
'multipart/form-data'
]
|
"""
Simulation parameters.
"""
SIMULATION_TIME_STEPS = 300
|
def numb_of_char(a):
d = {}
for char in set(a):
d[char] = a.count(char)
return d
a = numb_of_char(str(input("Input the word please: ")))
print(a)
|
class Vector2D:
def __init__(self, v: List[List[int]]):
def getIt():
for row in v:
for val in row:
yield val
self.it = iter(getIt())
self.val = next(self.it, None)
def next(self) -> int:
result = self.val
... |
prod1 = float(input("Insira o valor do produto A: "))
prod2 = float(input("Insira o valor do produto B: "))
prod3 = float(input("Insira o valor do produto C: "))
if prod1 < prod2 and prod1 < prod3:
print ("Escolha o produto A é o mais barato")
elif prod2 < prod1 and prod2 < prod3:
print ("Escolha o produto B é... |
def plot_3D_Data(
self,
*arg_list,
is_norm=False,
unit="SI",
component_list=None,
save_path=None,
x_min=None,
x_max=None,
y_min=None,
y_max=None,
z_min=None,
z_max=None,
z_range=None,
is_auto_ticks=True,
is_auto_range=False,
is_2D_view=False,
is_same_s... |
def elo(winner_rank, loser_rank, weighting):
"""
:param winner: The Player that won the match.
:param loser: The Player that lost the match.
:param weighting: The weighting factor to suit your comp.
:return: (winner_new_rank, loser_new_rank) Tuple.
This follows the ELO ranking method.
"""
... |
'''
给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
示例 1:
输入: [[1,3], [0,2], [1,3], [0,2]]
输出: true
解释:
无向图如下:
0----1
| |
| |
3----2
我们可以将... |
n = int(input())
line = list(map(int, input().split()))
l = {}
res = ""
for i, j in enumerate(line):
l[j] = i+1
for k in range(n):
res += str(l[k+1]) + " "
print(res.rstrip()) |
valor = int(input())
for i in range(valor+1):
if(i%2 != 0):
print(i) |
# https://leetcode.com/problems/delete-and-earn/
class Solution:
def deleteAndEarn(self, nums: list[int]) -> int:
num_profits = dict()
for num in nums:
num_profits[num] = num_profits.get(num, 0) + num
sorted_nums = sorted(num_profits.keys())
second_last_profit = 0
... |
# Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final mostre, os 10 primeiros termos dessa prograssão.
primeiro = int(input("Primeiro Termo: "))
razao = int(input("Razão: "))
decimo = primeiro + (10 - 1) * razao
for c in range(primeiro, decimo + razao, razao):
print(f"{c}", end=" -> ")
pr... |
class BaseStorage(object):
def get_rule(self, name):
raise NotImplementedError()
def get_ruleset(self, name):
raise NotImplementedError()
|
class Solution:
# dictionary keys are tuples, storing results
# structure of the tuple:
# (level, prev_sum, val_to_include)
# value is number of successful tuples
def fourSumCount(self, A, B, C, D, prev_sum=0, level=0, sums={}):
"""
:type A: List[int]
:type B: List[int]
... |
# https://projecteuler.net/problem=19
def is_leap(year):
if year%4 != 0:
return False
if year%100 == 0 and year%400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
if month == 4 or month == 6 or m... |
class Config:
ngram = 2
train_set = "data/rmrb.txt"
modified_train_set = "data/rmrb_modified.txt"
test_set = ""
model_file = ""
param_file = ""
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 |
def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return (len(a) <= len(b))
def analisar(e, i, s):
a, b = e
if(diferenca_tamanhos(a, ... |
class Solution:
def allPossibleFBT(self, N):
def constr(N):
if N == 1: yield TreeNode(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = TreeNode(0)
m.left = l
... |
"""
How to set up virtual environment
pip install virtualenv
pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
# To activate virtualenv and set up flask
1. mkvirtualenv my-venv
###2. workon my-venv
3. pip install Flask
4. pip freeze
5. #... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... |
macs_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
VERIFIED_OP_REFERENCES = [
'Abs-1',
'Acos-1',
'Add-1',
'Asin-1',
'Asinh-3',
'Assign-6',
'AvgPool-1',
'BatchNormInference-5',
'BatchToSpace-2',
'BinaryConvolution-1',
'Broadcast-1',
'Broadcast-3'... |
# Copyright 2015 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.
# This dictionary of GPU information was captured from a run of
# Telemetry on a Linux workstation with NVIDIA GPU. It helps test
# telemetry.internal.platfo... |
## Highest Score
# 🚨 Don't change the code below 👇
student_scores = input("Input a list of student scores: ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 Don't change the code above 👆
# Write your code below this row 👇
highest_score = 0... |
for i in range(int(input())):
number_of_candies = int(input())
candies_weights = list(map(int, input().split()))
bob_pos = number_of_candies - 1
alice_pos = 0
bob_current_weight = 0
alice_current_weight = 0
last_equal_candies_total_number = 0
while alice_pos <= bob_pos:
if al... |
# --------------
# Code starts here
# Create the lists
class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio']
class_2 = ['hilary mason', 'carla gentry', 'corinna cortes']
# Concatenate both the strings
new_class = class_1+class_2
print(new_class)
# Append the list
new_class.append('p... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:31:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.... |
samples = {
"2_brother_plays": {
"question_parts": [range(1, 13), range(13, 17)],
"sp_parts": [range(20, 43), range(50, 60)]
}
}
|
# -*- coding: utf-8 -*-
'''
File name: code\gcd_sequence\sol_443.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #443 :: GCD sequence
#
# For more information see:
# https://projecteuler.net/problem=443
# Problem Statement
'''
Let g(n) ... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
... |
def insert_metatable():
"""SQL query to insert records from table insert into a table on a DB
"""
return """
INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES
('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0... |
"""
Tools para validar o arquivo template recebido do SQS
"""
class Validate:
def __init__(self):
pass
def check_validate_yml(self, template):
"""
valida se o arquivo yml é valido
"""
if template:
return True
else:
return False
def che... |
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... |
def save_form(form, actor=None):
"""Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require
this to be passed (is not handled by middleware), you can use this to replace form.save().
Requires you to use the audit.Model model as the actor is passed to th... |
# coding = utf-8
# Create date: 2018-11-05
# Author :Hailong
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
stdin, stdout, st... |
#Datos de entrada
num=int(input("Ingrese un numero: "))
# Proceso
if num==10:
print("Calificacion: A")
elif num==9:
print("Calificacion: B")
elif num==8:
print("Calificacion: C")
elif num==7 and num==6:
print("Calificacion: D")
elif num<=5 and num>=0:
print("Calificacion: F")
|
ribbon_needed = 0
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
length, width, height = [int(item) for item in line.split("x")]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_side = min(dimensions)
ribbon_n... |
"""
# refactoring
Refactoring is the key to successfull projects.
Refactor:
1) annuity_factor such that:
conversion to integer is handled,
no extra printing
2) policy_book into a class such that:
a function generates the book and the premium
stats and visualizations functions are avalaible
3) book_report su... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor =... |
"""
Visual Genome Python API wrapper, models
"""
class Image:
"""
Image.
ID int
url hyperlink string
width int
height int
"""
def __init__(self, id, url, width, height, coco_id, flickr_id):
self.id = id
self.url = url
self.width ... |
def setIntersectionCount(group):
return len(set.intersection(*group))
groupList = []
tempGroup = []
with open("./6/input.txt") as inputFile:
for line in inputFile:
line = line.replace("\n","")
if len(line) > 0:
tempGroup.append(set(line))
else:
groupList.append(tempGroup)
tempGroup = []
if len(tempGr... |
"""Errors module."""
__all__ = [
'Error',
'AddressError',
'AuthenticationError',
'TransportError',
'ValidationError',
'RegisterError',
'MessageError',
'DBusError',
'SignatureError',
'TooLongError',
]
class Error(Exception):
"""Base class."""
class AddressError(Error):
... |
# If you're new to file handling, be sure to check out with_open.py first!
# You'll also want to check out read_text.py before this example. This one is a bit more advanced.
with open('read_csv.csv', 'r') as states_file:
# Instead of leaving the file contents as a string, we're splitting the file into a list... |
class Student:
studentLevel = 'first year computer science 2020/2021 session'
studentCounter = 0
registeredCourse='csc102'
def __init__(self, thename, thematricno, thesex,thehostelname,theage,thecsc102examscore):
self.name = thename
self.matricno = thematricno
self.sex = thesex
... |
"""
Dany jest ciąg określony wzorem: A[n+1] = (A[n] % 2) ∗ (3 ∗ A[n] + 1) + (1 − A[n] % 2) ∗ A[n] / 2.
Startując z dowolnej liczby naturalnej > 1 ciąg ten osiąga wartość 1. Napisać program, który
znajdzie wyraz początkowy z przedziału 2-10000 dla którego wartość 1 jest osiągalna po największej
liczbie kroków.
"""
a0 = ... |
def say_hi(name,age):
print("Hello " + name + ", you are " + age)
say_hi("Mike", "35")
def cube(num): # function
return num*num*num
result = cube(4) # variable
print(result)
|
MUTATION = '''mutation {{
{mutation}
}}'''
def _verify_additional_type(additionaltype):
"""Check that the input to additionaltype is a list of strings.
If it is empty, raise ValueError
If it is a string, convert it to a list of strings."""
if additionaltype is None:
return None
if isins... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# dictionaries, look-up tables & key-value pairs\n",
"# d = {} OR d = dict()\n",
"# e.g. d = {\"George\": 24, \"Tom\": 32}\n",
"\n",
"d = {}\n",
"\n"
]
},
{
"cell_typ... |
sayi1 = int(input("1. Sayı: "))
sayi2 = int(input("2. Sayı: "))
sayi3 = int(input("3. Sayı: "))
sayi4 = int(input("4. Sayı: "))
sayi5 = int(input("5. Sayı: "))
sayilar=[];
sayilar.append(sayi1)
sayilar.append(sayi2)
sayilar.append(sayi3)
sayilar.append(sayi4)
sayilar.append(sayi5)
sayilar.sort()
print("En büyük sayimiz... |
#
# PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
# written by abraham on aug 24
def dyear2date(dyear):
year = int(dyear)
month_lengths = [31,28,31,30,31,30,31,31,30,31,30,31]
days_before_months = [0,31,59,90,120,151,181,212,243,273,304,334]
days_into_year_f = (dyear-year)*365
days_into_year_i = int(days_into_year_f)
for i in range(12):
if days_before_mo... |
class Camera:
"""docstring for ."""
def __init__(self, brand, sensor, lens, battery):
self.brand = brand
self.sensor = sensor
self.lens = lens
self.battery = battery
def __str__(self):
return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery
... |
#!/usr/bin/python3
"""
Good morning! Here's your coding interview problem for today.
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can ... |
# file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb')
file = open('encrypt_eye.png', 'rb')
image = file.read()
file.close()
image = bytearray(image)
key = 48
for index, value in enumerate(image):
image[index] = value^key
file = open('2eye.png','wb')
... |
n=int(input())
c = 1
while c**2 < n:
print(c**2)
c += 1
|
class BSTNode:
def __init__(self, data = None) -> None:
self.data = data
self.left = None
self.right = None
def __repr__(self) -> str:
return(f"BSTNode({self.data})")
def __str__(self) -> str:
return str(self.data)
def __eq__(self, o: object) -> ... |
'''
Given an array of intervals, merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].... |
# CPU: 0.06 s
possessed, found, condition = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
div, mod = divmod(possessed, condition)
count += div
possessed = div + mod
print(count)
|
print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0)
|
num = int(input())
d1 = (num % 10 ** 4) // 10 ** 3
d2 = (num % 10 ** 3) // 10 ** 2
d3 = (num % 10 ** 2) // 10
d4 = num % 10
print("Цифра в позиции тысяч равна", d1)
print("Цифра в позиции сотен равна", d2)
print("Цифра в позиции десятков равна", d3)
print("Цифра в позиции единиц равна", d4)
# print("Python", , "is the ... |
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This pr... |
class Dummy():
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class DummyData():
def __init__(self):
self.results = [
Dummy({
'name': 'PA',
'age': 29,
'city': 'Paris'... |
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
array = []
for _ in range(int(input())):
command = input().strip().split(" ")
cmd_type = command[0]
if (cmd_type == "print"):
print(array)
elif (cmd_type == "sort"):
array.sort()
elif (cmd_type == "reverse"):
array.reverse()
elif (cmd_type == "pop"):
array.pop()
... |
# -*- coding: utf-8 -*-
"""
mundiapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class UpdatePlanRequest(object):
"""Implementation of the 'UpdatePlanRequest' model.
Request for updating a plan
Attributes:
name (string): Plan's n... |
class AuthError(Exception):
pass
class JsonError(Exception):
pass
|
# 3. Define a function to check whether a number is even
def even(num):
if num%2 == 0:
return True
else:
return False
print(even(4))
print(even(-5))
|
class OverlapResult:
def __init__(self, overlap_map: dict[tuple[float, float], int]):
self._overlap_map = overlap_map
self._overlaps = overlap_map_to_overlaps(overlap_map)
@property
def overlaps(self) -> int:
return self._overlaps
@property
def overlap_map(self) -> dict[tu... |
class Config:
def __init__(self, config_file_name):
self.config_file_name = config_file_name
|
""" module logging"""
# logging
|
# @AUTHOR : lonsty
# @DATE : 2020/3/28 18:01
class CookiesExpiredException(Exception):
pass
class NoImagesException(Exception):
pass
class ContentParserError(Exception):
pass
class UserNotFound(Exception):
pass
|
"""Errors."""
class ProxyError(Exception):
pass
class NoProxyError(Exception):
pass
class ResolveError(Exception):
pass
class ProxyConnError(ProxyError):
pass
class ProxyRecvError(ProxyError): # connection_is_reset
pass
class ProxySendError(ProxyError): # connection_is_reset
pass
... |
def hello_world():
"""打印Hello world"""
message = 'hello world'
print(message.title())
hello_world()
|
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"WorldArea",
"VoxelLight",
"VoxelLightNode",
"VoxelLevelGenerator",
"VoxelLevelGeneratorFlat",
"VoxelSurfaceMerger",
"VoxelSurfaceSimple",
... |
# The Pokemon class should receive a name (string) and health (int) upon initialization.
# It should also have a method called pokemon_details that returns the information about the pokemon:
# "{pokemon_name} with health {pokemon_health}"
class Pokemon:
def __init__(self, name: str, health: int) -> None:
... |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_mem_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp"
],
"include... |
# Desafio 009
# Faça um programa que leia um numero inteiro qualquer
# e mostre na tela a sua tabuada.
n = int(input('digite um numero. '))
r1 = n * 1
r2 = (n * 2)
r3 = (n * 3)
r4 = (n * 4)
r5 = (n * 5)
r6 = (n * 6)
r7 = (n * 7)
r8 = (n * 8)
r9 = (n * 9)
r10 = (n * 10)
print('A Tabuada de {} é'.format(n))
print ('{} x... |
TINY_WAIT = 1
SMALL_WAIT = 3
MEDIUM_WAIT = 5
BIG_WAIT = 10
SECURITY_WAIT = 15
BATTLE_FINISH_DETECT = 12
BATTLE_NONE_DETECT_TIME = 90
BATTLE_END_SIGNAL_MAX_EXECUTE_TIME = 15
# 关键动作的偏移
FLAGS_START_BATTLE_BIAS = (50, 25)
FLAGS_ENSURE_TEAM_INFO_BIAS = (25, 50)
# 正方形偏移
FLAGS_CLICK_BIAS_TINY = (3, 3)
FLAGS_CLICK_BIAS_SMAL... |
_base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py']
model = dict(
pretrains=dict(
detector= # noqa: E251
'https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth' # noqa: E501
))
data_root = 'data/MOT17/'
test_set = 'test'
data = dict... |
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that ... |
DEFAULT_MIRRORS = {
"bitbucket": [
"https://bitbucket.org/{repository}/get/{commit}.tar.gz",
],
"buildifier": [
"https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}",
],
"github": [
"https://github.com/{repository}/archive/{commit}.tar.gz",
],
... |
SURVEY_POST = {
'tags': ['설문조사 관리'],
'description': '설문조사 등록',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str',
'required': True
},
{
'name': 'title',
... |
#!/usr/bin/env python3.4
# coding: utf-8
class Drawable:
"""
Base class for drawable objects.
"""
def draw(self):
"""
Returns a Surface object.
"""
raise NotImplementedError(
"Method `draw` is not implemented for {}".format(type(self)))
|
def integrate_exponential(a, x0, dt, T):
"""Compute solution of the differential equation xdot=a*x with
initial condition x0 for a duration T. Use time step dt for numerical
solution.
Args:
a (scalar): parameter of xdot (xdot=a*x)
x0 (scalar): initial condition (x at time 0)
dt (scalar): timeste... |
class Animal():
edad:int
patas:int
ruido:str
nombre: str
kgComida: float = 0
def __init__(self, edad, patas, ruido, nombre):
self.edad =edad
self.patas = patas
self.ruido = ruido
self.nombre = nombre
def comer(self, alimento):
self.kgComida += alimento... |
maxWeight = 30
value = [15, 7, 10, 5, 8, 17]
weight = [15, 3, 2, 5, 9, 20]
def bag(pos, selected):
# calcula o total
totalValue = 0
pesoTotal = 0
for i in selected:
totalValue += value[i]
pesoTotal += weight[i]
if pesoTotal > maxWeight:
return (0,0)
if pos >= len(weight):
return (totalValue, pesoT... |
def fibo(n):
return n <= 1 or fibo(n-1) + fibo(n-2)
def fibo_main():
for n in range(1,47):
res = fibo(n)
print("%s\t%s" % (n, res))
fibo_main()
# profiling result for 47 numbers
# profile: python -m profile fibo.py
"""
-1273940835 function calls (275 primitive calls) in 18966.707 seconds
Ordered... |
#!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
"""
* Wiki table for `leathers` C++ project
Expected format:
### Main table
Name | Clang | GCC | MSVC |
-----------------------------|----------|----------|------|
static-ctor-not-thread-safe | *no* ... |
# Copyright (C) 2014 VA Linux Systems Japan K.K.
# Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp>
# 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... |
ADDED_KARMA_TO_MEMBER = "Gave {} karma to {}, their karma is now at {}."
REMOVED_KARMA_FROM_MEMBER = "Removed {} karma from {}, their karma is now at {}."
LIST_KARMA_OWN = "You currently have {} karma."
LIST_KARMA_OBJECT = "\"{}\" currently has {} karma."
LIST_KARMA_MEMBER = "{} currently has {} karma."
KARMA_TOP_STA... |
# simple test function that uses python 3 features (e.g., f-strings)
# see https://github.com/localstack/localstack/issues/264
def handler(event, context):
# the following line is Python 3.6+ specific
msg = f"Successfully processed {event}" # noqa This code is Python 3.6+ only
return event
|
def decimal_to_binary_fraction(x=0.5):
"""
Input: x, a float between 0 and 1
Returns binary representation of x
"""
p = 0
while ((2 ** p) * x) % 1 != 0:
# print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
p += 1
num = int(x * (2 ** p))
result = ''
if num == 0:
... |
def deco1(func):
print("before myfunc() called.")
func()
print("after myfunc() called.")
def myfunc():
print("myfunc() called.")
deco1(myfunc)
|
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = dict()
def add_item(self, item_name, quantity, price):
if item_name != None and quantity >= 1:
self.items.update({item_name: quantity})
if quantity and price >= 1:
self.total += (quantity * price)
def re... |
def solution(bridge_length, weight, truck_weights):
answer = 0
# { weight, time }
wait = truck_weights[:]
bridge = []
passed = 0
currWeight = 0
while True:
if passed == len(truck_weights) and len(wait) == 0: return answer
answer += 1
# sth needs to be passed
... |
"""Holds the device gemoetry parameters (Table 5), taken from Wu et al.,
>> A Predictive 3-D Source/Drain Resistance Compact Model and the Impact on 7 nm and Scaled FinFets<<, 2020, with interpolation for 4nm. 16nm is taken from PTM HP.
"""
node_names = [16, 7, 5, 4, 3]
GP = [64, 56, 48, 44, 41]
FP = [40, 30, 28, 24, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.