content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
####################################################
# Block
########################
blocks_head = []
class Block:
name = "Block"
tag = "div"
content_seperator = ""
allows_nesting = True
def __init__(self, parent):
self.parent = parent
self.parent.add(self) if parent else None
... | blocks_head = []
class Block:
name = 'Block'
tag = 'div'
content_seperator = ''
allows_nesting = True
def __init__(self, parent):
self.parent = parent
self.parent.add(self) if parent else None
self.content = []
def add(self, x):
self.content.append(x)
def ... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
a=[*map(int,input().split())]
r=a[1]-a[0]
print(a[-1]+r*all(y-x==r for x,y in zip(a,a[1:])))
| """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n = int(input())
a = [*map(int, input().split())]
r = a[1] - a[0]
print(a[-1] + r * all((y - x == r for (x, y) in zip(a, a[1:])))) |
# -*- coding: utf-8 -*-
"""
List Data Examples and Operations
Intro to Python Workshop
"""
# List Data are NOT immutable, unlike string data
testlist = [10,11,13,7,8,3]
print (testlist)
testlist[2] = 14
print (testlist)
# Lists are collections of items - we can put many values in a single variable
dmb = ... | """
List Data Examples and Operations
Intro to Python Workshop
"""
testlist = [10, 11, 13, 7, 8, 3]
print(testlist)
testlist[2] = 14
print(testlist)
dmb = ['dave', 'tim', 'leroy', 'carter', 'steffan', 'boyd']
for i in dmb:
print('Band member:', i)
for i in range(len(dmb)):
dm = dmb[i]
print('Band member:',... |
test = { 'name': 'q4c',
'points': 1,
'suites': [ { 'cases': [ {'code': ">>> is_valid_november_2020_sweden('Sweden', '2020-11-04')\nTrue", 'hidden': False, 'locked': False},
{'code': ">>> not is_valid_november_2020_sweden('sweden', '2020-11-04')\nTrue", 'hidden': False,... | test = {'name': 'q4c', 'points': 1, 'suites': [{'cases': [{'code': ">>> is_valid_november_2020_sweden('Sweden', '2020-11-04')\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> not is_valid_november_2020_sweden('sweden', '2020-11-04')\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> not is_valid_november_... |
class complex:
def __init__(self, real, img):
self.real = real
self.img = img
def add(self, b):
res = complex(0,0)
res.real = self.real + b.real
res.img = self.img + b.img
return res
def display(self):
if self.img>=0:
print("{} + i{}".format(self.real, self.img))
if self.img<0:
print("{} -... | class Complex:
def __init__(self, real, img):
self.real = real
self.img = img
def add(self, b):
res = complex(0, 0)
res.real = self.real + b.real
res.img = self.img + b.img
return res
def display(self):
if self.img >= 0:
print('{} + i{}'... |
"""A macro for creating a webpack federation route module"""
load("@aspect_rules_swc//swc:swc.bzl", "swc")
# Defines this as an importable module area for shared macros and configs
def build_route(name, entry, srcs, data, webpack, federation_shared_config):
"""
Macro that allows easy composition of routes fr... | """A macro for creating a webpack federation route module"""
load('@aspect_rules_swc//swc:swc.bzl', 'swc')
def build_route(name, entry, srcs, data, webpack, federation_shared_config):
"""
Macro that allows easy composition of routes from a multi route spa
Args:
name: name of a route (route)
... |
"""
Author: Justin Cappos
Description:
It should be okay to put __ in a doc string...
"""
#pragma repy
def foo():
"""__ should also be allowed here__"""
pass
class bar:
"""__ and here__"""
pass
| """
Author: Justin Cappos
Description:
It should be okay to put __ in a doc string...
"""
def foo():
"""__ should also be allowed here__"""
pass
class Bar:
"""__ and here__"""
pass |
#1st method
sq1 = []
for x in range(10):
sq1.append(x**2)
print("sq1 = ", sq1)
# 2nd method
sq2 = [x**2 for x in range(10)]
print("sq2 = ", sq2)
sq3 = [(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]
print("sq3 = ", sq3)
vec = [-4, -2, 0, 2, 4]
print("x*2", [x*2 for x in vec])
print("x if x>0", [x for x in ve... | sq1 = []
for x in range(10):
sq1.append(x ** 2)
print('sq1 = ', sq1)
sq2 = [x ** 2 for x in range(10)]
print('sq2 = ', sq2)
sq3 = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print('sq3 = ', sq3)
vec = [-4, -2, 0, 2, 4]
print('x*2', [x * 2 for x in vec])
print('x if x>0', [x for x in vec if x >= 0])
pri... |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def solution(value: int) -> str:
"""
Complete the solution so that it
returns a formatted string.
The return value should equal "Value
is VALUE" where value is a 5 digit
padd... | def solution(value: int) -> str:
"""
Complete the solution so that it
returns a formatted string.
The return value should equal "Value
is VALUE" where value is a 5 digit
padded number.
:param value:
:return:
"""
result = str(value)
while len(result) != 5:
result = '0... |
# module trackmod.namereg
class NameRegistry(object):
class AllRegistered(object):
terminal = True
def register(self, names):
return
def __contains__(self, name):
return True
all_registered = AllRegistered()
class AllFound(object):
def __init__(... | class Nameregistry(object):
class Allregistered(object):
terminal = True
def register(self, names):
return
def __contains__(self, name):
return True
all_registered = all_registered()
class Allfound(object):
def __init__(self, value):
s... |
"""
For a given string and dictionary, how many sentences can you make from the
string, such that all the words are contained in the dictionary.
eg: for given string -> "appletablet"
"apple", "tablet"
"applet", "able", "t"
"apple", "table", "t"
"app", "let", "able", "t"
"applet", {app, let, apple, t, applet} => 3
"th... | """
For a given string and dictionary, how many sentences can you make from the
string, such that all the words are contained in the dictionary.
eg: for given string -> "appletablet"
"apple", "tablet"
"applet", "able", "t"
"apple", "table", "t"
"app", "let", "able", "t"
"applet", {app, let, apple, t, applet} => 3
"th... |
BOP_CONFIG = dict()
BOP_CONFIG['hb'] = dict(
input_resize=(640, 480),
urdf_ds_name='hb',
obj_ds_name='hb',
train_pbr_ds_name=['hb.pbr'],
inference_ds_name=['hb.bop19'],
test_ds_name=[],
)
BOP_CONFIG['icbin'] = dict(
input_resize=(640, 480),
urdf_ds_name='icbin',
obj_ds_name='icbin',... | bop_config = dict()
BOP_CONFIG['hb'] = dict(input_resize=(640, 480), urdf_ds_name='hb', obj_ds_name='hb', train_pbr_ds_name=['hb.pbr'], inference_ds_name=['hb.bop19'], test_ds_name=[])
BOP_CONFIG['icbin'] = dict(input_resize=(640, 480), urdf_ds_name='icbin', obj_ds_name='icbin', train_pbr_ds_name=['icbin.pbr'], inferen... |
class MixUp:
def __init__(self):
pass
class CutMix:
def __init__(self):
pass
| class Mixup:
def __init__(self):
pass
class Cutmix:
def __init__(self):
pass |
# 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:
def calc_diameter(self, diameter, node):
if node:
l_height = calc_diameter(node.left)
... | class Solution:
def calc_diameter(self, diameter, node):
if node:
l_height = calc_diameter(node.left)
r_height = calc_diameter(node.right)
diameter[0] = max(diameter[0], l_height + r_height + 1)
return 1 + max(l_height, r_height)
return 0
def dia... |
class C:
def f(self, x):
pass
def g(self):
def f(x): #gets ignored by pytype but fixer sees it, generates warning (FIXME?)
return 1
return f
| class C:
def f(self, x):
pass
def g(self):
def f(x):
return 1
return f |
var1 = 10
var2 = 15
var3 = 12.6
print (var1, var2, var3)
A = 89
B = 56
Addition = A + B
print (Addition)
A = 89
B = 56
Substraction = A - B
print (Substraction)
#type function
#variable
#operands
#operator
f = 9/5*+32
print (float(f))
#type function
#variable
#operands
#operator
c = 5*32/9
print (float(c)) | var1 = 10
var2 = 15
var3 = 12.6
print(var1, var2, var3)
a = 89
b = 56
addition = A + B
print(Addition)
a = 89
b = 56
substraction = A - B
print(Substraction)
f = 9 / 5 * +32
print(float(f))
c = 5 * 32 / 9
print(float(c)) |
expected_output = {
"main": {
"chassis": {
"name": {
"descr": "A901-6CZ-FT-A Chassis",
"name": "A901-6CZ-FT-A Chassis",
"pid": "A901-6CZ-FT-A",
"sn": "CAT2342U1S6",
"vid": "V04 "
}
}
},
"s... | expected_output = {'main': {'chassis': {'name': {'descr': 'A901-6CZ-FT-A Chassis', 'name': 'A901-6CZ-FT-A Chassis', 'pid': 'A901-6CZ-FT-A', 'sn': 'CAT2342U1S6', 'vid': 'V04 '}}}, 'slot': {'0': {'rp': {'A901-6CZ-FT-A Chassis': {'descr': 'A901-6CZ-FT-A Chassis', 'name': 'A901-6CZ-FT-A Chassis', 'pid': 'A901-6CZ-FT-A', 's... |
# -*- coding: utf-8 -*-
"""
@author: 2series
"""
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
... | """
@author: 2series
"""
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def get_name(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
"""Assumes src ... |
class Clock:
def __init__(self, hour, minute):
self.hour = (hour + (minute // 60)) % 24
self.minute = minute % 60
def __repr__(self):
return "{:02d}:{:02d}".format(self.hour, self.minute)
def __eq__(self, other):
return self.hour == other.hour and self.minute == other.minut... | class Clock:
def __init__(self, hour, minute):
self.hour = (hour + minute // 60) % 24
self.minute = minute % 60
def __repr__(self):
return '{:02d}:{:02d}'.format(self.hour, self.minute)
def __eq__(self, other):
return self.hour == other.hour and self.minute == other.minute... |
{'name': 'Library Management Application',
'description': 'Library books, members and book borrowing.',
'author': 'Daniel Reis',
'depends': ['base'],
'data': [
'security/library_security.xml',
'security/ir.model.access.csv',
'views/library_menu.xml',
'views/book_view.xml',
'views/book_list_templ... | {'name': 'Library Management Application', 'description': 'Library books, members and book borrowing.', 'author': 'Daniel Reis', 'depends': ['base'], 'data': ['security/library_security.xml', 'security/ir.model.access.csv', 'views/library_menu.xml', 'views/book_view.xml', 'views/book_list_template.xml'], 'application':... |
number = int(input('Enter a number: '))
times = int(input('Enter a times: '))
def multiplication(numbers, x):
z = 1
while z <= numbers:
b = '{} x {} = {}'.format(z, x, x * z)
print(b)
z += 1
multiplication(number, times)
| number = int(input('Enter a number: '))
times = int(input('Enter a times: '))
def multiplication(numbers, x):
z = 1
while z <= numbers:
b = '{} x {} = {}'.format(z, x, x * z)
print(b)
z += 1
multiplication(number, times) |
"""The Sampling configuration file consists of the parameters which conducting adaptive sampling/active learning from the VRM system
:param sampling_config['sample_dim']: Initial set (number) of KCC values to be generated to be sent to VRM for deviation pattern simulation
:type samplin... | """The Sampling configuration file consists of the parameters which conducting adaptive sampling/active learning from the VRM system
:param sampling_config['sample_dim']: Initial set (number) of KCC values to be generated to be sent to VRM for deviation pattern simulation
:type samplin... |
#! python3
# isPhoneNumber.py - Program without regular expressions to find a phone number in text
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4... | def is_phone_number(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
... |
# -*- coding:utf-8 -*-
def payment(balance, paid):
if balance < paid:
return balance, 0
else:
return paid, balance - paid
if __name__ == '__main__':
balance = float(input("Enter opening balance: "))
paid = float(input("Enter monthly payment: "))
print(" Amount Remaining")
... | def payment(balance, paid):
if balance < paid:
return (balance, 0)
else:
return (paid, balance - paid)
if __name__ == '__main__':
balance = float(input('Enter opening balance: '))
paid = float(input('Enter monthly payment: '))
print(' Amount Remaining')
print('Pymt# Paid ... |
# Title : Lambda example
# Author : Kiran raj R.
# Date : 31:10:2020
def higher_o_func(x, func): return x + func(x)
result1 = higher_o_func(2, lambda x: x * x)
# result1 x = 2, (2*2) + 2, x = 6
result2 = higher_o_func(2, lambda x: x + 3)
# result2 x=2, (2 + 3) + 2, x = 7
result3 = higher_o_func(4, lambda x: x*... | def higher_o_func(x, func):
return x + func(x)
result1 = higher_o_func(2, lambda x: x * x)
result2 = higher_o_func(2, lambda x: x + 3)
result3 = higher_o_func(4, lambda x: x * x)
result4 = higher_o_func(4, lambda x: x + 3)
print(result1, result2)
print(result3, result4)
def add(x, y):
return x + y
result5 = ad... |
class ListTransformer():
def __init__(self, _list):
self._list = _list
@property
def tuple(self):
return tuple(self._list)
| class Listtransformer:
def __init__(self, _list):
self._list = _list
@property
def tuple(self):
return tuple(self._list) |
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
# Time Complexity: O(N)
# Space Complexity: O(1)
longest = releaseTimes[0]
slowestKey = keysPressed[0]
for i in range(1, len(releaseTimes)):
... | class Solution:
def slowest_key(self, releaseTimes: List[int], keysPressed: str) -> str:
longest = releaseTimes[0]
slowest_key = keysPressed[0]
for i in range(1, len(releaseTimes)):
cur = releaseTimes[i] - releaseTimes[i - 1]
if cur > longest or (cur == longest and k... |
def main():
# Write code here
while True:
N=int(input())
if 1<=N and N<=100:
break
List_elements=[]
List_elements=[int(x) for x in input().split()]
#List_elements.append(element)
List_elements.sort()
print(List_elements)
Absent_students=[]
... | def main():
while True:
n = int(input())
if 1 <= N and N <= 100:
break
list_elements = []
list_elements = [int(x) for x in input().split()]
List_elements.sort()
print(List_elements)
absent_students = []
for i in range(N):
if i + 1 not in List_elements:
... |
# -*- coding: utf-8 -*-
def test_modules_durations(testdir):
# create a temporary pytest test module
testdir.makepyfile(
test_foo="""
def test_sth():
assert 2 + 2 == 4
"""
)
# run pytest with the following cmd args
result = testdir.runpytest("--modules-durations=2... | def test_modules_durations(testdir):
testdir.makepyfile(test_foo='\n def test_sth():\n assert 2 + 2 == 4\n ')
result = testdir.runpytest('--modules-durations=2')
result.stdout.fnmatch_lines(['*s test_foo.py'])
assert 'sum of all tests durations' in '\n'.join(result.stdout.lines)
... |
load(":dev_binding.bzl", "envoy_dev_binding")
load(":genrule_repository.bzl", "genrule_repository")
load("@envoy_api//bazel:envoy_http_archive.bzl", "envoy_http_archive")
load("@envoy_api//bazel:external_deps.bzl", "load_repository_locations")
load(":repository_locations.bzl", "REPOSITORY_LOCATIONS_SPEC")
load("@com_go... | load(':dev_binding.bzl', 'envoy_dev_binding')
load(':genrule_repository.bzl', 'genrule_repository')
load('@envoy_api//bazel:envoy_http_archive.bzl', 'envoy_http_archive')
load('@envoy_api//bazel:external_deps.bzl', 'load_repository_locations')
load(':repository_locations.bzl', 'REPOSITORY_LOCATIONS_SPEC')
load('@com_go... |
class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
Time: O(log n)
Space: O(1)
"""
low = 0
high = len(nums) - 1
while low < high:
m1 = (low + high) // 2
m2 = m1 + 1
if nums[... | class Solution:
def find_peak_element(self, nums):
"""
:type nums: List[int]
:rtype: int
Time: O(log n)
Space: O(1)
"""
low = 0
high = len(nums) - 1
while low < high:
m1 = (low + high) // 2
m2 = m1 + 1
if nu... |
def get_gini(loc, sheet):
df = pd.read_excel(loc,sheet_name = sheet)
df_2 = df[['PD','Default']]
gini_df = df_2.sort_values(by=["PD"],ascending=False)
gini_df.reset_index()
D = sum(gini_df['Default'])
N = len(gini_df['Default'])
default = np.array(gini_df.Default)
proxy_data_arr = np.cum... | def get_gini(loc, sheet):
df = pd.read_excel(loc, sheet_name=sheet)
df_2 = df[['PD', 'Default']]
gini_df = df_2.sort_values(by=['PD'], ascending=False)
gini_df.reset_index()
d = sum(gini_df['Default'])
n = len(gini_df['Default'])
default = np.array(gini_df.Default)
proxy_data_arr = np.cu... |
VALID_COLORS = ['blue', 'yellow', 'red']
def print_colors():
while True:
color = input('Enter a color: ').lower()
if color == 'quit':
print('bye')
break
if color not in VALID_COLORS:
print('Not a valid color')
continue
prin... | valid_colors = ['blue', 'yellow', 'red']
def print_colors():
while True:
color = input('Enter a color: ').lower()
if color == 'quit':
print('bye')
break
if color not in VALID_COLORS:
print('Not a valid color')
continue
print(color)
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return he... | class Solution(object):
def reverse_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
prev = None
curr = head
while curr is not None:
next = curr.next
curr.next = prev
... |
a = int(input())
b = {}
def fab(a):
if a<=1:
return 1
if a in b:
return b[a]
b[a]=fab(a-1)+fab(a-2)
return b[a]
print(fab(a))
print(b)
#1 1 2 3 5 8 13 21 34
| a = int(input())
b = {}
def fab(a):
if a <= 1:
return 1
if a in b:
return b[a]
b[a] = fab(a - 1) + fab(a - 2)
return b[a]
print(fab(a))
print(b) |
# Mocapy: A parallelized Dynamic Bayesian Network toolkit
#
# Copyright (C) 2004 Thomas Hamelryck
#
# This library 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... | """
Mocapy exception classes.
"""
class Mocapyexception(Exception):
pass
class Mocapyvectorexception(MocapyException):
pass
class Mocapydbnexception(MocapyException):
pass
class Mocapyvmfexception(MocapyException):
pass
class Mocapygaussianexception(MocapyException):
pass
class Mocapydiscretee... |
def gen():
yield 3 # Like return but one by one
yield 'wow'
yield -1
yield 1.2
x = gen()
print(next(x)) # Use next() function to go one by one
print(next(x))
print(next(x))
print(next(x)) | def gen():
yield 3
yield 'wow'
yield (-1)
yield 1.2
x = gen()
print(next(x))
print(next(x))
print(next(x))
print(next(x)) |
class MTransformationMatrix(object):
"""
Manipulate the individual components of a transformation.
"""
def __eq__(*args, **kwargs):
"""
x.__eq__(y) <==> x==y
"""
pass
def __ge__(*args, **kwargs):
"""
x.__ge__(y) <==> x>=y
... | class Mtransformationmatrix(object):
"""
Manipulate the individual components of a transformation.
"""
def __eq__(*args, **kwargs):
"""
x.__eq__(y) <==> x==y
"""
pass
def __ge__(*args, **kwargs):
"""
x.__ge__(y) <==> x>=y
"""
pass
... |
def tokenize(sentence):
return sentence.split(" ")
class InvertedIndex:
def __init__(self):
self.dict = {}
def get_docs_ids(self, token):
if token in self.dict:
return self.dict[token]
else:
return []
def put_token(self, token, doc_i... | def tokenize(sentence):
return sentence.split(' ')
class Invertedindex:
def __init__(self):
self.dict = {}
def get_docs_ids(self, token):
if token in self.dict:
return self.dict[token]
else:
return []
def put_token(self, token, doc_id):
if toke... |
VERSION = "1.1"
SOCKET_PATH = "/tmp/optimus-manager"
SOCKET_TIMEOUT = 1.0
STARTUP_MODE_VAR_PATH = "/var/lib/optimus-manager/startup_mode"
REQUESTED_MODE_VAR_PATH = "/var/lib/optimus-manager/requested_mode"
DPI_VAR_PATH = "/var/lib/optimus-manager/dpi"
TEMP_CONFIG_PATH_VAR_PATH = "/var/lib/optimus-manager/temp_conf_pa... | version = '1.1'
socket_path = '/tmp/optimus-manager'
socket_timeout = 1.0
startup_mode_var_path = '/var/lib/optimus-manager/startup_mode'
requested_mode_var_path = '/var/lib/optimus-manager/requested_mode'
dpi_var_path = '/var/lib/optimus-manager/dpi'
temp_config_path_var_path = '/var/lib/optimus-manager/temp_conf_path... |
#!/usr/bin/env python3
"""
Copyright (c) 2019: Scott Atkins <scott@kins.dev>
(https://git.kins.dev/igrill-smoker)
License: MIT License
See the LICENSE file
"""
__author__ = "Scott Atkins"
__version__ = "1.4.0"
__license__ = "MIT" | """
Copyright (c) 2019: Scott Atkins <scott@kins.dev>
(https://git.kins.dev/igrill-smoker)
License: MIT License
See the LICENSE file
"""
__author__ = 'Scott Atkins'
__version__ = '1.4.0'
__license__ = 'MIT' |
'''
Create a customer class
Add a constructor with parameters first, last, and phone_number
Create public attributes for first, last, and phone_number
STUDENT MUST ALSO MODIFY INVOICE CLASS TO USE THIS CLASS
SEE INVOICE file FOR INSTRUCTIONS
'''
class Customer:
def __init__(self, first, last, phone_number):
... | """
Create a customer class
Add a constructor with parameters first, last, and phone_number
Create public attributes for first, last, and phone_number
STUDENT MUST ALSO MODIFY INVOICE CLASS TO USE THIS CLASS
SEE INVOICE file FOR INSTRUCTIONS
"""
class Customer:
def __init__(self, first, last, phone_number):
... |
d=[int(i) for i in input().split()]
s=sum(d)
result=0
if s%len(d)==0:
for i in range(len(d)):
if d[i]<(s//len(d)):
result=result+((s//len(d))-d[i])
print(result,end='')
else:
print('-1',end='') | d = [int(i) for i in input().split()]
s = sum(d)
result = 0
if s % len(d) == 0:
for i in range(len(d)):
if d[i] < s // len(d):
result = result + (s // len(d) - d[i])
print(result, end='')
else:
print('-1', end='') |
N = int(input())
def brute_force(s, remain):
if remain == 0:
print(s)
else:
brute_force(s + "a", remain - 1)
brute_force(s + "b", remain - 1)
brute_force(s + "c", remain - 1)
brute_force("", N)
| n = int(input())
def brute_force(s, remain):
if remain == 0:
print(s)
else:
brute_force(s + 'a', remain - 1)
brute_force(s + 'b', remain - 1)
brute_force(s + 'c', remain - 1)
brute_force('', N) |
"""
"""
# Created on 2019.08.31
#
# Author: Giovanni Cannata
#
# Copyright 2014 - 2020 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Founda... | """
"""
edir_9_1_4_schema = '\n{\n "raw": {\n "attributeTypes": [\n "( 2.5.4.35 NAME \'userPassword\' DESC \'Internal NDS policy forces this to be single-valued\' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} USAGE directoryOperation )",\n "( 2.5.18.1 NAME \'createTimestamp\' DESC \'Operatio... |
class School:
def __init__(self, name, num_pupils, num_classrooms):
self.name = name
self.num_pupils = num_pupils
self.num_classrooms = num_classrooms
def calculate_average_pupils(self):
return self.num_pupils / self.num_classrooms
def show_info(self):
"""
>>> s = School("Eveyln Intermediate", 96, 15... | class School:
def __init__(self, name, num_pupils, num_classrooms):
self.name = name
self.num_pupils = num_pupils
self.num_classrooms = num_classrooms
def calculate_average_pupils(self):
return self.num_pupils / self.num_classrooms
def show_info(self):
"""
>>> s ... |
class FatalErrorResponse:
def __init__(self, message):
self._message = message
self.result = message
self.id = "error"
def get_audit_text(self):
return 'error = "{0}", (NOT PUBLISHED)'.format(self._message)
| class Fatalerrorresponse:
def __init__(self, message):
self._message = message
self.result = message
self.id = 'error'
def get_audit_text(self):
return 'error = "{0}", (NOT PUBLISHED)'.format(self._message) |
"""
Copyright 2010 Rusty Klophaus <rusty@basho.com>
Copyright 2010 Justin Sheehy <justin@basho.com>
Copyright 2009 Jay Baird <jay@mochimedia.com>
This file is provided to you 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 o... | """
Copyright 2010 Rusty Klophaus <rusty@basho.com>
Copyright 2010 Justin Sheehy <justin@basho.com>
Copyright 2009 Jay Baird <jay@mochimedia.com>
This file is provided to you 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 o... |
def my_init(shape, dtype=None):
array = np.array([
[0.0, 0.2, 0.0],
[0.0, -0.2, 0.0],
[0.0, 0.0, 0.0],
])
# adds two axis to match the required shape (3,3,1,1)
return np.expand_dims(np.expand_dims(array,-1),-1)
conv_edge = Sequential([
Conv2D(kernel_size=(3,3), filters=1,... | def my_init(shape, dtype=None):
array = np.array([[0.0, 0.2, 0.0], [0.0, -0.2, 0.0], [0.0, 0.0, 0.0]])
return np.expand_dims(np.expand_dims(array, -1), -1)
conv_edge = sequential([conv2_d(kernel_size=(3, 3), filters=1, padding='same', kernel_initializer=my_init, input_shape=(None, None, 1))])
img_in = np.expand... |
banks = [
# bank 0
{
'ram': {
'start': 0xB848,
'end': 0xBFCF
},
'rom': {
'start': 0x3858,
'end': 0x3FDF
},
'offset': 0
},
# bank 1
{
'ram': {
'start': 0xB8CC,
'end': 0xB... | banks = [{'ram': {'start': 47176, 'end': 49103}, 'rom': {'start': 14424, 'end': 16351}, 'offset': 0}, {'ram': {'start': 47308, 'end': 49103}, 'rom': {'start': 30940, 'end': 32735}, 'offset': 0}, {'ram': {'start': 48867, 'end': 49102}, 'rom': {'start': 48883, 'end': 49118}, 'offset': 0}, {'ram': {'start': 40182, 'end': ... |
majors = {
"UND": "Undeclared",
"UNON": "Non Degree",
"ANTH": "Anthropology",
"APPH": "Applied Physics",
"ART": "Art",
"ARTG": "Art And Design: Games And Playable Media",
"ARTH": "See History Of Art And Visual Culture",
"BENG": "Bioengineering",
"BIOC": "Biochemistry And Molecular Biology",
"BINF": "Bioinformatics",
"B... | majors = {'UND': 'Undeclared', 'UNON': 'Non Degree', 'ANTH': 'Anthropology', 'APPH': 'Applied Physics', 'ART': 'Art', 'ARTG': 'Art And Design: Games And Playable Media', 'ARTH': 'See History Of Art And Visual Culture', 'BENG': 'Bioengineering', 'BIOC': 'Biochemistry And Molecular Biology', 'BINF': 'Bioinformatics', 'BI... |
class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
"""
ints are unique
is it guaranteed there will be a winner? - YES
- YES: if the array is already sorted in reverse order
- YES: if array is in sorted order, and
arr = [1,11,22,33,44,55,66,77,88,99]... | class Solution:
def get_winner(self, arr: List[int], k: int) -> int:
"""
ints are unique
is it guaranteed there will be a winner? - YES
- YES: if the array is already sorted in reverse order
- YES: if array is in sorted order, and
arr = [1,11,22,33,44,55,66,77,88,9... |
'''
from ..utils import gislib, utils, constants
from ..core.trajectorydataframe import *
import numpy as np
import pandas as pd
def stops(tdf, stop_radius_meters=20, minutes_for_a_stop=10):
""" Stops detection
Detect the stops for each individual in a TrajDataFrame. A stop is
detected when th... | '''
from ..utils import gislib, utils, constants
from ..core.trajectorydataframe import *
import numpy as np
import pandas as pd
def stops(tdf, stop_radius_meters=20, minutes_for_a_stop=10):
""" Stops detection
Detect the stops for each individual in a TrajDataFrame. A stop is
detected when th... |
unknown_error = (1000, 'unknown_error', 400)
access_forbidden = (1001, 'access_forbidden', 403)
unimplemented_error = (1002, 'unimplemented_error', 400)
not_found = (1003, 'not_found', 404)
illegal_state = (1004, 'illegal_state', 400)
| unknown_error = (1000, 'unknown_error', 400)
access_forbidden = (1001, 'access_forbidden', 403)
unimplemented_error = (1002, 'unimplemented_error', 400)
not_found = (1003, 'not_found', 404)
illegal_state = (1004, 'illegal_state', 400) |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/waymo_open_2d_detection_f0.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(bbox_head=dict(num_classes=3))
data = dict(samples_per_gpu=4)
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, wei... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/waymo_open_2d_detection_f0.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
model = dict(bbox_head=dict(num_classes=3))
data = dict(samples_per_gpu=4)
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)... |
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | {'variables': {'v8_code': 1, 'generated_file': '<(SHARED_INTERMEDIATE_DIR)/resources.cc'}, 'includes': ['../../build/toolchain.gypi', '../../build/features.gypi'], 'targets': [{'target_name': 'cctest', 'type': 'executable', 'dependencies': ['resources', '../../tools/gyp/v8.gyp:v8_libplatform'], 'include_dirs': ['../..'... |
class DataGridViewColumnStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.ColumnStateChanged event.
DataGridViewColumnStateChangedEventArgs(dataGridViewColumn: DataGridViewColumn,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __ne... | class Datagridviewcolumnstatechangedeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.ColumnStateChanged event.
DataGridViewColumnStateChangedEventArgs(dataGridViewColumn: DataGridViewColumn,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: identity_group_info
short_description: Information module for Identity Group
description:
- Get all Identity Group... | documentation = '\n---\nmodule: identity_group_info\nshort_description: Information module for Identity Group\ndescription:\n- Get all Identity Group.\n- Get Identity Group by id.\n- Get Identity Group by name.\nversion_added: \'1.0.0\'\nauthor: Rafael Campos (@racampos)\noptions:\n name:\n description:\n - Name... |
# -*- coding: UTF-8 -*-
light = input('please input a light')
'''
if light =='red':
print('stop')
else:
if light =='green':
print('GoGoGO')
else:
if light=='yellow':
print('stop or Go fast')
else:
print('Light is bad!!!')
'''
if light == 'red':
print('Stop... | light = input('please input a light')
"\nif light =='red':\n print('stop')\nelse:\n if light =='green':\n print('GoGoGO')\n else:\n if light=='yellow':\n print('stop or Go fast')\n else:\n print('Light is bad!!!')\n"
if light == 'red':
print('Stop')
elif light == ... |
class PluginInterface:
hooks = {}
load = False
defaultState = False
def getAuthor(self) -> str:
return ""
def getCommands(self) -> list:
return [] | class Plugininterface:
hooks = {}
load = False
default_state = False
def get_author(self) -> str:
return ''
def get_commands(self) -> list:
return [] |
def enum(name, *sequential, **named):
values = dict(zip(sequential, range(len(sequential))), **named)
# NOTE: Yes, we *really* want to cast using str() here.
# On Python 2 type() requires a byte string (which is str() on Python 2).
# On Python 3 it does not matter, so we'll use str(), which acts as
... | def enum(name, *sequential, **named):
values = dict(zip(sequential, range(len(sequential))), **named)
return type(str(name), (), values) |
class Configuration(object):
"""Model hyper parameters and data information"""
""" Path to different files """
source_alphabet = './data/EnPe/source.txt'
target_alphabet = './data/EnPe/target.txt'
train_set = './data/EnPe/mytrain.txt'
dev_set = './data/EnPe/mydev.txt'
test_set = './data/EnP... | class Configuration(object):
"""Model hyper parameters and data information"""
' Path to different files '
source_alphabet = './data/EnPe/source.txt'
target_alphabet = './data/EnPe/target.txt'
train_set = './data/EnPe/mytrain.txt'
dev_set = './data/EnPe/mydev.txt'
test_set = './data/EnPe/myt... |
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Webcam',
# list of one or more authors for the module
... | class Module:
def __init__(self, mainMenu, params=[]):
self.info = {'Name': 'Webcam', 'Author': ['Juuso Salonen'], 'Description': "Searches for keychain candidates and attempts to decrypt the user's keychain.", 'Background': False, 'OutputExtension': '', 'NeedsAdmin': True, 'OpsecSafe': False, 'Comments': ... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/ObjectCount.msg;/home/pnu/catkin_ws/devel/shar... | messages_str = '/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/ObjectCount.msg;/home/pnu/catkin_ws/devel/share/darknet_ros_msgs/msg/CheckForObjectsAction.msg;/hom... |
""".. Ignore pydocstyle D400.
=========
Shortcuts
=========
Shortcut mixin classes
======================
.. autoclass:: resdk.shortcuts.collection.CollectionRelationsMixin
:members:
"""
| """.. Ignore pydocstyle D400.
=========
Shortcuts
=========
Shortcut mixin classes
======================
.. autoclass:: resdk.shortcuts.collection.CollectionRelationsMixin
:members:
""" |
class ExceptionMissingFile:
"""
An exception class for errors detected at runtime, thrown when OCIO cannot
find a file that is expected to exist. This is provided as a custom type to
distinguish cases where one wants to continue looking for missing files,
but wants to properly fail for other error ... | class Exceptionmissingfile:
"""
An exception class for errors detected at runtime, thrown when OCIO cannot
find a file that is expected to exist. This is provided as a custom type to
distinguish cases where one wants to continue looking for missing files,
but wants to properly fail for other error c... |
"""Algorithm to select influential nodes in a graph using VoteRank."""
__all__ = ["voterank"]
def voterank(G, number_of_nodes=None):
"""Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank [1]_ computes a ranking of the nodes in a graph G based on a
voting scheme. With VoteRan... | """Algorithm to select influential nodes in a graph using VoteRank."""
__all__ = ['voterank']
def voterank(G, number_of_nodes=None):
"""Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank [1]_ computes a ranking of the nodes in a graph G based on a
voting scheme. With VoteRank,... |
def arrayMaxConsecutiveSum(inputArray, k):
arr = [sum(inputArray[:k])]
for i in range(1, len(inputArray) - (k - 1)):
arr.append(arr[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
sort_arr = sorted(arr)
return sort_arr[-1]
| def array_max_consecutive_sum(inputArray, k):
arr = [sum(inputArray[:k])]
for i in range(1, len(inputArray) - (k - 1)):
arr.append(arr[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
sort_arr = sorted(arr)
return sort_arr[-1] |
# O(n) time | O(1) space
def find_loop(head):
"""
Returns the node that originates a loop if a loop exists
"""
if not head:
return None
slow, fast = head, head
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if slow is fast:
... | def find_loop(head):
"""
Returns the node that originates a loop if a loop exists
"""
if not head:
return None
(slow, fast) = (head, head)
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if slow is fast:
break
if... |
# output: ok
input = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
expected = [11, 8, 30, 2.5, 2, 4, 10000000, 20, 2, 2, 14, 15]
def test(v):
v[0] += 1
v[1] -= 2
v[2] *= 3
v[3] /= 4
v[4] //= 5
v[5] %= 6
v[6] **= 7
v[7] <<= 1
v[8] >>= 2
v[9] &= 3
v[10] ^= 4
v[11] |= 5... | input = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
expected = [11, 8, 30, 2.5, 2, 4, 10000000, 20, 2, 2, 14, 15]
def test(v):
v[0] += 1
v[1] -= 2
v[2] *= 3
v[3] /= 4
v[4] //= 5
v[5] %= 6
v[6] **= 7
v[7] <<= 1
v[8] >>= 2
v[9] &= 3
v[10] ^= 4
v[11] |= 5
return v
... |
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
#s = "ab"
#wordDict = ["a","b"]
#s="aaaaaaa"
#wordDict=["aaaa","aa","a"]
#wordDict=["a","aa","aaaa"]
s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... | s = 'catsanddog'
word_dict = ['cat', 'cats', 'and', 'sand', 'dog']
s = 'pineapplepenapple'
word_dict = ['apple', 'pen', 'applepen', 'pine', 'pineapple']
s = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
word_dict ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Hans-Joachim Kliemeck <git@kliemeck.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported... | ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'}
documentation = '\n---\nmodule: win_share\nversion_added: "2.1"\nshort_description: Manage Windows shares\ndescription:\n - Add, modify or remove Windows share and set share permissions.\nrequirements:\n - As this module use... |
# Program verificare nr prim/compus
num = int(input("Enter number: "))
# nr prime sunt mai mari decat 1
if num > 1:
# verificare
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"... | num = int(input('Enter number: '))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, 'is not a prime number')
print(i, 'times', num // i, 'is', num)
break
else:
print(num, 'is a prime number')
else:
print(num, 'is not a prime number') |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"routes": {
"10.121.65.0/24": {
"active": True,
"candidate_default": False,
"dat... | expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'routes': {'10.121.65.0/24': {'active': True, 'candidate_default': False, 'date': '7w0d', 'metric': 20, 'next_hop': {'next_hop_list': {1: {'index': 1, 'next_hop': '10.121.64.35', 'outgoing_interface_name': 'inside'}, 2: {'index': 2, 'next_hop': '10.121.... |
#n=int(input('Diga o valor'))
#print('O quadrado {}'.format(n**2))
#print('O Antecessor {} Sucessor {}'.format(n+1,n-1))
dist=int(input('Diga o valor Distancia'))
comb=int(input('Diga o valor Combustivel'))
print('O consumo Medio {}'.format(dist/comb))
| dist = int(input('Diga o valor Distancia'))
comb = int(input('Diga o valor Combustivel'))
print('O consumo Medio {}'.format(dist / comb)) |
def ali_sta_seznama_enaka(sez1, sez2):
slo1 = {}
slo2 = {}
for i in sez1:
slo1[i] = slo1.get(i, 0) + 1
for i in sez2:
slo2[i] = slo2.get(i, 0) + 1
if slo1 == slo2:
return True
else:
return False
def permutacijsko_stevilo():
x = 1
while True:
sez1 ... | def ali_sta_seznama_enaka(sez1, sez2):
slo1 = {}
slo2 = {}
for i in sez1:
slo1[i] = slo1.get(i, 0) + 1
for i in sez2:
slo2[i] = slo2.get(i, 0) + 1
if slo1 == slo2:
return True
else:
return False
def permutacijsko_stevilo():
x = 1
while True:
sez1 ... |
# Tuples of RA,dec in degrees
ELAISS1 = (9.45, -44.)
XMM_LSS = (35.708333, -4-45/60.)
ECDFS = (53.125, -28.-6/60.)
COSMOS = (150.1, 2.+10./60.+55/3600.)
EDFS_a = (58.90, -49.315)
EDFS_b = (63.6, -47.60)
def ddf_locations():
"""Return the DDF locations as as dict. RA and dec in degrees.
"""
result = {}
... | elaiss1 = (9.45, -44.0)
xmm_lss = (35.708333, -4 - 45 / 60.0)
ecdfs = (53.125, -28.0 - 6 / 60.0)
cosmos = (150.1, 2.0 + 10.0 / 60.0 + 55 / 3600.0)
edfs_a = (58.9, -49.315)
edfs_b = (63.6, -47.6)
def ddf_locations():
"""Return the DDF locations as as dict. RA and dec in degrees.
"""
result = {}
result['... |
def solution(s: str) -> bool:
stack = []
left = 0
right = 0
for c in s:
if not stack:
if c == ")":
return False
stack.append(c)
left += 1
continue
if c == ")":
if stack[-1] == "(":
stack.pop()
... | def solution(s: str) -> bool:
stack = []
left = 0
right = 0
for c in s:
if not stack:
if c == ')':
return False
stack.append(c)
left += 1
continue
if c == ')':
if stack[-1] == '(':
stack.pop()
... |
self.description = "Quick check for using XferCommand"
# this setting forces us to download packages
self.cachepkgs = False
#wget doesn't support file:// urls. curl does
self.option['XferCommand'] = ['/usr/bin/curl %u -o %o']
numpkgs = 10
pkgnames = []
for i in range(numpkgs):
name = "pkg_%s" % i
pkgnames.ap... | self.description = 'Quick check for using XferCommand'
self.cachepkgs = False
self.option['XferCommand'] = ['/usr/bin/curl %u -o %o']
numpkgs = 10
pkgnames = []
for i in range(numpkgs):
name = 'pkg_%s' % i
pkgnames.append(name)
p = pmpkg(name)
p.files = ['usr/bin/foo-%s' % i]
self.addpkg2db('sync', ... |
class Solution:
def search(self, nums: List[int], target: int) -> bool:
start_idx = 0
for i in range(len(nums)-1):
if nums[i] > nums[i + 1]:
start_idx = i + 1
break
originList = nums[start_idx:] + nums[:start_idx]
... | class Solution:
def search(self, nums: List[int], target: int) -> bool:
start_idx = 0
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
start_idx = i + 1
break
origin_list = nums[start_idx:] + nums[:start_idx]
if target < originList... |
VERSION = (0, 6)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Ministry of Justice'
__email__ = 'dev@digital.justice.gov.uk'
default_app_config = 'govuk_forms.apps.FormsAppConfig'
| version = (0, 6)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Ministry of Justice'
__email__ = 'dev@digital.justice.gov.uk'
default_app_config = 'govuk_forms.apps.FormsAppConfig' |
# -*- coding: utf-8 -*-
VERSION = (1, 0, 0, 'beta')
__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = 'Kuba Janoszek'
| version = (1, 0, 0, 'beta')
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Kuba Janoszek' |
"""Show how to use list comprehensions and zip"""
sunday_temps = [76, 78, 86, 54, 88, 77, 66, 55, 44, 57, 58, 58, 78, 79, 69, 65]
monday_temps = [68, 67, 68, 76, 77, 66, 61, 81, 73, 61, 83, 67, 89, 78, 67, 85]
tuesday_temps = [78, 79, 70, 76, 75, 74, 73, 72, 63, 64, 65, 58, 59, 85, 59, 85]
def show_temp_tuples():
... | """Show how to use list comprehensions and zip"""
sunday_temps = [76, 78, 86, 54, 88, 77, 66, 55, 44, 57, 58, 58, 78, 79, 69, 65]
monday_temps = [68, 67, 68, 76, 77, 66, 61, 81, 73, 61, 83, 67, 89, 78, 67, 85]
tuesday_temps = [78, 79, 70, 76, 75, 74, 73, 72, 63, 64, 65, 58, 59, 85, 59, 85]
def show_temp_tuples():
... |
# Make an algorithm that reads an employee's salary and shows his new salary, with a 15% increase
n1 = float(input('Enter the employee`s salary: US$ '))
n2 = n1 * 1.15
print('The new salary, with 15% increase, is US${:.2f}'.format(n2))
| n1 = float(input('Enter the employee`s salary: US$ '))
n2 = n1 * 1.15
print('The new salary, with 15% increase, is US${:.2f}'.format(n2)) |
def test():
test_instructions = """0
3
0
1
-3"""
assert run(test_instructions) == 5
def run(in_val):
instructions = [int(instruction) for instruction in in_val.split()]
rel_offsets = {}
register = 0
steps = 0
while True:
try:
instruction = instructions[register]
... | def test():
test_instructions = '0\n3\n0\n1\n-3'
assert run(test_instructions) == 5
def run(in_val):
instructions = [int(instruction) for instruction in in_val.split()]
rel_offsets = {}
register = 0
steps = 0
while True:
try:
instruction = instructions[register]
... |
def get_string_count_to_by(to, by):
if by < 1:
raise ValueError("'by' must be > 0")
if to < 1:
raise ValueError("'to' must be > 0")
if to <= by:
return str(to)
return get_string_count_to_by(to - by, by) + ", " + str(to)
def count_to_by(to, by):
print(get_string_count_to_by(t... | def get_string_count_to_by(to, by):
if by < 1:
raise value_error("'by' must be > 0")
if to < 1:
raise value_error("'to' must be > 0")
if to <= by:
return str(to)
return get_string_count_to_by(to - by, by) + ', ' + str(to)
def count_to_by(to, by):
print(get_string_count_to_by... |
def sol():
N, M = map(int, input().split(" "))
data = sorted(list(map(int, input().split(" "))))
visited = [False] * (N + 1)
save = set()
dfs(N, M, data, visited, save, 0, "")
def dfs(N, M, data, visited, save, cnt, line):
if cnt == M:
if line not in save:
save.add(line)
... | def sol():
(n, m) = map(int, input().split(' '))
data = sorted(list(map(int, input().split(' '))))
visited = [False] * (N + 1)
save = set()
dfs(N, M, data, visited, save, 0, '')
def dfs(N, M, data, visited, save, cnt, line):
if cnt == M:
if line not in save:
save.add(line)
... |
def generate_instance_name(name):
out = name[0].lower()
for char in name[1:]:
if char.isupper():
out += "_%s" % char.lower()
else:
out += char
return out
def generate_human_name(name):
out = name[0]
for char in name[1:]:
if char.isupper():
... | def generate_instance_name(name):
out = name[0].lower()
for char in name[1:]:
if char.isupper():
out += '_%s' % char.lower()
else:
out += char
return out
def generate_human_name(name):
out = name[0]
for char in name[1:]:
if char.isupper():
... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py... | _base_ = ['../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py']
crop_size = (512, 512)
model = dict(backbone=dict(type='ConvNeXt', in_chans=3, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0.4, layer_scale_init_val... |
"""Utils module."""
__all__ = ['convert_choice', 'convert_loglevel', 'convert_predicate',
'convert_string', 'create_getter', 'create_setter', 'create_deleter']
def convert_choice(choices, *, converter=None, default=None):
"""Return a function that can be used as a converter.
For an example see th... | """Utils module."""
__all__ = ['convert_choice', 'convert_loglevel', 'convert_predicate', 'convert_string', 'create_getter', 'create_setter', 'create_deleter']
def convert_choice(choices, *, converter=None, default=None):
"""Return a function that can be used as a converter.
For an example see the source code... |
'''
Kompresi Benny
Menyederhanakan sebuah kata dengan membuat beberapa
karakter yang sama dan berurutan hanya akan menjadi
satu karakter saja.
'''
def kompresi(a_str):
'''
Mengompres a_str sehingga tidak ada
karakter yang sama yang bersebelahan.
Contoh: kompresi('aabbbbaaacddeae')
... | """
Kompresi Benny
Menyederhanakan sebuah kata dengan membuat beberapa
karakter yang sama dan berurutan hanya akan menjadi
satu karakter saja.
"""
def kompresi(a_str):
"""
Mengompres a_str sehingga tidak ada
karakter yang sama yang bersebelahan.
Contoh: kompresi('aabbbbaaacddeae')
akan me... |
__all__ = ['CommandError', 'CommandLineError']
class CommandError(Exception):
pass
class CommandLineError(Exception):
pass
class SubcommandError(Exception):
pass
class MaincommandError(Exception):
pass
class CommandCollectionError(Exception):
pass
| __all__ = ['CommandError', 'CommandLineError']
class Commanderror(Exception):
pass
class Commandlineerror(Exception):
pass
class Subcommanderror(Exception):
pass
class Maincommanderror(Exception):
pass
class Commandcollectionerror(Exception):
pass |
# Copyright (c) 2021, Carlos Millett
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the Simplified BSD License. See the LICENSE file for details.
'''
Renamer renames your TV files into a nice new format.
The new filename includes the TV show name, season and episode num... | """
Renamer renames your TV files into a nice new format.
The new filename includes the TV show name, season and episode numbers and
the episode title.
"""
__version__ = '0.3.2'
__author__ = 'Carlos Millett <carlos4735@gmail.com>' |
s = open('input.txt','r').read()
s = [k for k in s.split("\n")]
ans = 0
p = ""
q = 0
for line in s:
if line == "":
x = [0]*26
for i in p:
j = ord(i) - 97
if 0 <= j < 26:
x[j] += 1
ans += len([k for k in x if k == q])
p = ""
q = 0
... | s = open('input.txt', 'r').read()
s = [k for k in s.split('\n')]
ans = 0
p = ''
q = 0
for line in s:
if line == '':
x = [0] * 26
for i in p:
j = ord(i) - 97
if 0 <= j < 26:
x[j] += 1
ans += len([k for k in x if k == q])
p = ''
q = 0
... |
# Python - 3.6.0
def presses(phrase):
keypads = ['1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#']
times, i = 0, 0
for p in phrase.upper():
for keypad in keypads:
i = keypad.find(p)
if i >= 0:
break
times += i + 1
... | def presses(phrase):
keypads = ['1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#']
(times, i) = (0, 0)
for p in phrase.upper():
for keypad in keypads:
i = keypad.find(p)
if i >= 0:
break
times += i + 1
return tim... |
# Copyright 2017 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.
DEPS = [
'flavor',
'recipe_engine/properties',
'recipe_engine/raw_io',
'run',
'vars',
]
def test_exceptions(api):
try:
api.flavor.copy_dir... | deps = ['flavor', 'recipe_engine/properties', 'recipe_engine/raw_io', 'run', 'vars']
def test_exceptions(api):
try:
api.flavor.copy_directory_contents_to_device('src', 'dst')
except ValueError:
pass
try:
api.flavor.copy_directory_contents_to_host('src', 'dst')
except ValueError:... |
pass_marks = 70
if pass_marks == 70:
print('pass')
its_raining = True # you can change this to False
if its_raining:
print("It's raining!")
its_raining = True # you can change this to False
its_not_raining = not its_raining # False if its_raining, True otherwise
if its... | pass_marks = 70
if pass_marks == 70:
print('pass')
its_raining = True
if its_raining:
print("It's raining!")
its_raining = True
its_not_raining = not its_raining
if its_raining:
print("It's raining!")
if its_not_raining:
print("It's not raining.")
if its_raining:
print("It's raining!")
else:
pri... |
a = 28
b = 1.5
c = "Hello!"
d = True
e = None
| a = 28
b = 1.5
c = 'Hello!'
d = True
e = None |
#1) Indexing lists and tuples
list_values = [1, 2, 3]
set_values = (10, 20, 30)
print(list_values[0])
print(set_values[0])
#2) Changing values: lists vs tuples
list_values = [1, 2, 3]
set_values = (10, 20, 30)
list_values[0] = 100
print(list_values)
set_values[0] = 100
#3) Tuple vs List Expanding
list_values = ... | list_values = [1, 2, 3]
set_values = (10, 20, 30)
print(list_values[0])
print(set_values[0])
list_values = [1, 2, 3]
set_values = (10, 20, 30)
list_values[0] = 100
print(list_values)
set_values[0] = 100
list_values = [1, 2, 3]
set_values = (1, 2, 3)
print(id(list_values))
print(id(set_values))
print()
list_values += [4... |
#!/usr/bin/env python3
"""
This reads a log file and verifies that all the 'action' entries are
corrent. And action entry looks like:
act: key value up-card action
"""
act_line = ''
def main():
global act_line
with open('trace.txt', 'rt') as fd:
for line in fd:
line = line.rstrip()
... | """
This reads a log file and verifies that all the 'action' entries are
corrent. And action entry looks like:
act: key value up-card action
"""
act_line = ''
def main():
global act_line
with open('trace.txt', 'rt') as fd:
for line in fd:
line = line.rstrip()
act_line = line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.