content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Copyright (c) 2010 Spotify AB
# Copyright (c) 2010 Yelp
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify... | class Bootstrapaction(object):
def __init__(self, name, path, bootstrap_action_args):
self.name = name
self.path = path
if isinstance(bootstrap_action_args, basestring):
bootstrap_action_args = [bootstrap_action_args]
self.bootstrap_action_args = bootstrap_action_args
... |
def bond(output, i,j,Jz,Jx,S2=1):
if S2==1:
bond_half(output, i,j,Jz,Jx)
elif S2==2:
bond_one(output, i,j,Jz,Jx)
else:
error("S2 should be 1 or 2.")
def bond_half(output, i,j, Jz,Jx):
z = 0.25*Jz
x = 0.5*Jx
# diagonal
output.write('{} 0 {} 0 {} 0 {} 0 {} 0.0 \n'.format(i,i,j,j,z))
output.wr... | def bond(output, i, j, Jz, Jx, S2=1):
if S2 == 1:
bond_half(output, i, j, Jz, Jx)
elif S2 == 2:
bond_one(output, i, j, Jz, Jx)
else:
error('S2 should be 1 or 2.')
def bond_half(output, i, j, Jz, Jx):
z = 0.25 * Jz
x = 0.5 * Jx
output.write('{} 0 {} 0 {} 0 {} 0 {} 0.0 \n'... |
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
ans = int(2e5)
i = curr = 0
for j in range(len(nums)):
curr += nums[j]
while curr >= s:
curr -= nums[i]
ans = min(ans, j + 1 - i)
i += 1
return 0 if ans == int(2e5) else ans
| class Solution:
def min_sub_array_len(self, s: int, nums: List[int]) -> int:
ans = int(200000.0)
i = curr = 0
for j in range(len(nums)):
curr += nums[j]
while curr >= s:
curr -= nums[i]
ans = min(ans, j + 1 - i)
i += 1
... |
{'application':{'type':'Application',
'name':'Addresses',
'backgrounds':
[
{'type':'Background',
'name':'bgBody',
'title':'Addresses',
'position':(208,183),
'size':(416, 310),
'menubar':
{
'type':'MenuBar',
'menus':
[
{ 'type':'Menu',
'name':'menuFile',
... | {'application': {'type': 'Application', 'name': 'Addresses', 'backgrounds': [{'type': 'Background', 'name': 'bgBody', 'title': 'Addresses', 'position': (208, 183), 'size': (416, 310), 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': '... |
class API:
# BASE_URL
API_PREFIX = '/api/v1'
# REST Endpoints
ACCOUNT_BALANCE = '/accountbalance'
CURRENT_POSITIONS = '/currentpositions'
EXCHANGE_LIST = '/exchangelist'
HISTORICAL_ACCOUNT_BALANCES = '/historicalaccountbalances'
HISTORICAL_ORDER_FILLS = '/historicalorderfills'
SECU... | class Api:
api_prefix = '/api/v1'
account_balance = '/accountbalance'
current_positions = '/currentpositions'
exchange_list = '/exchangelist'
historical_account_balances = '/historicalaccountbalances'
historical_order_fills = '/historicalorderfills'
security_definition = '/securitydefinition... |
class KubeKrbMixin(object):
def __init__(self, **kwargs):
self.ticket_vol = "kerberos-data"
self.secret_name = "statesecret"
def inject_kerberos(self, kube_resources):
for r in kube_resources:
if r["kind"] == "Job":
for c in r["spec"]["template"]["spec"]["ini... | class Kubekrbmixin(object):
def __init__(self, **kwargs):
self.ticket_vol = 'kerberos-data'
self.secret_name = 'statesecret'
def inject_kerberos(self, kube_resources):
for r in kube_resources:
if r['kind'] == 'Job':
for c in r['spec']['template']['spec']['in... |
products = {
# 'Basil Hayden\'s 10 Year': '016679',
'Blade and Bow 22 Year': '016834',
'Blantons': '016850',
'Blantons Gold Label': '016841',
'Booker\'s': '016906',
'Buffalo Trace': '018006',
# 'Buffalo Trace Experimental': '0953565',
# 'Eagle Rare': '017766',
'Eagle Rare 17yr': '017... | products = {'Blade and Bow 22 Year': '016834', 'Blantons': '016850', 'Blantons Gold Label': '016841', "Booker's": '016906', 'Buffalo Trace': '018006', 'Eagle Rare 17yr': '017756', 'EH Taylor Barrel Proof': '021600', 'EH Taylor Four Grain': '021605', 'EH Taylor Single Barrel': '021589', 'EH Taylor Small Batch': '021602'... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'List[List[int]]':
return self.hasPathSum(root, sum, sum, 0)
def hasPathS... | class Solution:
def path_sum(self, root: 'TreeNode', sum: 'int') -> 'List[List[int]]':
return self.hasPathSum(root, sum, sum, 0)
def has_path_sum(self, root: 'TreeNode', sum: 'int', originalSum: 'int', dirty: 'int'):
if root == None:
return 0
elif root.right == None and roo... |
#
# PySNMP MIB module NETSERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSERVER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ... |
'''2. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30} '''
original_dict = {0: 10, 1: 20}
original_dict[2] = 30
print(original_dict) | """2. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30} """
original_dict = {0: 10, 1: 20}
original_dict[2] = 30
print(original_dict) |
# Class method return
# EXPECTED OUTPUT:
# case4.py: MyClass.hash -> dict
# case4.py: MyClass.get_hash() -> {}
class MyClass:
def __init__(self):
self.hash = {}
def get_hash(self):
return self.hash
| class Myclass:
def __init__(self):
self.hash = {}
def get_hash(self):
return self.hash |
# https://leetcode.com/problems/factorial-trailing-zeroes/
# https://practice.geeksforgeeks.org/problems/trailing-zeroes-in-factorial5134/1
class Solution:
def trailingZeroes(self, N):
j = 5
ans = 0
while j<=N:
ans = ans + N//j
j = j*5
return ans | class Solution:
def trailing_zeroes(self, N):
j = 5
ans = 0
while j <= N:
ans = ans + N // j
j = j * 5
return ans |
# train and classify variations
class ReadDepthLogisticClassifier (object):
'''
build a classifier using local read depth data with 2 possible labels
'''
def __init__( self, fasta, read_length ):
'''
@fasta: ProbabilisticFasta
@read_length: determines how local the features will be (i.... | class Readdepthlogisticclassifier(object):
"""
build a classifier using local read depth data with 2 possible labels
"""
def __init__(self, fasta, read_length):
"""
@fasta: ProbabilisticFasta
@read_length: determines how local the features will be (i.e. +/- read_legnth)
"""
... |
class Jumble(object):
def __init__(self):
self.dict = self.create_dict()
def create_dict(self):
f = open('/usr/share/dict/words', 'r')
sortedict = {}
for word in f:
word = word.strip().lower()
sort = ''.join(sorted(word))
sortedict[sort] = wor... | class Jumble(object):
def __init__(self):
self.dict = self.create_dict()
def create_dict(self):
f = open('/usr/share/dict/words', 'r')
sortedict = {}
for word in f:
word = word.strip().lower()
sort = ''.join(sorted(word))
sortedict[sort] = wo... |
class Task:
def __init__(self, robot):
self.robot = robot
def warmup(self):
pass
def run(self, input):
pass
def cooldown(self):
pass
def mock(self, input):
return "this is a test"
| class Task:
def __init__(self, robot):
self.robot = robot
def warmup(self):
pass
def run(self, input):
pass
def cooldown(self):
pass
def mock(self, input):
return 'this is a test' |
#!usr/bin/python3
#simple fizzbuzz solution
# Author: @fr4nkl1n-1k3h
for num in range(101):
if n%5 == 0 and n%3 == 0:
print('fizzbuzz',num,end="/n")
elif n%5 == 0:
print('buzz',num,end=" ")
elif n%3 == 0:
print('fizz',num, end=" ")
else:
print(num, end=" ")
print("Simpl... | for num in range(101):
if n % 5 == 0 and n % 3 == 0:
print('fizzbuzz', num, end='/n')
elif n % 5 == 0:
print('buzz', num, end=' ')
elif n % 3 == 0:
print('fizz', num, end=' ')
else:
print(num, end=' ')
print('Simple fizzbuzz by Fr4nkl1n-1keh') |
__title__ = "betfairlightweight"
__description__ = "Lightweight python wrapper for Betfair API-NG"
__url__ = "https://github.com/liampauling/betfair"
__version__ = "2.7.2"
__author__ = "Liam Pauling"
__license__ = "MIT"
| __title__ = 'betfairlightweight'
__description__ = 'Lightweight python wrapper for Betfair API-NG'
__url__ = 'https://github.com/liampauling/betfair'
__version__ = '2.7.2'
__author__ = 'Liam Pauling'
__license__ = 'MIT' |
class Operand:
def add(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
def subtract(self, x, y):
return x - y
def divide(self, x, y):
if y == 0:
return 0
return x / y | class Operand:
def add(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
def subtract(self, x, y):
return x - y
def divide(self, x, y):
if y == 0:
return 0
return x / y |
__version__ = "6.7.0"
__title__ = "slims-python-api"
__description__ = "A python api for SLims."
__uri__ = "http://www.genohm.com"
__author__ = "Genohm"
__email__ = "support@genohm.com"
__license__ = "TODO"
__copyright__ = "Copyright (c) 2016 Genohm"
| __version__ = '6.7.0'
__title__ = 'slims-python-api'
__description__ = 'A python api for SLims.'
__uri__ = 'http://www.genohm.com'
__author__ = 'Genohm'
__email__ = 'support@genohm.com'
__license__ = 'TODO'
__copyright__ = 'Copyright (c) 2016 Genohm' |
NEGATIVE_COLLECTION_FIDS = set(
(
"88513394757c43089cd44f817f16ca05", # Khadija Project Research Data
"45602a9bb6c04a179a2657e56ed3a310", # Mozambique Persons of Interest (2015)
"zz_occrp_pdi", # Persona de Interes (2014)
"ch_seco_sanctions", # Swiss SECO Sanctions
"inter... | negative_collection_fids = set(('88513394757c43089cd44f817f16ca05', '45602a9bb6c04a179a2657e56ed3a310', 'zz_occrp_pdi', 'ch_seco_sanctions', 'interpol_red_notices', '45602a9bb6c04a179a2657e56ed3a310', 'ru_pskov_people_2007', 'ua_antac_peps', 'am_voters', 'hr_gong_peps', 'hr_gong_companies', 'mk_dksk', 'ru_oligarchs', '... |
class ClientException(Exception):
pass
class ServerException(Exception):
pass
class BadRequestError(ServerException):
pass
class UnauthorizedError(ServerException):
pass
class NotFoundError(ServerException):
pass
class UnprocessableError(ServerException):
pass
class InternalServerErr... | class Clientexception(Exception):
pass
class Serverexception(Exception):
pass
class Badrequesterror(ServerException):
pass
class Unauthorizederror(ServerException):
pass
class Notfounderror(ServerException):
pass
class Unprocessableerror(ServerException):
pass
class Internalservererror(Ser... |
class DealResult(object):
'''
Details of a deal that has taken place.
'''
def __init__(self):
self.proposer = None
self.proposee = None
self.properties_transferred_to_proposer = []
self.properties_transferred_to_proposee = []
self.cash_transferred_from_proposer_t... | class Dealresult(object):
"""
Details of a deal that has taken place.
"""
def __init__(self):
self.proposer = None
self.proposee = None
self.properties_transferred_to_proposer = []
self.properties_transferred_to_proposee = []
self.cash_transferred_from_proposer_t... |
'''
Full write up is here! https://devclass.io/climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
**Example 1**
`Input: n = 2`
`Output: 2`
_Explanation_
There are two ways to climb to ... | """
Full write up is here! https://devclass.io/climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
**Example 1**
`Input: n = 2`
`Output: 2`
_Explanation_
There are two ways to climb to ... |
STATUS = {
'no_content': ('No content, check the request body', 204),
'unprocessable_entity': ('Unprocessable entity, check the request attributes', 422)
}
def missing_attributes(document, attributes):
for attribute in attributes:
if attribute not in document:
return True
return F... | status = {'no_content': ('No content, check the request body', 204), 'unprocessable_entity': ('Unprocessable entity, check the request attributes', 422)}
def missing_attributes(document, attributes):
for attribute in attributes:
if attribute not in document:
return True
return False |
# This module defines many standard colors that should be useful.
# These colors should be exactly the same as the ones defined in
# vtkNamedColors.h.
# Whites
antique_white = (0.9804, 0.9216, 0.8431)
azure = (0.9412, 1.0000, 1.0000)
bisque = (1.0000, 0.8941, 0.7686)
blanched_almond = (1.0000, 0.9216, 0.8039)
cornsil... | antique_white = (0.9804, 0.9216, 0.8431)
azure = (0.9412, 1.0, 1.0)
bisque = (1.0, 0.8941, 0.7686)
blanched_almond = (1.0, 0.9216, 0.8039)
cornsilk = (1.0, 0.9725, 0.8627)
eggshell = (0.99, 0.9, 0.79)
floral_white = (1.0, 0.9804, 0.9412)
gainsboro = (0.8627, 0.8627, 0.8627)
ghost_white = (0.9725, 0.9725, 1.0)
honeydew ... |
class Course:
def __init__(self, records: dict = None):
self.id: int = records.get('Id')
self.name: str = records.get('CourseName')
self.about: str = records.get('About')
self.about_exam: str = records.get('About Exam')
self.site: str = records.get('Site')
| class Course:
def __init__(self, records: dict=None):
self.id: int = records.get('Id')
self.name: str = records.get('CourseName')
self.about: str = records.get('About')
self.about_exam: str = records.get('About Exam')
self.site: str = records.get('Site') |
seconds = int(input("Enter number of seconds:"))
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
print(f"{days} day(s), {hours} hour(s), {minutes} minute(s), and {seconds} second(s).") | seconds = int(input('Enter number of seconds:'))
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
print(f'{days} day(s), {hours} hour(s), {minutes} minute(s), and {seconds} second(s).') |
# Interval List Intersections
class Solution:
def intervalIntersection(self, firstList, secondList):
fl, sl = len(firstList), len(secondList)
fi, si = 0, 0
inter = []
while fi < fl and si < sl:
f, s = firstList[fi], secondList[si]
if s[0] <= f[1] <= s[1]:
... | class Solution:
def interval_intersection(self, firstList, secondList):
(fl, sl) = (len(firstList), len(secondList))
(fi, si) = (0, 0)
inter = []
while fi < fl and si < sl:
(f, s) = (firstList[fi], secondList[si])
if s[0] <= f[1] <= s[1]:
inte... |
class InvalidParameter:
def __init__(self, reason: str):
self.reason = reason
| class Invalidparameter:
def __init__(self, reason: str):
self.reason = reason |
RESERVED_SUBSTITUTIONS = {
0x1D455: 0x210E, 0x1D49D: 0x212C, 0x1D4A0: 0x2130, 0x1D4A1: 0x2131,
0x1D4A3: 0x210B, 0x1D4A4: 0x2110, 0x1D4A7: 0x2112, 0x1D4A8: 0x2133,
0x1D4AD: 0x211B, 0x1D4BA: 0x212F, 0x1D4BC: 0x210A, 0x1D4C4: 0x2134,
0x1D506: 0x212D, 0x1D50B: 0x210C, 0x1D50C: 0x2111, 0x1D515: 0x211C,
0... | reserved_substitutions = {119893: 8462, 119965: 8492, 119968: 8496, 119969: 8497, 119971: 8459, 119972: 8464, 119975: 8466, 119976: 8499, 119981: 8475, 119994: 8495, 119996: 8458, 120004: 8500, 120070: 8493, 120075: 8460, 120076: 8465, 120085: 8476, 120093: 8488, 120122: 8450, 120127: 8461, 120133: 8469, 120135: 8473, ... |
class Solution:
# @param A : tuple of integers
# @return an integer
def maxProduct(self, A):
m = -1
for i in range(len(A)):
p = A[i]
if p > m:
m = p
for j in range(i+1, len(A)):
a = A[i+1:j]
for k in a:
... | class Solution:
def max_product(self, A):
m = -1
for i in range(len(A)):
p = A[i]
if p > m:
m = p
for j in range(i + 1, len(A)):
a = A[i + 1:j]
for k in a:
p *= k
if p > m:
... |
#a sample object
class animal:
#properties - details
size = 0
age = 0
color = ""
gender = ""
breed = ""
#actions
def __init__(self, size, age, color, gender, breed):
self.size = int(size)
self.age = int(age)
self.color = str(color)
self.gender = str(gende... | class Animal:
size = 0
age = 0
color = ''
gender = ''
breed = ''
def __init__(self, size, age, color, gender, breed):
self.size = int(size)
self.age = int(age)
self.color = str(color)
self.gender = str(gender)
self.breed = str(breed)
def grow(self, g... |
grocery = ["Sugar", "Pizza", "Ice-Cream", 100]
print(grocery)
print(grocery[1])
numbers = [2, 5, 6, 9, 4]
print(numbers)
print(numbers[3])
print(numbers[0:4])
print(numbers[1:3])
print(numbers[::1])
print("\n")
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers.append(99)
print("\t", numbers)
num... | grocery = ['Sugar', 'Pizza', 'Ice-Cream', 100]
print(grocery)
print(grocery[1])
numbers = [2, 5, 6, 9, 4]
print(numbers)
print(numbers[3])
print(numbers[0:4])
print(numbers[1:3])
print(numbers[::1])
print('\n')
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers.append(99)
print('\t', numbers)
number... |
# Copyright (c) 2012 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.
{
'variables': {
'chromium_code': 1,
},
'target_defaults': {
'conditions': [
['use_x11 == 1', {
'include_dirs': [
... | {'variables': {'chromium_code': 1}, 'target_defaults': {'conditions': [['use_x11 == 1', {'include_dirs': ['<(DEPTH)/third_party/angle/include']}]]}, 'targets': [{'target_name': 'surface', 'type': '<(component)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annot... |
{ 'application':{ 'type':'Application',
'name':'Test Sounds',
'backgrounds':
[
{ 'type':'Background',
'name':'Test Sounds',
'title':'Test Sounds',
'position':( 5, 5 ),
'size':( 300, 200 ),
'menubar':
{
'type':'MenuBar',
'menus':
[
{... | {'application': {'type': 'Application', 'name': 'Test Sounds', 'backgrounds': [{'type': 'Background', 'name': 'Test Sounds', 'title': 'Test Sounds', 'position': (5, 5), 'size': (300, 200), 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'File', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': ... |
'''
Date: 2021-06-24 10:56:59
LastEditors: Liuliang
LastEditTime: 2021-06-24 11:26:06
Description:
'''
class Node():
def __init__(self,item):
self.item = item
self.next = None
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a.item)
print(a.next.item)
print(b.next.item)
print(c.ne... | """
Date: 2021-06-24 10:56:59
LastEditors: Liuliang
LastEditTime: 2021-06-24 11:26:06
Description:
"""
class Node:
def __init__(self, item):
self.item = item
self.next = None
a = node(1)
b = node(2)
c = node(3)
a.next = b
b.next = c
print(a.item)
print(a.next.item)
print(b.next.item)
print(c.next... |
n=input()
words=input()
words=words.lower()
lst=[]
for i in words:
if i not in lst:
lst.append(i)
print("YES") if len(lst)==26 else print("NO") | n = input()
words = input()
words = words.lower()
lst = []
for i in words:
if i not in lst:
lst.append(i)
print('YES') if len(lst) == 26 else print('NO') |
pkgname = "libexecinfo"
version = "1.1"
revision = 0
build_style = "gnu_makefile"
make_build_args = ["PREFIX=/usr"]
short_desc = "BSD licensed clone of the GNU libc backtrace facility"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-2-Clause"
homepage = "http://www.freshports.org/devel/libexecinfo"
distfiles ... | pkgname = 'libexecinfo'
version = '1.1'
revision = 0
build_style = 'gnu_makefile'
make_build_args = ['PREFIX=/usr']
short_desc = 'BSD licensed clone of the GNU libc backtrace facility'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'BSD-2-Clause'
homepage = 'http://www.freshports.org/devel/libexecinfo'
distfiles ... |
# -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'python-troveclient'
copyright = u'2012, OpenStack Foundation'
exclude_trees = []
pygments_style = 'sphinx'... | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'python-troveclient'
copyright = u'2012, OpenStack Foundation'
exclude_trees = []
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['... |
#Excersie 1.1
str1 = "JohnDipPeta"
newstr1 = list(str1)
output = None
for i in range (0,len(newstr1)):
if(newstr1[i]=="D" and newstr1[i+1]=='i' and newstr1[i+2]=='p'):
output = newstr1[i]+ newstr1[i+1]+newstr1[i+2]
print(output)
#Excersie 2
#Given 2 strings, s1 and s2, create a new string by appending s2 in the mid... | str1 = 'JohnDipPeta'
newstr1 = list(str1)
output = None
for i in range(0, len(newstr1)):
if newstr1[i] == 'D' and newstr1[i + 1] == 'i' and (newstr1[i + 2] == 'p'):
output = newstr1[i] + newstr1[i + 1] + newstr1[i + 2]
print(output)
s1 = 'Ault'
s2 = 'Kelly'
result = s1[0:2] + s2 + s1[2:4]
print(result)
def... |
# Copyright (c) 2017 Dustin Doloff
# Licensed under Apache License v2.0
load(
"//actions:actions.bzl",
"stamp_file",
)
load(
"//assert:assert.bzl",
"assert_files_equal",
)
load(
"//rules:rules.bzl",
"generate_file",
"zip_files",
"zip_runfiles",
)
def run_all_tests():
test_generate_... | load('//actions:actions.bzl', 'stamp_file')
load('//assert:assert.bzl', 'assert_files_equal')
load('//rules:rules.bzl', 'generate_file', 'zip_files', 'zip_runfiles')
def run_all_tests():
test_generate_file()
test_zip_files()
test_zip_runfiles()
def test_generate_file():
test_generate_bin_file()
te... |
expected_output={
"replicate_oce": {
"0x7F9E40C590C8": {
"uid": 6889
},
"0x7F9E40C59340": {
"uid": 6888
}
}
}
| expected_output = {'replicate_oce': {'0x7F9E40C590C8': {'uid': 6889}, '0x7F9E40C59340': {'uid': 6888}}} |
# Return lines from a file
def getFileLines(file):
f = open(file, "r")
lines = f.readlines()
f.close
return lines | def get_file_lines(file):
f = open(file, 'r')
lines = f.readlines()
f.close
return lines |
expected_output = {
"channel_assignment": {
"chan_assn_mode": "AUTO",
"chan_upd_int": "12 Hours",
"anchor_time_hour": 7,
"channel_update_contribution" : {
"channel_noise": "Enable",
"channel_interference": "Enable",
"channel_load": "Disable",
... | expected_output = {'channel_assignment': {'chan_assn_mode': 'AUTO', 'chan_upd_int': '12 Hours', 'anchor_time_hour': 7, 'channel_update_contribution': {'channel_noise': 'Enable', 'channel_interference': 'Enable', 'channel_load': 'Disable', 'device_aware': 'Disable'}, 'clean_air': 'Disabled', 'wlc_leader_name': 'sj-00a-e... |
# Example: list media files and save any with the name `dog` in file name
media_list = api.get_media_files()
for media in media_list:
if 'dog' in media['mediaName'].lower():
stream, content_type = api.download_media_file(media['mediaName'])
with io.open(media['mediaName'], 'wb') as file:
... | media_list = api.get_media_files()
for media in media_list:
if 'dog' in media['mediaName'].lower():
(stream, content_type) = api.download_media_file(media['mediaName'])
with io.open(media['mediaName'], 'wb') as file:
file.write(stream.read()) |
def de(fobj, bounds, mut=0.8, crossp=0.7, popsize=20, its=1000):
dimensions = len(bounds)
pop = np.random.rand(popsize, dimensions)
min_b, max_b = np.asarray(bounds).T
diff = np.fabs(min_b - max_b)
pop_denorm = min_b + pop * diff
fitness = np.asarray([fobj(ind) for ind in pop_denorm])
best_idx = np.argmin(fitness)... | def de(fobj, bounds, mut=0.8, crossp=0.7, popsize=20, its=1000):
dimensions = len(bounds)
pop = np.random.rand(popsize, dimensions)
(min_b, max_b) = np.asarray(bounds).T
diff = np.fabs(min_b - max_b)
pop_denorm = min_b + pop * diff
fitness = np.asarray([fobj(ind) for ind in pop_denorm])
best_idx = np.argmin(fitness... |
#This program is for practicing lists
#Take a list, say for example this one:
#a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements of the list that are less than 5.
a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = len(a)
new1 = []
print ("Number of elements in a is %d" %b)
for i in ... | a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = len(a)
new1 = []
print('Number of elements in a is %d' % b)
for i in range(0, b):
if a[i] < 5:
new1.append(a[i])
print(new1)
new = []
for i in range(0, 10):
x = int(input('enter the %d th element of the list:' % i))
new.append(x)
print(new)
new2 = []
for i... |
a = [1,2,3]
b = [4,5,6]
print(a+b)
print(a)
print(a*2)
print(a*3)
print(b*2)
print(b*3)
print(1 in a)
print(2 in a)
print(3 in a)
print(4 in a) | a = [1, 2, 3]
b = [4, 5, 6]
print(a + b)
print(a)
print(a * 2)
print(a * 3)
print(b * 2)
print(b * 3)
print(1 in a)
print(2 in a)
print(3 in a)
print(4 in a) |
# encoding: utf-8
__all__ = ['LoggingTransport']
log = __import__('logging').getLogger(__name__)
class LoggingTransport(object):
__slots__ = ('ephemeral', 'log')
def __init__(self, config):
self.log = log if 'name' not in config else __import__('logging').getLogger(config.name)
def s... | __all__ = ['LoggingTransport']
log = __import__('logging').getLogger(__name__)
class Loggingtransport(object):
__slots__ = ('ephemeral', 'log')
def __init__(self, config):
self.log = log if 'name' not in config else __import__('logging').getLogger(config.name)
def startup(self):
log.debug... |
## 2. Syntax Errors ##
def first_elts(input_lst):
elts = []
for each in input_lst:
elts.append(each)
return elts
animals = [["dog","cat","rabbit"],["turtle","snake"], ["sloth","penguin","bird"]]
first_animal = first_elts(animals)
print(first_animal)
## 4. TypeError and ValueError ##
forty_two =... | def first_elts(input_lst):
elts = []
for each in input_lst:
elts.append(each)
return elts
animals = [['dog', 'cat', 'rabbit'], ['turtle', 'snake'], ['sloth', 'penguin', 'bird']]
first_animal = first_elts(animals)
print(first_animal)
forty_two = '42'
forty_two + 42
int('guardians')
lives = [1, 2, 3]
... |
'''
Assignment: Create functions that serialize/deserialize objects to/from a stream of data. Additionally, create a function
that retrieves a given value from the stream of data.
All objects have a flat structure that is described by a schema. Objects needn't have all fields, in such a case, the default
value is assu... | """
Assignment: Create functions that serialize/deserialize objects to/from a stream of data. Additionally, create a function
that retrieves a given value from the stream of data.
All objects have a flat structure that is described by a schema. Objects needn't have all fields, in such a case, the default
value is assu... |
async def run(plugin, ctx):
plugin.db.configs.update(ctx.guild.id, "persist", True)
await ctx.send(plugin.t(ctx.guild, "enabled_module_no_channel", _emote="YES", module="Persist")) | async def run(plugin, ctx):
plugin.db.configs.update(ctx.guild.id, 'persist', True)
await ctx.send(plugin.t(ctx.guild, 'enabled_module_no_channel', _emote='YES', module='Persist')) |
def attation(proto_layers, layer_infos, edges_info, attation_num):
for proto_index, proto_layer in enumerate(proto_layers):
for key, layer_info in layer_infos.items():
if layer_info['name'] == proto_layer.name:
cur_layer_info = layer_info
break
cur_data = layer_info['data... | def attation(proto_layers, layer_infos, edges_info, attation_num):
for (proto_index, proto_layer) in enumerate(proto_layers):
for (key, layer_info) in layer_infos.items():
if layer_info['name'] == proto_layer.name:
cur_layer_info = layer_info
break
cur_dat... |
def main():
n, m = map(int, input().split())
if n < m:
print(f"Dr. Chaz will have {m-n} piece{'' if m-n == 1 else 's'} of chicken left over!")
else:
print(f"Dr. Chaz needs {n-m} more piece{'' if n-m == 1 else 's'} of chicken!")
return
if __name__ == "__main__":
main()
| def main():
(n, m) = map(int, input().split())
if n < m:
print(f"Dr. Chaz will have {m - n} piece{('' if m - n == 1 else 's')} of chicken left over!")
else:
print(f"Dr. Chaz needs {n - m} more piece{('' if n - m == 1 else 's')} of chicken!")
return
if __name__ == '__main__':
main() |
data = int(input("Num : "))
max = 12
min = 1
while min<=max:
print("%d * %d = %d" % (data,min,data*min))
min+=1
| data = int(input('Num : '))
max = 12
min = 1
while min <= max:
print('%d * %d = %d' % (data, min, data * min))
min += 1 |
def setup():
size(600, 400)
def draw():
global theta
background(0);
frameRate(30);
stroke(255);
a = (mouseX / float(width)) * 90;
theta = radians(a);
translate(width/2,height);
line(0,0,0,-120);
translate(0,-120);
branch(120);
def branch(l):
l *= .66
... | def setup():
size(600, 400)
def draw():
global theta
background(0)
frame_rate(30)
stroke(255)
a = mouseX / float(width) * 90
theta = radians(a)
translate(width / 2, height)
line(0, 0, 0, -120)
translate(0, -120)
branch(120)
def branch(l):
l *= 0.66
if l > 1:
... |
def f(x):
y = x**4 - 3*x
return y
#pythran export integrate_f6(float64, float64, int)
def integrate_f6(a, b, n):
dx = (b - a) / n
dx2 = dx / 2
s = f(a) * dx2
i = 0
for i in range(1, n):
s += f(a + i * dx) * dx
s += f(b) * dx2
return s
| def f(x):
y = x ** 4 - 3 * x
return y
def integrate_f6(a, b, n):
dx = (b - a) / n
dx2 = dx / 2
s = f(a) * dx2
i = 0
for i in range(1, n):
s += f(a + i * dx) * dx
s += f(b) * dx2
return s |
# O(n) time | O(1) space
def reverseLinkedList(head):
p1, p2 = None, head
while p2 is not None:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
return p1 | def reverse_linked_list(head):
(p1, p2) = (None, head)
while p2 is not None:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
return p1 |
# Make a config.py file filling in these constants. Note: This is only a template file!
clientID = 'CLIENT_ID'
secretID = 'SECRET_ID'
uName = 'USERNAME'
password = 'PASSWORD'
db_host = 'IP_ADDR_DB'
db_name = 'MockSalutes'
db_user = 'DB_USER'
db_pass = 'DB_PASSWORD'
| client_id = 'CLIENT_ID'
secret_id = 'SECRET_ID'
u_name = 'USERNAME'
password = 'PASSWORD'
db_host = 'IP_ADDR_DB'
db_name = 'MockSalutes'
db_user = 'DB_USER'
db_pass = 'DB_PASSWORD' |
# cook your dish here
for _ in range(int(input())):
N,MINX,MAXX = map(int,input().split())
num = MAXX-MINX+1
even = num//2
odd = num-even
for i in range(N):
w, b = map(int,input().split())
if w%2==0 and b%2==0:
even = even+odd
odd=0
elif w%2==1 and b%2... | for _ in range(int(input())):
(n, minx, maxx) = map(int, input().split())
num = MAXX - MINX + 1
even = num // 2
odd = num - even
for i in range(N):
(w, b) = map(int, input().split())
if w % 2 == 0 and b % 2 == 0:
even = even + odd
odd = 0
elif w % 2 ==... |
#!/usr/bin/env python3
'''
Create a function, that takes 3 numbers: a, b, c and returns True if the last digit
of (the last digit of a * the last digit of b) = the last digit of c.
'''
def last_dig(a, b, c):
a = list(str(a))
b = list(str(b))
c = list(str(c))
val = list(str(int(a[-1]) * int(b[-1])))
return int(val... | """
Create a function, that takes 3 numbers: a, b, c and returns True if the last digit
of (the last digit of a * the last digit of b) = the last digit of c.
"""
def last_dig(a, b, c):
a = list(str(a))
b = list(str(b))
c = list(str(c))
val = list(str(int(a[-1]) * int(b[-1])))
return int(val[-1]) =... |
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param intervals, a list of Intervals
# @return a list of Interval
def merge(self, intervals):
newInterval = []
if len(intervals) == 0:
r... | class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
new_interval = []
if len(intervals) == 0:
return [newInterval] |
# Basic Fantasy RPG Dungeoneer Suite
# Copyright 2007-2018 Chris Gonnerman
# 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
# no... | roomtypes = [0, (5, 'Antechamber'), (3, 'Armory'), (7, 'Audience'), (2, 'Aviary'), (7, 'Banquet Room'), (4, 'Barracks'), (6, 'Bath'), (10, 'Bedroom'), (2, 'Bestiary'), (1, 'Cell'), (1, 'Chantry'), (2, 'Chapel'), (1, 'Cistern'), (3, 'Classroom'), (8, 'Closet'), (2, 'Conjuring'), (5, 'Corridor'), (1, 'Courtroom'), (1, 'C... |
##########################################################################################
#
# Asteroid Version
#
# (c) University of Rhode Island
##########################################################################################
VERSION = "0.1.0"
| version = '0.1.0' |
class User:
def __init__(self,account_name,card,pin):
self.account_name = account_name
self.card = card
self.pin = pin | class User:
def __init__(self, account_name, card, pin):
self.account_name = account_name
self.card = card
self.pin = pin |
CFG = {
'in_ch': 3,
'out_ch': 24,
'kernel_size': 3,
'stride': 2,
'width_mult': 1,
'divisor': 8,
'actn_layer': None,
'layers': [
{'channels': 24, 'expansion': 1, 'kernel_size': 3, 'stride': 1,
'nums': 2, 'norm_layer': None, 'dropout_ratio': 0.1, 'dc_ratio': 0.2,
... | cfg = {'in_ch': 3, 'out_ch': 24, 'kernel_size': 3, 'stride': 2, 'width_mult': 1, 'divisor': 8, 'actn_layer': None, 'layers': [{'channels': 24, 'expansion': 1, 'kernel_size': 3, 'stride': 1, 'nums': 2, 'norm_layer': None, 'dropout_ratio': 0.1, 'dc_ratio': 0.2, 'reduction_ratio': 0.25, 'actn_layer': None, 'fused': True, ... |
pod_examples = [
dict(
apiVersion='v1',
kind='Pod',
metadata=dict(
name='good',
namespace='default'
),
spec=dict(
serviceAccountName='default'
)
),
dict(
apiVersion='v1',
kind='Pod',
metadata=dict(
... | pod_examples = [dict(apiVersion='v1', kind='Pod', metadata=dict(name='good', namespace='default'), spec=dict(serviceAccountName='default')), dict(apiVersion='v1', kind='Pod', metadata=dict(name='bad', namespace='default'), spec=dict(serviceAccountName='bad')), dict(apiVersion='v1', kind='Pod', metadata=dict(name='raise... |
######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... | logprint('Starting EVLA_pipe_targetflag_lines.py', logfileout='logs/targetflag.log')
time_list = runtiming('checkflag', 'start')
qa2_targetflag = 'Pass'
logprint('Checking RFI flagging of all targets', logfileout='logs/targetflag.log')
default('flagdata')
vis = ms_active
mode = 'rflag'
field = ''
correlation = 'ABS_' +... |
regularServingPancakes = 24
cupsOfFlourrPer24Pancakes = 4.5
noOfEggsPer24Pancakes = 4
litresOfMilkPer24Pancakes = 1
noOfPancakes = float(input("How many pancakes do you want to make: "))
expectedCupsOfFlour = ( noOfPancakes / regularServingPancakes ) * \
cupsOfFlourrPer24Pancakes
expect... | regular_serving_pancakes = 24
cups_of_flourr_per24_pancakes = 4.5
no_of_eggs_per24_pancakes = 4
litres_of_milk_per24_pancakes = 1
no_of_pancakes = float(input('How many pancakes do you want to make: '))
expected_cups_of_flour = noOfPancakes / regularServingPancakes * cupsOfFlourrPer24Pancakes
expected_no_of_eggs = noOf... |
def generated_per_next_split(max_day):
# generate a table saying how many lanternfish result from a lanternfish
# which next split is on a given day
table = {}
for i in range(max_day+10, 0, -1):
table[i] = 1 if i >= max_day else (table[i+7] + table[i+9])
return table
def solve(next_splits... | def generated_per_next_split(max_day):
table = {}
for i in range(max_day + 10, 0, -1):
table[i] = 1 if i >= max_day else table[i + 7] + table[i + 9]
return table
def solve(next_splits, max_day):
table = generated_per_next_split(max_day)
return sum([table[next_split] for next_split in next_s... |
n = int(input())
xs = []
ys = []
numToPosX = dict()
numToPosY = dict()
for i in range(n):
x, y = list(map(float, input().split()))
numToPosX.setdefault(x, i)
numToPosY.setdefault(y, i)
xs.append(x)
ys.append(y)
xs.sort()
ys.sort()
resX = [0] * n
resY = [0] * n
for i in range(n):
resX[numT... | n = int(input())
xs = []
ys = []
num_to_pos_x = dict()
num_to_pos_y = dict()
for i in range(n):
(x, y) = list(map(float, input().split()))
numToPosX.setdefault(x, i)
numToPosY.setdefault(y, i)
xs.append(x)
ys.append(y)
xs.sort()
ys.sort()
res_x = [0] * n
res_y = [0] * n
for i in range(n):
resX[n... |
def setup():
size(400,400)
stroke(225)
background(192, 64, 0)
def draw():
line(200, 200, mouseX, mouseY)
def mousePressed():
saveFrame("Output.png")
| def setup():
size(400, 400)
stroke(225)
background(192, 64, 0)
def draw():
line(200, 200, mouseX, mouseY)
def mouse_pressed():
save_frame('Output.png') |
class random:
def __init__(self, animaltype, name, canfly):
self.animaltype = animaltype
self.name = name
self.fly = canfly
def getanimaltype(self):
return self.animaltype
def getobjects(self):
print('{} {} {}'.format(self.animaltype, self.name, self.fly))
ok = random('bird', 'penguin',... | class Random:
def __init__(self, animaltype, name, canfly):
self.animaltype = animaltype
self.name = name
self.fly = canfly
def getanimaltype(self):
return self.animaltype
def getobjects(self):
print('{} {} {}'.format(self.animaltype, self.name, self.fly))
ok = ran... |
class ValidationResult:
def __init__(self, is_success, error_message=None):
self.is_success = is_success
self.error_message = error_message
@classmethod
def success(cls):
return cls(True)
@classmethod
def error(cls, error_message):
return cls(False, error_message)
... | class Validationresult:
def __init__(self, is_success, error_message=None):
self.is_success = is_success
self.error_message = error_message
@classmethod
def success(cls):
return cls(True)
@classmethod
def error(cls, error_message):
return cls(False, error_message)
... |
def eval_chunk_size(rm):
chunks = []
chunk_size = 0
for row in range(rm.max_row):
for col in range(rm.max_col):
if (rm.seats[row][col] == None or rm.seats[row][col].sid == -1) and chunk_size > 0:
chunks.append(chunk_size)
chunk_size = 0
else:
... | def eval_chunk_size(rm):
chunks = []
chunk_size = 0
for row in range(rm.max_row):
for col in range(rm.max_col):
if (rm.seats[row][col] == None or rm.seats[row][col].sid == -1) and chunk_size > 0:
chunks.append(chunk_size)
chunk_size = 0
else:
... |
class Circle:
def __init__(self,d):
self.diameter=d
self.__pi=3.14
def calculate_circumference(self):
c=self.__pi*self.diameter
return c
def calculate_area(self):
r=self.diameter/2
return self.__pi*(r*r)
def calculate_area_of_sector(self,angle):
... | class Circle:
def __init__(self, d):
self.diameter = d
self.__pi = 3.14
def calculate_circumference(self):
c = self.__pi * self.diameter
return c
def calculate_area(self):
r = self.diameter / 2
return self.__pi * (r * r)
def calculate_area_of_sector(se... |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
amounts = [float('inf')] * (amount + 1)
amounts[0] = 0
for coin in coins:
for amt in range(coin, amount + 1):
amounts[amt] = min(amounts[amt], amounts[amt - coin] + 1)
if amounts... | class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
amounts = [float('inf')] * (amount + 1)
amounts[0] = 0
for coin in coins:
for amt in range(coin, amount + 1):
amounts[amt] = min(amounts[amt], amounts[amt - coin] + 1)
if amounts... |
names = ["Katya", "Max", "Oleksii", "Olesya", "Oleh", "Yaroslav", "Anastasiia"]
age = [25, 54, 18, 23, 45, 21, 21]
isPaid = [True, False, True, True, False, True, False]
namesFromDatabaseClear = names.index("Max")
ageMax = age[namesFromDatabaseClear]
print(ageMax)
| names = ['Katya', 'Max', 'Oleksii', 'Olesya', 'Oleh', 'Yaroslav', 'Anastasiia']
age = [25, 54, 18, 23, 45, 21, 21]
is_paid = [True, False, True, True, False, True, False]
names_from_database_clear = names.index('Max')
age_max = age[namesFromDatabaseClear]
print(ageMax) |
# -*- coding: utf-8 -*-
SEXO = (
('F', 'Feminino'),
('M', 'Masculino'),
) | sexo = (('F', 'Feminino'), ('M', 'Masculino')) |
cats_path = "python_crash_course/exceptions/cats.txt"
dogs_path = "python_crash_course/exceptions/dogs.txt"
try:
with open(cats_path) as file_object:
cats = file_object.read()
print("Koty:")
print(cats)
except FileNotFoundError:
pass
try:
with open(dogs_path) as file_object:
dogs =... | cats_path = 'python_crash_course/exceptions/cats.txt'
dogs_path = 'python_crash_course/exceptions/dogs.txt'
try:
with open(cats_path) as file_object:
cats = file_object.read()
print('Koty:')
print(cats)
except FileNotFoundError:
pass
try:
with open(dogs_path) as file_object:
dogs = f... |
def has_unique_chars(string: str) -> bool:
if len(string) == 1:
return True
unique = []
for item in string:
if item not in unique:
unique.append(item)
else:
return False
return True | def has_unique_chars(string: str) -> bool:
if len(string) == 1:
return True
unique = []
for item in string:
if item not in unique:
unique.append(item)
else:
return False
return True |
#
# PySNMP MIB module ChrComPmSonetSNT-PFE-Interval-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComPmSonetSNT-PFE-Interval-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:20:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'local_database.db',
'TEST_NAME': ':memory:',
}
}
SECRET_KEY = '9(-c^&tzdv(d-*x$cefm2pddz=0!_*8iu*i8fh+krpa!5ebk)+'
ROOT_URLCONF = 'test_project.urls'
TEMPLATE_DIRS = (
'templates',
)
INSTALL... | debug = True
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'local_database.db', 'TEST_NAME': ':memory:'}}
secret_key = '9(-c^&tzdv(d-*x$cefm2pddz=0!_*8iu*i8fh+krpa!5ebk)+'
root_urlconf = 'test_project.urls'
template_dirs = ('templates',)
installed_apps = ('django.contrib.auth', 'django.contri... |
class Course:
def __init__(self, link, code, title, credits, campus, dept, year, semester, semester_code, faculty, courselvl, description, prereq, coreq, exclusion, breadth, apsc, flags):
self.link = link.strip()
self.code = code.strip()
self.title = title.strip()
self.credits = credits.strip()
self.campus ... | class Course:
def __init__(self, link, code, title, credits, campus, dept, year, semester, semester_code, faculty, courselvl, description, prereq, coreq, exclusion, breadth, apsc, flags):
self.link = link.strip()
self.code = code.strip()
self.title = title.strip()
self.credits = cre... |
# Generates comments with the specified indentation and wrapping-length
def generateComment(comment, length=100, indentation=""):
out = ""
for commentChunk in [
comment[i : i + length] for i in range(0, len(comment), length)
]:
out += indentation + "// " + commentChunk + "\n"
return out
... | def generate_comment(comment, length=100, indentation=''):
out = ''
for comment_chunk in [comment[i:i + length] for i in range(0, len(comment), length)]:
out += indentation + '// ' + commentChunk + '\n'
return out
def get_data_reference(element, root):
for parent in root.iter():
if elem... |
# -*- coding: utf-8 -*-
class Solution:
def exist(self, board, word):
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if self.startsHere(board, word, visited, 0, i, j):
return True
return False
def startsHere(s... | class Solution:
def exist(self, board, word):
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if self.startsHere(board, word, visited, 0, i, j):
return True
return False
def starts_here(self, board, word, visite... |
#-------------------------------------------------------------------------------
# Name: Removing duplicates
# Purpose:
#
# Author: Ben Jones
#
# Created: 03/02/2022
# Copyright: (c) Ben Jones 2022
#-------------------------------------------------------------------------------
new_menu = [... | new_menu = ['Hawaiian', 'Margherita', 'Mushroom', 'Prosciutto', 'Meat Feast', 'Hawaiian', 'Bacon', 'Black Olive Special', 'Sausage', 'Sausage']
final_new_menu = list(dict.fromkeys(new_menu))
print(final_new_menu) |
word_size = 8
num_words = 256
num_banks = 1
tech_name = "freepdk45"
process_corners = ["TT"]
supply_voltages = [1.0]
temperatures = [25]
| word_size = 8
num_words = 256
num_banks = 1
tech_name = 'freepdk45'
process_corners = ['TT']
supply_voltages = [1.0]
temperatures = [25] |
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
def post_order(node):
... | class Solution:
def check_equivalence(self, root1: 'Node', root2: 'Node') -> bool:
def post_order(node):
ans = collections.Counter()
if node is None:
return ans
if node.left is None and node.right is None:
ans[node.val] += 1
e... |
# Panel settings: /project/<default>/api_access
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
# The default _was_ "overview", but that gives 403s.
# Make this the default in this dashboard.
DEFAULT_PANEL = 'api_access'
| panel_dashboard = 'project'
panel_group = 'default'
panel = 'api_access'
default_panel = 'api_access' |
# python stack using list #
my_Stack = [10, 12, 13, 11, 33, 24, 56, 78, 13, 56, 31, 32, 33, 10, 15] # array #
print(my_Stack)
print(my_Stack.pop())
# think python simple just pop and push #
print(my_Stack.pop())
print(my_Stack.pop())
print(my_Stack.pop())
| my__stack = [10, 12, 13, 11, 33, 24, 56, 78, 13, 56, 31, 32, 33, 10, 15]
print(my_Stack)
print(my_Stack.pop())
print(my_Stack.pop())
print(my_Stack.pop())
print(my_Stack.pop()) |
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School']) | dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']
dict.clear()
del dict
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School']) |
'''
URL: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
Difficulty: Easy
Description: Maximum Nesting Depth of the Parentheses
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It c... | """
URL: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
Difficulty: Easy
Description: Maximum Nesting Depth of the Parentheses
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
It is an empty string "", or a single character not equal to "(" or ")",
It c... |
#
# PySNMP MIB module CISCO-EVC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EVC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ... |
#
# PySNMP MIB module ALPHA-RECTIFIER-SYS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALPHA-RECTIFIER-SYS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:20:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (simple, scaled_number) = mibBuilder.importSymbols('ALPHA-RESOURCE-MIB', 'simple', 'ScaledNumber')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constr... |
# O(n) time | O(1) space
def twoNumberSum(array, targetSum):
# Write your code here.
result = []
for num in array:
offset = targetSum - num
if offset in array:
result = [offset, num]
return result
# def twoNumberSum(array, targetSum):
# for i in range(len(array)-1):
# for k in range(i+1, len(array)... | def two_number_sum(array, targetSum):
result = []
for num in array:
offset = targetSum - num
if offset in array:
result = [offset, num]
return result |
class MockMail:
def __init__(self):
self.inbox = []
def send_mail(self, recipient_list, **kwargs):
for recipient in recipient_list:
self.inbox.append({
'recipient': recipient,
'subject': kwargs['subject'],
'message': kwargs['message']
... | class Mockmail:
def __init__(self):
self.inbox = []
def send_mail(self, recipient_list, **kwargs):
for recipient in recipient_list:
self.inbox.append({'recipient': recipient, 'subject': kwargs['subject'], 'message': kwargs['message']})
def clear(self):
self.inbox[:] = ... |
for x in range(0, 11):
for c in range(0, 11):
print(x, 'x', c, '= {}'.format(x * c))
print('\t')
| for x in range(0, 11):
for c in range(0, 11):
print(x, 'x', c, '= {}'.format(x * c))
print('\t') |
# Main network and testnet3 definitions
params = {
'argentum_main': {
'pubkey_address': 23,
'script_address': 5,
'genesis_hash': '88c667bc63167685e4e4da058fffdfe8e007e5abffd6855de52ad59df7bb0bb2'
},
'argentum_test': {
'pubkey_address': 111,
'script_address': 196,
... | params = {'argentum_main': {'pubkey_address': 23, 'script_address': 5, 'genesis_hash': '88c667bc63167685e4e4da058fffdfe8e007e5abffd6855de52ad59df7bb0bb2'}, 'argentum_test': {'pubkey_address': 111, 'script_address': 196, 'genesis_hash': 'f5ae71e26c74beacc88382716aced69cddf3dffff24f384e1808905e0188f68f'}} |
def add_time(start, duration, day=None):
hour, minutes = start.split(':')
minutes, am_pm = minutes.split()
add_hour, add_min = duration.split(":")
hour = int(hour)
minutes = int(minutes)
add_hour = int(add_hour)
add_min = int(add_min)
n = add_hour // 24
rem_hour = add_hour % 24
n... | def add_time(start, duration, day=None):
(hour, minutes) = start.split(':')
(minutes, am_pm) = minutes.split()
(add_hour, add_min) = duration.split(':')
hour = int(hour)
minutes = int(minutes)
add_hour = int(add_hour)
add_min = int(add_min)
n = add_hour // 24
rem_hour = add_hour % 24... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.