content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = []
for i in range(n//2):
ans.append(i+1)
ans.append(-i-1)
if n % 2 != 0:
ans.append(0)
return ans | class Solution:
def sum_zero(self, n: int) -> List[int]:
ans = []
for i in range(n // 2):
ans.append(i + 1)
ans.append(-i - 1)
if n % 2 != 0:
ans.append(0)
return ans |
INCHES_PER_FOOT = 12.0 # 12 inches in a foot
INCHES_PER_YARD = INCHES_PER_FOOT * 3.0 # 3 feet in a yard
UNITS = ("in", "ft", "yd")
def inches_to_feet(x, reverse=False):
"""
Terminal command | pyment -w -o numpydoc inches_to_feet.py
Flags
-w | overwrite
-o <style> | styleput in NumPy D... | inches_per_foot = 12.0
inches_per_yard = INCHES_PER_FOOT * 3.0
units = ('in', 'ft', 'yd')
def inches_to_feet(x, reverse=False):
"""
Terminal command | pyment -w -o numpydoc inches_to_feet.py
Flags
-w | overwrite
-o <style> | styleput in NumPy Documentation style
Convert lengths betwe... |
"""
Initial settings for Up and Down the River
"""
class Settings() :
def __init__(self) :
"""Initializes static settings"""
#Screen Settings
self.screen_width = 1400
self.screen_height = 800
self.bg_color = (34, 139, 34)
#Basic settings
self.number_of_play... | """
Initial settings for Up and Down the River
"""
class Settings:
def __init__(self):
"""Initializes static settings"""
self.screen_width = 1400
self.screen_height = 800
self.bg_color = (34, 139, 34)
self.number_of_players_option = [3, 4, 5, 6, 7, 8]
self.number_of... |
test = {
'name': 'Problem 5',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> expr = read_line('(+ 2 2)')
>>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors
4
>>> expr = read_line('(+ (+ 2 2) (+ 1 3)... | test = {'name': 'Problem 5', 'points': 2, 'suites': [{'cases': [{'code': "\n >>> expr = read_line('(+ 2 2)')\n >>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors\n 4\n >>> expr = read_line('(+ (+ 2 2) (+ 1 3) (* 1 4))')\n >>> scheme_eval... |
class A:
def __init__(self, a):
pass
class B(A):
def __init__(self, a=1):
A.__init__(self, a) | class A:
def __init__(self, a):
pass
class B(A):
def __init__(self, a=1):
A.__init__(self, a) |
#!/usr/bin/env python
# coding: utf-8
# # section 7: Exceptions :
#
# ### writer : Faranak Alikhah 1954128
# ### 1.Exceptions :
#
#
# In[ ]:
n=int(input())
for i in range(n):
try:
a,b=map(int,input().split())
print(a//b)# need to be integer
except Exception as e:
print ("Erro... | n = int(input())
for i in range(n):
try:
(a, b) = map(int, input().split())
print(a // b)
except Exception as e:
print('Error Code:', e) |
class HealthController:
"""
Manages interactions with the /health endpoints
"""
def __init__(self, client):
self.client = client
def check_health(self):
"""
GET request ot the /health endpoint
:return: Requests Response Object
"""
return self.client.c... | class Healthcontroller:
"""
Manages interactions with the /health endpoints
"""
def __init__(self, client):
self.client = client
def check_health(self):
"""
GET request ot the /health endpoint
:return: Requests Response Object
"""
return self.client.... |
class ContainerSpec():
REPLACEABLE_ARGS = ['randcon', 'oracle_server', 'bootnodes', 'genesis_time']
def __init__(self, cname, cimage, centry):
self.name = cname
self.image = cimage
self.entrypoint = centry
self.args = {}
def append_args(self, **kwargs):
self.args.... | class Containerspec:
replaceable_args = ['randcon', 'oracle_server', 'bootnodes', 'genesis_time']
def __init__(self, cname, cimage, centry):
self.name = cname
self.image = cimage
self.entrypoint = centry
self.args = {}
def append_args(self, **kwargs):
self.args.upda... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/80471495
# IDEA : OPERATION : INVERSE -> Exclusive or (1->0, 0->1)
# NOTE : Exclusive or
# In [29]: x=1
# In [30]: x
# Out[30]: 1
# In [31]: x^=1
# In [32]: x
# Out[32]: 0
# In [33]: x=0
# In [34]: x
# Out[34]: 0
# In [35]: x^=1
# In [36]: x
# Out... | class Solution:
def flip_and_invert_image(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rows = len(A)
cols = len(A[0])
for row in range(rows):
A[row] = A[row][::-1]
for col in range(cols):
A[row][co... |
#
# This file is part of snmpresponder software.
#
# Copyright (c) 2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpresponder/license.html
#
class Numbers(object):
current = 0
def getId(self):
self.current += 1
if self.current > 65535:
self.current = 0
... | class Numbers(object):
current = 0
def get_id(self):
self.current += 1
if self.current > 65535:
self.current = 0
return self.current
numbers = numbers()
get_id = numbers.getId |
"""
This is the "Rotate Image" problem on Leetcode: https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/770
"""
# Out of Place Solution
def rotate_out_of_place(matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
"""
Idea #1: Swaps
A: movin... | """
This is the "Rotate Image" problem on Leetcode: https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/770
"""
def rotate_out_of_place(matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
'\n Idea #1: Swaps\n \n A: moving the upper left corner... |
def _get_dart_host(config):
elb_params = config['cloudformation_stacks']['elb']['boto_args']['Parameters']
rs_name_param = _get_element(elb_params, 'ParameterKey', 'RecordSetName')
dart_host = rs_name_param['ParameterValue']
return dart_host
def _get_element(l, k, v):
for e in l:
if e[k]... | def _get_dart_host(config):
elb_params = config['cloudformation_stacks']['elb']['boto_args']['Parameters']
rs_name_param = _get_element(elb_params, 'ParameterKey', 'RecordSetName')
dart_host = rs_name_param['ParameterValue']
return dart_host
def _get_element(l, k, v):
for e in l:
if e[k] ==... |
# Calculate the smallest Multiple
def smallestMultiple(n):
smallestMultiple = 1
while(True):
evenMultiple = True
for i in range(1, int(n) + 1):
if(smallestMultiple % i != 0):
evenMultiple = False
break
if(evenMultiple):
return small... | def smallest_multiple(n):
smallest_multiple = 1
while True:
even_multiple = True
for i in range(1, int(n) + 1):
if smallestMultiple % i != 0:
even_multiple = False
break
if evenMultiple:
return smallestMultiple
smallest_mult... |
class User:
'''
Class that generates a new instance of a passlocker user
__init__method that helps us to define properties for our objects
Args:
name:New user name
password:New user password
'''
user_list=[]
def __init__(self,name,password):
self.na... | class User:
"""
Class that generates a new instance of a passlocker user
__init__method that helps us to define properties for our objects
Args:
name:New user name
password:New user password
"""
user_list = []
def __init__(self, name, password):
self.name = nam... |
# output: ok
def foo(x):
yield 1
yield x
iter = foo(2)
assert next(iter) == 1
assert next(iter) == 2
def bar(array):
for x in array:
yield 2 * x
iter = bar([1, 2, 3])
assert next(iter) == 2
assert next(iter) == 4
assert next(iter) == 6
def collect(iter):
result = []
for x in iter:
... | def foo(x):
yield 1
yield x
iter = foo(2)
assert next(iter) == 1
assert next(iter) == 2
def bar(array):
for x in array:
yield (2 * x)
iter = bar([1, 2, 3])
assert next(iter) == 2
assert next(iter) == 4
assert next(iter) == 6
def collect(iter):
result = []
for x in iter:
result.appe... |
RTL_LANGUAGES = {
'he', 'ar', 'arc', 'dv', 'fa', 'ha',
'khw', 'ks', 'ku', 'ps', 'ur', 'yi',
}
COLORS = {
'primary': '#0d6efd', 'blue': '#0d6efd', 'secondary': '#6c757d',
'success': '#198754', 'green': '#198754', 'danger': '#dc3545',
'red': '#dc3545', 'warning': '#ffc107', 'yellow': '#ffc107',
... | rtl_languages = {'he', 'ar', 'arc', 'dv', 'fa', 'ha', 'khw', 'ks', 'ku', 'ps', 'ur', 'yi'}
colors = {'primary': '#0d6efd', 'blue': '#0d6efd', 'secondary': '#6c757d', 'success': '#198754', 'green': '#198754', 'danger': '#dc3545', 'red': '#dc3545', 'warning': '#ffc107', 'yellow': '#ffc107', 'info': '#0dcaf0', 'cyan': '#0... |
COINBASE_MATURITY = 500
INITIAL_BLOCK_REWARD = 20000
INITIAL_HASH_UTXO_ROOT = 0x21b463e3b52f6201c0ad6c991be0485b6ef8c092e64583ffa655cc1b171fe856
INITIAL_HASH_STATE_ROOT = 0x9514771014c9ae803d8cea2731b2063e83de44802b40dce2d06acd02d0ff65e9
MAX_BLOCK_BASE_SIZE = 2000000
BEERCHAIN_MIN_GAS_PRICE = 40
BEERCHAIN_MIN_GAS_PRICE... | coinbase_maturity = 500
initial_block_reward = 20000
initial_hash_utxo_root = 15245045886785142666142131387346645761820096966537625257719794791382855444566
initial_hash_state_root = 67430773121565887155292377391296365627809276935091884798145281674911173010921
max_block_base_size = 2000000
beerchain_min_gas_price = 40
b... |
# 461. Hamming Distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1') | class Solution:
def hamming_distance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1') |
MATERIALS = [
"gold", "silver", "bronze", "copper",
"iron", "titanium", "stone", "lithium",
"wood", "glass", "bone", "diamond"
]
PLACES = [
"cemetery", "forest", "desert", "cave",
"church", "school", "montain", "waterfall",
"prison", "garden", "crossroad", "nexus"
]
AMULETS = [
"warrior", ... | materials = ['gold', 'silver', 'bronze', 'copper', 'iron', 'titanium', 'stone', 'lithium', 'wood', 'glass', 'bone', 'diamond']
places = ['cemetery', 'forest', 'desert', 'cave', 'church', 'school', 'montain', 'waterfall', 'prison', 'garden', 'crossroad', 'nexus']
amulets = ['warrior', 'thief', 'wizard', 'barbarian', 'sc... |
# -*- coding: utf-8 -*-
a = ['doge1','doge2','doge3','doge4']
print(a)
| a = ['doge1', 'doge2', 'doge3', 'doge4']
print(a) |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
elif nums[mid] > target:
hi = mid
else:
... | class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
(lo, hi) = (0, len(nums))
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
elif nums[mid] > target:
hi = mid
else... |
#
# PySNMP MIB module DAVID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DAVID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months+1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_mo... | journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months + 1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_money ... |
subscription_data=\
{
"description": "A subscription to get info about Room1",
"subject": {
"entities": [
{
"id": "Room1",
"type": "Room",
}
],
"condition": {
"attrs": [
"p3"
]
}
},
"notification": {
"http": {
"url": "http://192.168.100.162:88... | subscription_data = {'description': 'A subscription to get info about Room1', 'subject': {'entities': [{'id': 'Room1', 'type': 'Room'}], 'condition': {'attrs': ['p3']}}, 'notification': {'http': {'url': 'http://192.168.100.162:8888'}, 'attrs': ['p1', 'p2', 'p3']}, 'expires': '2040-01-01T14:00:00.00Z', 'throttling': 5}
... |
with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents)
| with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents) |
class HistoryStatement:
def __init__(self, hashPrev, hashUploaded, username, comment=""):
self.hashPrev = hashPrev
self.hashUploaded = hashUploaded
self.username = username
self.comment = comment
def to_bytes(self):
buf = bytearray()
buf.extend(self.hashPrev)
buf.extend(self.hashUploaded)
... | class Historystatement:
def __init__(self, hashPrev, hashUploaded, username, comment=''):
self.hashPrev = hashPrev
self.hashUploaded = hashUploaded
self.username = username
self.comment = comment
def to_bytes(self):
buf = bytearray()
buf.extend(self.hashPrev)
... |
_base_ = [
'../_base_/models/upernet_swin.py', '../_base_/datasets/uvo_finetune.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(
pretrained='PATH/TO/YOUR/swin_large_patch4_window12_384_22k.pth',
backbone=dict(
pretrain_img_size=384,
embed_dims=... | _base_ = ['../_base_/models/upernet_swin.py', '../_base_/datasets/uvo_finetune.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py']
model = dict(pretrained='PATH/TO/YOUR/swin_large_patch4_window12_384_22k.pth', backbone=dict(pretrain_img_size=384, embed_dims=192, depths=[2, 2, 18, 2], num_heads=... |
class IDependency:
pass
class IScoped(IDependency):
pass
def __del__(self):
pass
class ISingleton(IDependency):
pass
| class Idependency:
pass
class Iscoped(IDependency):
pass
def __del__(self):
pass
class Isingleton(IDependency):
pass |
h = int(input())
x = int(input())
y = int(input())
result = 'Outside'
# Base, left vertical, left horizontal, middle left etc.
if (3*h >= x >= 0 == y) or (x == 0 <= y <= h) or (0 <= x <= h == y) or (x == h <= y <= 4*h) or \
(h <= x <= 2*h and y == 4*h) or (x == 2*h and h <= y <= 4*h) or (2*h <= x <= 3*h and... | h = int(input())
x = int(input())
y = int(input())
result = 'Outside'
if 3 * h >= x >= 0 == y or x == 0 <= y <= h or 0 <= x <= h == y or (x == h <= y <= 4 * h) or (h <= x <= 2 * h and y == 4 * h) or (x == 2 * h and h <= y <= 4 * h) or (2 * h <= x <= 3 * h and y == h) or (x == 3 * h and 0 <= y <= h):
result = 'Borde... |
# https://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion
def hsv_to_rgb(h, s, v):
if s == 0.0: return (v, v, v)
i = int(h*6.) # XXX assume int() truncates!
f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
if i == 0: return (v, t, p)
if i == 1: r... | def hsv_to_rgb(h, s, v):
if s == 0.0:
return (v, v, v)
i = int(h * 6.0)
f = h * 6.0 - i
(p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)))
i %= 6
if i == 0:
return (v, t, p)
if i == 1:
return (q, v, p)
if i == 2:
return (p, v, t)
... |
class Parameter:
def __init__(self,
name,
prior,
initial_value,
transform=None,
fixed=False):
self.name = name
self.prior = prior
self.transform = (lambda x: x) if transform is None else transform
se... | class Parameter:
def __init__(self, name, prior, initial_value, transform=None, fixed=False):
self.name = name
self.prior = prior
self.transform = (lambda x: x) if transform is None else transform
self.value = initial_value
self.fixed = fixed
def propose(self, *args):
... |
class Solution:
labs = []
def __init__(self, T):
self.z = 0
self.x = []
for i in range(T):
self.x.append(0)
def calculate_z(self):
if len(self.labs) == 0:
return 0
self.z = 0
for i in range(len(self.labs)):
for j in range(s... | class Solution:
labs = []
def __init__(self, T):
self.z = 0
self.x = []
for i in range(T):
self.x.append(0)
def calculate_z(self):
if len(self.labs) == 0:
return 0
self.z = 0
for i in range(len(self.labs)):
for j in range(... |
symbol = input()
count = int(input())
c = 0
for i in range(count):
if input() == symbol:
c += 1
print(c)
| symbol = input()
count = int(input())
c = 0
for i in range(count):
if input() == symbol:
c += 1
print(c) |
#!/usr/bin/python
'''
Priority queue with random access updates
-----------------------------------------
.. autoclass:: PrioQueue
:members:
:special-members:
'''
#-----------------------------------------------------------------------------
class PrioQueue:
'''
Priority queue that supports updating pr... | """
Priority queue with random access updates
-----------------------------------------
.. autoclass:: PrioQueue
:members:
:special-members:
"""
class Prioqueue:
"""
Priority queue that supports updating priority of arbitrary elements and
removing arbitrary elements.
Entry with lowest priority... |
SETTINGS_TMPL = '''import os
from glueplate import Glue as _
settings = _(
blog = _(
title = '{blog_title}',
base_url = '{base_url}',
language = '{language}',
),
dir = _(
output = os.path.abspath(os.path.join('..', 'out'))
),
GLUE_PLATE_PLUS_BEFORE_template_dirs = [o... | settings_tmpl = "import os\nfrom glueplate import Glue as _\n\nsettings = _(\n blog = _(\n title = '{blog_title}',\n base_url = '{base_url}',\n language = '{language}',\n ),\n dir = _(\n output = os.path.abspath(os.path.join('..', 'out'))\n ),\n GLUE_PLATE_PLUS_BEFORE_template... |
# code to find if given string
# is K-Palindrome or not
"""
Explanation
Process all characters one by one staring from either from left or right sides of both strings.
Let us traverse from the right corner, there are two possibilities for every pair of character being traversed.
If last characters of two strings a... | """
Explanation
Process all characters one by one staring from either from left or right sides of both strings.
Let us traverse from the right corner, there are two possibilities for every pair of character being traversed.
If last characters of two strings are same, we ignore last characters and get count for remai... |
class Dog:
kind = 'canine'
tricks = [] #mistaken use
def __init__(self, name):
self.name = name
self.tricksInstance = []
def add_trick(self, trick):
self.tricks.append(trick)
def add_trick_instance(self, trick):
self.tricksInstance.append(trick)
d = Dog('Fido'... | class Dog:
kind = 'canine'
tricks = []
def __init__(self, name):
self.name = name
self.tricksInstance = []
def add_trick(self, trick):
self.tricks.append(trick)
def add_trick_instance(self, trick):
self.tricksInstance.append(trick)
d = dog('Fido')
e = dog('Buddy')
... |
#!/usr/bin/env python3
#----------------------------------------------------------------------------------------------------------------------#
# #
# Tuplex: Blazing... | class Tuplexexception(Exception):
"""Base Exception class on which all Tuplex Framework specific exceptions are based"""
pass
class Udfcodeextractionerror(TuplexException):
"""thrown when UDF code extraction/reflection failed"""
pass |
# The following is the homework 4 for course MIS3500
# This assignment is Home Work 4
def file_read():
add = 0 # variable for adding total
counter = 0 # counter to understand how many counts are there
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open("... | def file_read():
add = 0
counter = 0
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open('AAPL.txt', 'r')
lines = file.readlines()
for line in lines:
price = float(line)
prices.append(price)
add += price
counter += 1... |
# -*- coding: utf-8 -*-
# @Time : 2021-07-31 19:34
# @Author : Ze Yi Sun
# @Site : BUAA
# @File : question.py
# @Software: PyCharm
class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return "None"
def check_correctness(self, answer: str) -... | class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return 'None'
def check_correctness(self, answer: str) -> bool:
return True
class Choicequestion(Question):
def __init__(self, statement: str, correct_answer: set):
... |
class Solution(object):
def validMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
i=0
j=len(arr)-1
while i<j and (arr[i] < arr[i+1]):
i+=1
while j>0 and (arr[j-1] > arr[j]):
j-=1
return i > 0 and j <... | class Solution(object):
def valid_mountain_array(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
i = 0
j = len(arr) - 1
while i < j and arr[i] < arr[i + 1]:
i += 1
while j > 0 and arr[j - 1] > arr[j]:
j -= 1
retur... |
"""Top-level package for BakpdlBot."""
__author__ = """Mick Boekhoff"""
__email__ = 'mickboekhoff@hotmail.com'
__version__ = '0.1.0'
| """Top-level package for BakpdlBot."""
__author__ = 'Mick Boekhoff'
__email__ = 'mickboekhoff@hotmail.com'
__version__ = '0.1.0' |
class Solution:
def countSubstrings(self, s: str) -> int:
p = len(s)
dp = [[i,i+1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i-1]:
if j-1 >= 0 and s[j-1] == s[i]:
p += 1
dp[i].append(j-1)
... | class Solution:
def count_substrings(self, s: str) -> int:
p = len(s)
dp = [[i, i + 1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i - 1]:
if j - 1 >= 0 and s[j - 1] == s[i]:
p += 1
dp[i].append(j - 1)
... |
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
#
r... | """
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
row = len... |
artifacts = {
"io_bazel_rules_scala_scala_library": {
"artifact": "org.scala-lang:scala-library:2.11.12",
"sha256": "0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce",
},
"io_bazel_rules_scala_scala_compiler": {
"artifact": "org.scala-lang:scala-compiler:2.11.12",
... | artifacts = {'io_bazel_rules_scala_scala_library': {'artifact': 'org.scala-lang:scala-library:2.11.12', 'sha256': '0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce'}, 'io_bazel_rules_scala_scala_compiler': {'artifact': 'org.scala-lang:scala-compiler:2.11.12', 'sha256': '3e892546b72ab547cb77de4d840bcfd05... |
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
| alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien) |
# The opcode tables were taken from Mammon_'s Guide to Writing Disassemblers in Perl, You Morons!"
# and the bastard project. http://www.eccentrix.com/members/mammon/
INSTR_PREFIX = 0xF0000000
ADDRMETH_MASK = 0x00FF0000
ADDRMETH_A = 0x00010000 # Direct address with segment prefix
ADDRMETH_B = 0x00020000 # VEX.v... | instr_prefix = 4026531840
addrmeth_mask = 16711680
addrmeth_a = 65536
addrmeth_b = 131072
addrmeth_c = 196608
addrmeth_d = 262144
addrmeth_e = 327680
addrmeth_f = 393216
addrmeth_g = 458752
addrmeth_h = 524288
addrmeth_i = 589824
addrmeth_j = 655360
addrmeth_l = 720896
addrmeth_m = 786432
addrmeth_n = 851968
addrmeth_o... |
class StubCursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return self.row, self.column
@coords.setter
def coords(self, coords):
self.row, self.column = coords
| class Stubcursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return (self.row, self.column)
@coords.setter
def coords(self, coords):
(self.row, self.column) = coords |
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
... | class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
... |
# Copyright 2013 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': {
'verbose_libraries_build%': 0,
'instrumented_libraries_jobs%': 1,
'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(m... | {'variables': {'verbose_libraries_build%': 0, 'instrumented_libraries_jobs%': 1, 'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang', 'instrumented_libraries_cxx%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang++'}, 'libdir': 'lib', 'ubuntu_release': '<!(lsb_release -cs)', 'co... |
'''
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
'''
class S... | """
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
"""
class Solution(ob... |
# Write a Python program to add an item in a tuple
tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
#2nd method
tuple = tuplex[:3] + (23,56,7)
print(tuple)
#3rd method
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex) | tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
tuple = tuplex[:3] + (23, 56, 7)
print(tuple)
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex) |
class ActionBatchAppliance(object):
def __init__(self):
super(ActionBatchAppliance, self).__init__()
def updateNetworkApplianceConnectivityMonitoringDestinations(self, networkId: str, **kwargs):
"""
**Update the connectivity testing destinations for an MX network**
https://dev... | class Actionbatchappliance(object):
def __init__(self):
super(ActionBatchAppliance, self).__init__()
def update_network_appliance_connectivity_monitoring_destinations(self, networkId: str, **kwargs):
"""
**Update the connectivity testing destinations for an MX network**
https:/... |
contador = 0
file = open("funciones_matematicas.py","w")
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input("Ingrese ecuacion: ")
def agregar_funcion():
f = open("funciones_matematicas.py","w")
ecuacion = input("Ingrese ... | contador = 0
file = open('funciones_matematicas.py', 'w')
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input('Ingrese ecuacion: ')
def agregar_funcion():
f = open('funciones_matematicas.py', 'w')
ecuac... |
class SlotPickleMixin(object):
"""
This mixin makes it possible to pickle/unpickle objects with __slots__ defined.
Origin: http://code.activestate.com/recipes/578433-mixin-for-pickling-objects-with-__slots__/
"""
def __getstate__(self):
return dict(
(slot, getattr(self, slot))
... | class Slotpicklemixin(object):
"""
This mixin makes it possible to pickle/unpickle objects with __slots__ defined.
Origin: http://code.activestate.com/recipes/578433-mixin-for-pickling-objects-with-__slots__/
"""
def __getstate__(self):
return dict(((slot, getattr(self, slot)) for slot in s... |
N = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)]))
| n = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)])) |
def solution(lottos, win_nums):
answer = []
zeros=0
for i in lottos:
if(i==0) : zeros+=1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6:1,5:2,4:3,3:4,2:5,1:6,0:6}
answer.append(_dict[len(correct)+zeros])
answer.append(_dict[len(correct)])
return answer
| def solution(lottos, win_nums):
answer = []
zeros = 0
for i in lottos:
if i == 0:
zeros += 1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6, 0: 6}
answer.append(_dict[len(correct) + zeros])
answer.append(_dict[len(corre... |
class Solution:
def solve(self, path):
ans = []
for part in path:
if part == "..":
if ans: ans.pop()
elif part != ".": ans.append(part)
return ans
| class Solution:
def solve(self, path):
ans = []
for part in path:
if part == '..':
if ans:
ans.pop()
elif part != '.':
ans.append(part)
return ans |
# https://www.codewars.com/kata/523a86aa4230ebb5420001e1
def letterCounter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
wordMap = letterCounter... | def letter_counter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
word_map = letter_counter(word)
for w in words:
if wordMap == lette... |
# %%
def Naive(N):
is_prime = True
if N <= 1 :
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return(is_prime)
def main():
N = 139
print(f"{N} prime ? : {Naive(N)}")
if __name__=="__main__":
main()... | def naive(N):
is_prime = True
if N <= 1:
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return is_prime
def main():
n = 139
print(f'{N} prime ? : {naive(N)}')
if __name__ == '__main__':
main() |
'''
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
'''
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length-1):
if sequence[i] == sequence[i+1]:
dp[i+1] = dp[i] + 1
else:
... | """
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
"""
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length - 1):
if sequence[i] == sequence[i + 1]:
dp[i + 1] = dp[i] + 1
else:
... |
def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit ... | def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit =... |
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
| def all_perms(str):
if len(str) <= 1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm) + 1):
yield (perm[:i] + str[0:1] + perm[i:]) |
#!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""
Author: Wang, Jun
Email: wangjun41@baidu.com
Date: 2018-11-16
"""
class BaseException(Exception):
"base exception"
def __init__(self, msg):
self.msg = msg
class UnsupportedError(BaseException):
"""Not support"""
def __init__(self, msg):
... | """
Author: Wang, Jun
Email: wangjun41@baidu.com
Date: 2018-11-16
"""
class Baseexception(Exception):
"""base exception"""
def __init__(self, msg):
self.msg = msg
class Unsupportederror(BaseException):
"""Not support"""
def __init__(self, msg):
self.msg = msg
class Requestmethodnot... |
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | def riff_wave__checks(WAVE_block):
fmt_chunk = None
fact_chunk = None
data_chunk = None
if 'fmt ' not in WAVE_block._named_chunks:
WAVE_block.warnings.append('expected one "fmt " block, found none')
else:
fmt_chunk = WAVE_block._named_chunks['fmt '][0]
if 'fact' not in WAVE_block... |
# Problem 1- Summation of primes
# https://projecteuler.net/problem=10
# Answer =
def question():
print("""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.""")
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if n... | def question():
print('The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.')
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def prime_lister(bound):
pri... |
#!/usr/bin/env python
# coding: utf-8
# # 7: Dictionaries Solutions
#
# 1. Below are two lists, `keys` and `values`. Combine these into a single dictionary.
#
# ```python
# keys = ['Ben', 'Ethan', 'Stefani']
# values = [1, 29, 28]
# ```
# Expected output:
# ```python
# {'Ben': 1, 'Ethan': 29, 'Stefani': 28}
# ```
# ... | keys = ['Ben', 'Ethan', 'Stefani']
values = [1, 29, 28]
my_dict = dict(zip(keys, values))
print(my_dict)
dict1 = {'Ben': 1, 'Ethan': 29}
dict2 = {'Stefani': 28, 'Madonna': 16, 'RuPaul': 17}
"\nIn Python 3.9+, we can use `dict3 = dict1 | dict2`\nIn Python 3.5+ we can use `dict3 = {**dict1, **dict2}`\nBut I'll show you t... |
np = int(input('Say a number: '))
som = 0
for i in range(1,np):
if np%i == 0:
print (i),
som += i
if som == np:
print('It is a perfect number!')
else:
print ('It is not a perfect number')
| np = int(input('Say a number: '))
som = 0
for i in range(1, np):
if np % i == 0:
(print(i),)
som += i
if som == np:
print('It is a perfect number!')
else:
print('It is not a perfect number') |
"""The ofx parser package. A package to parse OpenFlow messages.
This package is a library that parses and creates OpenFlow Messages.
It contains all implemented versions of OpenFlow protocol
"""
__version__ = '2020.2b3'
| """The ofx parser package. A package to parse OpenFlow messages.
This package is a library that parses and creates OpenFlow Messages.
It contains all implemented versions of OpenFlow protocol
"""
__version__ = '2020.2b3' |
stormtrooper = r'''
,ooo888888888888888oooo,
o8888YYYYYY77iiiiooo8888888o
8888YYYY77iiYY8888888888888888
[88YYY77iiY88888888888888888888]
88YY7iYY888888888888888888888888
... | stormtrooper = "\n ,ooo888888888888888oooo,\n o8888YYYYYY77iiiiooo8888888o\n 8888YYYY77iiYY8888888888888888\n [88YYY77iiY88888888888888888888]\n 88YY7iYY888888888888888888888888\n ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
stack = []
cur = head
while cur:
stack.append(cur)
... | class Solution:
def remove_zero_sum_sublists(self, head: ListNode) -> ListNode:
stack = []
cur = head
while cur:
stack.append(cur)
s = 0
for i in range(len(stack) - 1, -1, -1):
s += stack[i].val
if s == 0:
... |
# -*- coding: utf-8 -*-
"""
bandwidth
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
class ConferenceEventMethodEnum(object):
"""Implementation of the 'ConferenceEventMethod' enum.
TODO: type enum description here.
Attributes:
POST: T... | """
bandwidth
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
class Conferenceeventmethodenum(object):
"""Implementation of the 'ConferenceEventMethod' enum.
TODO: type enum description here.
Attributes:
POST: TODO: type description here.
GET: TOD... |
# -*- coding: utf-8 -*-
""""
Author: Jean Pierre
Last Edited:
"""
| """"
Author: Jean Pierre
Last Edited:
""" |
# add your QUIC implementation here
IMPLEMENTATIONS = { # name => [ docker image, role ]; role: 0 == 'client', 1 == 'server', 2 == both
"quicgo": {"url": "martenseemann/quic-go-interop:latest", "role": 2},
"quicly": {"url": "janaiyengar/quicly:interop", "role": 2},
"ngtcp2": {"url": "ngtcp2/ngtcp2-interop:... | implementations = {'quicgo': {'url': 'martenseemann/quic-go-interop:latest', 'role': 2}, 'quicly': {'url': 'janaiyengar/quicly:interop', 'role': 2}, 'ngtcp2': {'url': 'ngtcp2/ngtcp2-interop:latest', 'role': 2}, 'quant': {'url': 'ntap/quant:interop', 'role': 2}, 'mvfst': {'url': 'lnicco/mvfst-qns:latest', 'role': 2}, 'q... |
class WorksharingDisplayMode(Enum,IComparable,IFormattable,IConvertible):
"""
Indicates which worksharing display mode a view is in.
enum WorksharingDisplayMode,values: CheckoutStatus (1),ModelUpdates (3),Off (0),Owners (2),Worksets (4)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) ... | class Worksharingdisplaymode(Enum, IComparable, IFormattable, IConvertible):
"""
Indicates which worksharing display mode a view is in.
enum WorksharingDisplayMode,values: CheckoutStatus (1),ModelUpdates (3),Off (0),Owners (2),Worksets (4)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.... |
class Solution:
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic={}
for i in range(len(nums)):
if i in dic:
continue
j=i
dic[j]=1
while nums[i]!=j:
dic[j]+=1
... | class Solution:
def array_nesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for i in range(len(nums)):
if i in dic:
continue
j = i
dic[j] = 1
while nums[i] != j:
dic... |
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
"""
[1,2],[2,3],[3,4],[1,3]
[(1,s), (1,s), (2,e), (2, s), (3, e), (3, e), (3, s), (4,e)]
"""
events = []
for start, end in intervals:
events.append((start... | class Solution:
def erase_overlap_intervals(self, intervals: List[List[int]]) -> int:
"""
[1,2],[2,3],[3,4],[1,3]
[(1,s), (1,s), (2,e), (2, s), (3, e), (3, e), (3, s), (4,e)]
"""
events = []
for (start, end) in intervals:
events.append((... |
# https://stackoverflow.com/questions/16017397/injecting-function-call-after-init-with-decorator
# define a new metaclass which overrides the "__call__" function
class InitModifier(type):
def __call__(cls, *args, **kwargs):
"""Called when you call MyNewClass() """
obj = type.__call__(cls, *args, **k... | class Initmodifier(type):
def __call__(cls, *args, **kwargs):
"""Called when you call MyNewClass() """
obj = type.__call__(cls, *args, **kwargs)
obj._freeze()
return obj
class Frozenclasstemplate(object):
__isfrozen = False
def __setattr__(self, key, value):
if sel... |
#
# PySNMP MIB module ADTRAN-AOS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (ad_shared, ad_identity_shared) = mibBuilder.importSymbols('ADTRAN-MIB', 'adShared', 'adIdentityShared')
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_... |
chars_to_remove = ["-", ",", ".", "!", "?"]
with open('text.txt') as text_file:
for i, line in enumerate(text_file):
if i % 2 == 0:
for char in line:
if char in chars_to_remove:
line = line.replace(char, '@')
print(' '.join(reversed(line.split()))... | chars_to_remove = ['-', ',', '.', '!', '?']
with open('text.txt') as text_file:
for (i, line) in enumerate(text_file):
if i % 2 == 0:
for char in line:
if char in chars_to_remove:
line = line.replace(char, '@')
print(' '.join(reversed(line.split())... |
def hvplot_with_buffer(gdf, buffer_size, *args, **kwargs):
"""
Convenience function for plotting a GeoPandas point GeoDataFrame using point markers plus buffer polygons
Parameters
----------
gdf : geopandas.GeoDataFrame
point GeoDataFrame to plot
buffer_size : numeric
size o... | def hvplot_with_buffer(gdf, buffer_size, *args, **kwargs):
"""
Convenience function for plotting a GeoPandas point GeoDataFrame using point markers plus buffer polygons
Parameters
----------
gdf : geopandas.GeoDataFrame
point GeoDataFrame to plot
buffer_size : numeric
size o... |
# (C) Datadog, Inc. 2019
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
STANDARD = [
'sap_hana.backup.latest',
'sap_hana.connection.idle',
'sap_hana.connection.open',
'sap_hana.connection.running',
'sap_hana.cpu.service.utilized',
'sap_hana.disk.free',
'sap... | standard = ['sap_hana.backup.latest', 'sap_hana.connection.idle', 'sap_hana.connection.open', 'sap_hana.connection.running', 'sap_hana.cpu.service.utilized', 'sap_hana.disk.free', 'sap_hana.disk.size', 'sap_hana.disk.used', 'sap_hana.disk.utilized', 'sap_hana.file.service.open', 'sap_hana.memory.row_store.free', 'sap_h... |
def boxes_packing(length, width, height):
total=[sorted((i,j,k)) for i,j,k in zip(length, width, height)]
res=sorted(total, key=lambda x: -min(x))
for i,j in enumerate(res[1:]):
if any((k-l)<=0 for k,l in zip(res[i], j)):
return False
return True | def boxes_packing(length, width, height):
total = [sorted((i, j, k)) for (i, j, k) in zip(length, width, height)]
res = sorted(total, key=lambda x: -min(x))
for (i, j) in enumerate(res[1:]):
if any((k - l <= 0 for (k, l) in zip(res[i], j))):
return False
return True |
{
'includes': [ '../common.gyp' ],
'targets': [
{
'target_name': 'libjpeg',
'type': 'static_library',
'include_dirs': [
'.',
],
'sources': [
'ckconfig.c',
'jcapimin.c',
'jcapistd.c',
'jccoefct.c',
'jccolor.c',
'jcdctmgr.c',
... | {'includes': ['../common.gyp'], 'targets': [{'target_name': 'libjpeg', 'type': 'static_library', 'include_dirs': ['.'], 'sources': ['ckconfig.c', 'jcapimin.c', 'jcapistd.c', 'jccoefct.c', 'jccolor.c', 'jcdctmgr.c', 'jchuff.c', 'jcinit.c', 'jcmainct.c', 'jcmarker.c', 'jcmaster.c', 'jcomapi.c', 'jcparam.c', 'jcphuff.c', ... |
# Copyright (c) 2009 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.
{
'target_defaults': {
'defines': [
'_LIB',
'XML_STATIC', # Compile for static linkage.
],
'include_dirs': [
'files/lib'... | {'target_defaults': {'defines': ['_LIB', 'XML_STATIC'], 'include_dirs': ['files/lib'], 'dependencies': []}, 'conditions': [['OS=="linux" or OS=="freebsd"', {'targets': [{'target_name': 'expat', 'type': 'settings', 'link_settings': {'libraries': ['-lexpat']}}]}, {'targets': [{'target_name': 'expat', 'type': '<(library)'... |
"""
BSD 3-Clause License
Copyright (c) 2018, Jerrad Genson
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 condit... | """
BSD 3-Clause License
Copyright (c) 2018, Jerrad Genson
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 condit... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"acceleration_status": "accelerationStatus",
"accelerator_arn": "acceleratorArn",
"accept_st... | _snake_to_camel_case_table = {'acceleration_status': 'accelerationStatus', 'accelerator_arn': 'acceleratorArn', 'accept_status': 'acceptStatus', 'acceptance_required': 'acceptanceRequired', 'access_log_settings': 'accessLogSettings', 'access_logs': 'accessLogs', 'access_policies': 'accessPolicies', 'access_policy': 'ac... |
N, *S = open(0).read().split()
t = 1
f = 1
for s in S:
if s == 'AND':
f = t + f * 2
elif s == 'OR':
t = t * 2 + f
print(t)
| (n, *s) = open(0).read().split()
t = 1
f = 1
for s in S:
if s == 'AND':
f = t + f * 2
elif s == 'OR':
t = t * 2 + f
print(t) |
# %% [1221. Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/)
class Solution:
def balancedStringSplit(self, s: str) -> int:
res = cnt = 0
for c in s:
cnt += (c == "L") * 2 - 1
res += not cnt
return res
| class Solution:
def balanced_string_split(self, s: str) -> int:
res = cnt = 0
for c in s:
cnt += (c == 'L') * 2 - 1
res += not cnt
return res |
words = ['cat', 'window', "defenestrate"]
for w in words :
print(w, len(w))
users = ['A', "B", "C"]
for i in users :
print(i)
for i in range(5):
print(i) | words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
users = ['A', 'B', 'C']
for i in users:
print(i)
for i in range(5):
print(i) |
"""
You can use this file as a template to store your api credentials. Just copy (or
rename) this file to `api_credentials.py` and fill in your key and secret.
`api_credentials.py` is in this repository's `.gitignore` file.
"""
PAYONEER_ESCROW_API_KEY = 'ENTER_YOUR_API_KEY_HERE'
PAYONEER_ESCROW_SECRET = 'ENTER_YOUR_AP... | """
You can use this file as a template to store your api credentials. Just copy (or
rename) this file to `api_credentials.py` and fill in your key and secret.
`api_credentials.py` is in this repository's `.gitignore` file.
"""
payoneer_escrow_api_key = 'ENTER_YOUR_API_KEY_HERE'
payoneer_escrow_secret = 'ENTER_YOUR_API... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Valid Braces
#Problem level: 4 kyu
valid = {'(': ')', '[': ']', '{': '}'}
def validBraces(string):
li=[]
for item in string:
if item in valid: li.append(item)
elif li and valid[li[-1]] == item: li.pop()
else: return False
r... | valid = {'(': ')', '[': ']', '{': '}'}
def valid_braces(string):
li = []
for item in string:
if item in valid:
li.append(item)
elif li and valid[li[-1]] == item:
li.pop()
else:
return False
return False if li else True |
summultiples = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
summultiples += i
print(summultiples)
| summultiples = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
summultiples += i
print(summultiples) |
def say_hello(name: str = 'Lucas'):
print(f'Hello {name} ')
def ask_age():
user_age = input('Age?')
return user_age
def say_hello_mp(name, age_user=25):
print(f'Hello {name} {age_user}')
if __name__ == '__main__':
say_hello()
say_hello(123)
print(say_hello('Pierre'))
say_hello_m... | def say_hello(name: str='Lucas'):
print(f'Hello {name} ')
def ask_age():
user_age = input('Age?')
return user_age
def say_hello_mp(name, age_user=25):
print(f'Hello {name} {age_user}')
if __name__ == '__main__':
say_hello()
say_hello(123)
print(say_hello('Pierre'))
say_hello_mp(age_use... |
# -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: October 19, 2004
# Author: Ivan Vilata i Balaguer - reverse:net.selidor@ivan
#
# $Id$
#
########################################################################
"""Special node behaviours for ... | """Special node behaviours for PyTables.
This package contains several modules that give specific behaviours
to PyTables nodes. For instance, the filenode module provides
a file interface to a PyTables node.
Package modules:
filenode -- A file interface to nodes for PyTables databases.
"""
__all__ = ['filenode'] |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 1 13:12:08 2020
@author: Abhishek Parashar
"""
stack=[]
vector=[]
arr=[4,5,2,10,8]
for i in range(len(arr)-1):
if (len(stack)==0):
vector.append(-1)
elif (len(stack)>0 and stack[-1]<arr[i]):
vector.append(stack[-1])
elif (len(s... | """
Created on Thu Oct 1 13:12:08 2020
@author: Abhishek Parashar
"""
stack = []
vector = []
arr = [4, 5, 2, 10, 8]
for i in range(len(arr) - 1):
if len(stack) == 0:
vector.append(-1)
elif len(stack) > 0 and stack[-1] < arr[i]:
vector.append(stack[-1])
elif len(stack) > 0 and stack[-1] >= ... |
def foo(t1, t2, t3):
return str(t1)+str(t2)
res = foo(t1,t2,t3)
print("Testing output!")
| def foo(t1, t2, t3):
return str(t1) + str(t2)
res = foo(t1, t2, t3)
print('Testing output!') |
"""
* Copyright 2007,2008,2009 John C. Gunther
* Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http:#www.apache.org/lic... | """
* Copyright 2007,2008,2009 John C. Gunther
* Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http:#www.apache.org/lic... |
'''
@file: __init__.py.py
@author: qxLiu
@time: 2020/3/14 9:37
'''
| """
@file: __init__.py.py
@author: qxLiu
@time: 2020/3/14 9:37
""" |
def set(name):
ret = {
'name': name,
'changes': {},
'result': False,
'comment': ''
}
current_name = __salt__['c_hostname.get_hostname']()
if name == current_name:
ret['result'] = True
ret['comment'] = "Hostname \"{0}\" already set.".format(name)
r... | def set(name):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_name = __salt__['c_hostname.get_hostname']()
if name == current_name:
ret['result'] = True
ret['comment'] = 'Hostname "{0}" already set.'.format(name)
return ret
if __opts__['test'] is True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.