content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
p1, p2 = nums[0], nums[nums[0]]
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[nums[p2]]
p2 = 0
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[p2]
return... | class Solution:
def find_duplicate(self, nums: List[int]) -> int:
(p1, p2) = (nums[0], nums[nums[0]])
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[nums[p2]]
p2 = 0
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[p2]
... |
class A:
def a(self):
return 'a'
class B(A, object):
def b(self):
return 'b'
class Inherit(A):
def a(self):
return 'c'
| class A:
def a(self):
return 'a'
class B(A, object):
def b(self):
return 'b'
class Inherit(A):
def a(self):
return 'c' |
"""
A
/ |
B C
'B, C'
"""
class CategoryTree:
def __init__(self):
self.root = {}
self.all_categories = []
def add_category(self, category, parent):
if category in self.all_categories:
raise KeyError(f"{category} exists")
if parent is None:
self.r... | """
A
/ |
B C
'B, C'
"""
class Categorytree:
def __init__(self):
self.root = {}
self.all_categories = []
def add_category(self, category, parent):
if category in self.all_categories:
raise key_error(f'{category} exists')
if parent is None:
self.ro... |
def sum_of_squares(n):
return sum(i ** 2 for i in range(1, n+1))
def square_of_sum(n):
return sum(range(1, n+1)) ** 2
| def sum_of_squares(n):
return sum((i ** 2 for i in range(1, n + 1)))
def square_of_sum(n):
return sum(range(1, n + 1)) ** 2 |
Credits = [
('Bootstrap', 'https://getbootstrap.com', 'The Bootstrap team', 'MIT'),
('Bottle', 'http://bottlepy.org', 'Marcel Hellkamp', 'MIT'),
('Cheroot', 'https://github.com/cherrypy/cheroot', 'CherryPy Team', 'BSD 3-Clause "New" or "Revised" License'),
('Click', 'https://github.com/pallets/click', '... | credits = [('Bootstrap', 'https://getbootstrap.com', 'The Bootstrap team', 'MIT'), ('Bottle', 'http://bottlepy.org', 'Marcel Hellkamp', 'MIT'), ('Cheroot', 'https://github.com/cherrypy/cheroot', 'CherryPy Team', 'BSD 3-Clause "New" or "Revised" License'), ('Click', 'https://github.com/pallets/click', 'Pallets', 'BSD 3-... |
def repleace_pattern(t,s,r):
assert len(t) > 0
assert len(s) > 0
assert len(r) > 0
assert len(t) >= len(s)
n = len(t)
m = len(s)
k = len(r)
idx = -1
for i in range(0, n):
if t[i] == s[0]:
pattern = True
for j in range(1,m):
... | def repleace_pattern(t, s, r):
assert len(t) > 0
assert len(s) > 0
assert len(r) > 0
assert len(t) >= len(s)
n = len(t)
m = len(s)
k = len(r)
idx = -1
for i in range(0, n):
if t[i] == s[0]:
pattern = True
for j in range(1, m):
if t[i + ... |
# Copyright 2017 Mycroft AI 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 in writin... | class Enclosureweather:
"""
Listens for Enclosure API commands to display indicators of the weather.
Performs the associated command on Arduino by writing on the Serial port.
"""
def __init__(self, bus, writer):
self.bus = bus
self.writer = writer
self.__init_events()
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
x_depth = None
x_parent = None... | class Solution:
def is_cousins(self, root: TreeNode, x: int, y: int) -> bool:
x_depth = None
x_parent = None
x_found = 0
y_depth = None
y_parent = None
y_found = 0
def dfs(node, parent, depth):
nonlocal x_depth, x_parent, x_found, y_depth, y_foun... |
#
# Copyright (C) 2009 Mendix. All rights reserved.
#
SUCCESS = 0
# Starting the Mendix Runtime can fail in both a temporary or permanent way.
# Some of the errors can be fixed with some help of the user.
#
# The default m2ee cli program will only handle a few of these cases, by
# providing additional hints or intera... | success = 0
start_no_existing_db = 2
start_invalid_db_structure = 3
start_missing_mf_constant = 4
start_admin_1 = 5
start_invalid_state = 6
start_missing_dtap = 7
start_missing_basepath = 8
start_missing_runtimepath = 9
start_invalid_license = 10
start_security_disabled = 11
start_startup_action_failed = 12
start_no_mo... |
def count_words(sentence):
sentence = sentence.lower()
words = {}
shit = ',\n:!&@$%^&._'
for s in shit:
sentence = sentence.replace(s, ' ')
for w in sentence.split():
if w.endswith('\''):
w = w[:-1]
if w.startswith('\''):
w = w[1:]
words... | def count_words(sentence):
sentence = sentence.lower()
words = {}
shit = ',\n:!&@$%^&._'
for s in shit:
sentence = sentence.replace(s, ' ')
for w in sentence.split():
if w.endswith("'"):
w = w[:-1]
if w.startswith("'"):
w = w[1:]
words[w] = wor... |
ID = {"Worldwide":0,
"AF": 1,
"AL": 2,
"DZ": 3,
"AD": 5,
"AO": 6,
"AI": 7,
"AG": 9,
"AR": 10,
"AM": 11,
"AW": 12,
"AT": 14,
"AZ": 15,
"BS": 16,
"BH": 17,
"BD": 18,
"BB": 19,
"BY": 20,
"BZ": 22,
"BJ": 23,
... | id = {'Worldwide': 0, 'AF': 1, 'AL': 2, 'DZ': 3, 'AD': 5, 'AO': 6, 'AI': 7, 'AG': 9, 'AR': 10, 'AM': 11, 'AW': 12, 'AT': 14, 'AZ': 15, 'BS': 16, 'BH': 17, 'BD': 18, 'BB': 19, 'BY': 20, 'BZ': 22, 'BJ': 23, 'BM': 24, 'BO': 26, 'BA': 27, 'BW': 28, 'BV': 29, 'BR': 30, 'BN': 31, 'BG': 32, 'BF': 33, 'BI': 34, 'KH': 35, 'CM':... |
# RiveScript-Python
#
# This code is released under the MIT License.
# See the "LICENSE" file for more information.
#
# https://www.rivescript.com/
def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""Recursively scan a topic and return a list of all triggers.
Arguments:
... | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting... |
# In Search for the Lost Memory [Explorer Thief] (3526)
# To be replaced with GMS's exact dialogue.
# Following dialogue has been edited from DeepL on JMS's dialogue transcript (no KMS footage anywhere):
# https://kaengouraiu2.blog.fc2.com/blog-entry-46.html
recoveredMemory = 7081
darkLord = 1052001
sm.setSpeakerID(... | recovered_memory = 7081
dark_lord = 1052001
sm.setSpeakerID(darkLord)
sm.sendNext('The way you moved without a trace...you must have exceptional talent. Long time no see, #h #.')
sm.sendSay("Since when did you grow up to this point? You're no less inferior to any Dark Lord. You were just a greenhorn that couldn't even ... |
def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') | def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') |
def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
... | def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
VALID_HISTORY_FIELDS = [
'datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume',
'acc_net_value', 'discount_rate', 'unit_net_value',
'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement'
]
VALID_GET_PRICE_FI... | valid_history_fields = ['datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume', 'acc_net_value', 'discount_rate', 'unit_net_value', 'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement']
valid_get_price_fields = ['OpeningPx', 'ClosingPx', 'HighPx', 'LowPx', 'TotalTur... |
"""loads the nasm library, used by TF."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
tf_http_archive(
name = "nasm",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2",
"http://p... | """loads the nasm library, used by TF."""
load('//third_party:repo.bzl', 'tf_http_archive')
def repo():
tf_http_archive(name='nasm', urls=['https://storage.googleapis.com/mirror.tensorflow.org/www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2', 'http://pkgs.fedoraproject.org/repo/pkgs/nasm/nasm-2.13.... |
# unicode digit emojis
# digits from '0' to '9'
zero_digit_code = zd = 48
# excluded digits
excl_digits = [2, 4, 5, 7]
# unicode digit keycap
udkc = '\U0000fe0f\U000020e3'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10)
if i - zd not in excl_digits]
# number '10' emoji
hours_0_9.append('\U0001f51f')
# ... | zero_digit_code = zd = 48
excl_digits = [2, 4, 5, 7]
udkc = '️⃣'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10) if i - zd not in excl_digits]
hours_0_9.append('🔟')
hours_11_23 = [str(i) for i in range(11, 24)]
vote = ('PLUS', 'MINUS')
edit = '📝' |
class Solution:
def __init__(self):
self.res = []
self.path = []
def arr_to_num(self, arr):
s = ""
for x in arr:
s += str(x)
return int(s)
def find_position(self, nums):
for i in range(len(self.res)):
if self.res[i] == nums:
... | class Solution:
def __init__(self):
self.res = []
self.path = []
def arr_to_num(self, arr):
s = ''
for x in arr:
s += str(x)
return int(s)
def find_position(self, nums):
for i in range(len(self.res)):
if self.res[i] == nums:
... |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix: return 0
m, n = len(matrix), len(matrix[0])
dp = [[0]*n for _ in range(m)]
res = 0
for i in range(m):
dp[i][0] = int(matrix[i][0])
for j in range(n):
dp[0][... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
(m, n) = (len(matrix), len(matrix[0]))
dp = [[0] * n for _ in range(m)]
res = 0
for i in range(m):
dp[i][0] = int(matrix[i][0])
for j in range(n)... |
class term(object):
# Dados de cadastro das usinas termeletrica (presentes no TERM.DAT)
Codigo = None
Nome = None
Potencia = None
FCMax = None
TEIF = None
IP = None
GTMin = None
# Dados Adicionais Especificados no arquivo de configuracao termica (CONFT)
Sist = None
Status = ... | class Term(object):
codigo = None
nome = None
potencia = None
fc_max = None
teif = None
ip = None
gt_min = None
sist = None
status = None
classe = None
custo = None
nome_classe = None
tipo_comb = None
def insere(self, custo, gmax):
self.custo = custo
... |
"""
GPA Calculator
"""
# Write a function called "simple_gpa" to find GPA when student enters a letter grade as a string. Assign the result to a variable called "gpa".
"""
Use these conversions:
A+ --> 4.0
A --> 4.0
A- --> 3.7
B+ --> 3.3
B --> 3.0
B- --> 2.7
C+ --> 2.3
C --> 2.0
C- --> 1.7
D+ --> 1.3
D --> 1.0
D- -->... | """
GPA Calculator
"""
'\nUse these conversions:\nA+ --> 4.0\nA --> 4.0\nA- --> 3.7\nB+ --> 3.3\nB --> 3.0\nB- --> 2.7\nC+ --> 2.3\nC --> 2.0\nC- --> 1.7\nD+ --> 1.3\nD --> 1.0\nD- --> 0.7\nF --> 0.0\n' |
# This is a simple program to find the last three digits of 11 raised to any given number.
# The main algorithm that does the work is on line 10
def trim_num(num):
if len(str(num)) > 3: # no need to trim if the number is 3 or less digits long
return str(num)[(len(str(num)) - 3):] # trims the number
ret... | def trim_num(num):
if len(str(num)) > 3:
return str(num)[len(str(num)) - 3:]
return num
def main(exp):
init_val = str((exp - 1) * exp / 2 % 10 + exp % 100 / 10) + str(exp % 10) + '1'
return '{}'.format(trim_num(init_val)) |
class KunaError(Exception):
pass
class AuthenticationError(KunaError):
"""Raised when authentication fails."""
pass
class UnauthorizedError(KunaError):
"""Raised when an API call fails as unauthorized (401)."""
pass
| class Kunaerror(Exception):
pass
class Authenticationerror(KunaError):
"""Raised when authentication fails."""
pass
class Unauthorizederror(KunaError):
"""Raised when an API call fails as unauthorized (401)."""
pass |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = test_episodes # train, test, test_episodes, render
NUM_EPISODES_TO_TEST = 1000
MIN_FINAL_REWARD_FOR_SUCCESS = 1.0
LOAD_MODEL_FROM = models/gru_flat_babyai.pth
SAVE_MODELS_TO = None
# wo... | type_of_run = test_episodes
num_episodes_to_test = 1000
min_final_reward_for_success = 1.0
load_model_from = models / gru_flat_babyai.pth
save_models_to = None
env = BabyAI_Env
env_random_seed = 1
agent_random_seed = 1
reporting_interval = 1
total_steps = 1
anneal_lr = False
agent_net = GRU_Network
babyai_env_level = B... |
"""runghc support"""
load(":private/context.bzl", "render_env")
load(":private/packages.bzl", "expose_packages", "pkg_info_to_compile_flags")
load(
":private/path_utils.bzl",
"link_libraries",
"ln",
"target_unique_name",
)
load(
":private/set.bzl",
"set",
)
load(":providers.bzl", "get_ghci_extr... | """runghc support"""
load(':private/context.bzl', 'render_env')
load(':private/packages.bzl', 'expose_packages', 'pkg_info_to_compile_flags')
load(':private/path_utils.bzl', 'link_libraries', 'ln', 'target_unique_name')
load(':private/set.bzl', 'set')
load(':providers.bzl', 'get_ghci_extra_libs')
load('@bazel_skylib//l... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 20:00:00 2019
@author: Emilia Chojak
@e-mail: emilia.chojak@gmail.com
"""
tax_dict = {
'Pan troglodytes' : 'Hominoidea', 'Pongo abelii' : 'Hominoidea',
'Hominoidea' : 'Simiiformes', 'Simiiformes' : 'Haplorrhini',
'Tarsius tarsier' : 'Tarsiiformes', 'Haplorrhini' : 'Pr... | """
Created on Thu Dec 19 20:00:00 2019
@author: Emilia Chojak
@e-mail: emilia.chojak@gmail.com
"""
tax_dict = {'Pan troglodytes': 'Hominoidea', 'Pongo abelii': 'Hominoidea', 'Hominoidea': 'Simiiformes', 'Simiiformes': 'Haplorrhini', 'Tarsius tarsier': 'Tarsiiformes', 'Haplorrhini': 'Primates', 'Tarsiiformes': 'Haplor... |
ezan = {
'name': 'ezan',
'age': 18,
'hair': 'brown',
'cool': True ,
}
print(ezan)
class Person(object): #use class to make object
def __init__(
self, name, age ,hair, color, hungry) : #initialize
#first object inside of a class is self
self.name = 'ezan'
self.age = 18
... | ezan = {'name': 'ezan', 'age': 18, 'hair': 'brown', 'cool': True}
print(ezan)
class Person(object):
def __init__(self, name, age, hair, color, hungry):
self.name = 'ezan'
self.age = 18
self.hair = 'brown'
self.cool = True
def eat(self, food):
print('EAT {f}'.format(f=f... |
# # Simple Tuple
# fruits = ('Apple', 'Orange', 'Mango')
# # Using Constructor
# fruits = tuple(('Apple', 'Orange', 'Mango'))
# # Getting a Single Value
# print(fruits[1])
# Trying to change based on position
# fruits[1] = 'Grape'
# Tuples with one value should have trailing comma
# fruits = ('Apple')
# fruits = ('... | fruits = {'Apple', 'Orange', 'Mango', 'Apple'}
print('Apple' in fruits)
fruits.add('Grape')
fruits.remove('Grape')
fruits.clear()
del fruits
print(fruits) |
"""Collections of library function names.
"""
class Library:
"""Base class for a collection of library function names.
"""
@staticmethod
def get(libname, _cache={}):
if libname in _cache:
return _cache[libname]
if libname == 'stdlib':
r = Stdlib()
elif ... | """Collections of library function names.
"""
class Library:
"""Base class for a collection of library function names.
"""
@staticmethod
def get(libname, _cache={}):
if libname in _cache:
return _cache[libname]
if libname == 'stdlib':
r = stdlib()
elif l... |
"""HERE are the base Points for all valid Tonnetze Systems.
A period of all 12 notes divided by mod 3, mod 4 (always stable)
"""
# x = 4, y = 3
NotePointsT345 = {
0: (0, 0),
1: (1, 3),
2: (2, 2),
3: (0, 1),
4: (1, 0),
5: (2, 3),
6: (0, 2),
7: (1, 1),
8: (2, 0),
9: (0, 3),
1... | """HERE are the base Points for all valid Tonnetze Systems.
A period of all 12 notes divided by mod 3, mod 4 (always stable)
"""
note_points_t345 = {0: (0, 0), 1: (1, 3), 2: (2, 2), 3: (0, 1), 4: (1, 0), 5: (2, 3), 6: (0, 2), 7: (1, 1), 8: (2, 0), 9: (0, 3), 10: (1, 2), 11: (2, 1)}
note_points_t138 = {0: (0, 0), 1: (2... |
class RequirementsNotMetError(Exception):
"""For SQL INSERT, missing table attributes."""
def __init__(self, message):
super().__init__(message)
class AuthenticationError(Exception):
"""Generic authentication error."""
def __init__(self, message):
super().__init__(message)
| class Requirementsnotmeterror(Exception):
"""For SQL INSERT, missing table attributes."""
def __init__(self, message):
super().__init__(message)
class Authenticationerror(Exception):
"""Generic authentication error."""
def __init__(self, message):
super().__init__(message) |
## -*- encoding: utf-8 -*-
"""
This file (./domaines_doctest.sage) was *autogenerated* from ./domaines.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./domaines_doctest.sage
It is always ... | """
This file (./domaines_doctest.sage) was *autogenerated* from ./domaines.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./domaines_doctest.sage
It is always safe to delete this file; i... |
description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
dct1 = device('nicos.devices.entangle.PowerSupply',
description = 'current in first channel of supply (flipper current)',
tangodevice = tango_base + 't... | description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(dct1=device('nicos.devices.entangle.PowerSupply', description='current in first channel of supply (flipper current)', tangodevice=tango_base + 'tti1/out1', timeout=1, precisi... |
class Stack:
def __init__(self):
self.stack = []
self.minMaxStack = []
# O(1) time | O(1) space
def peek(self):
if (len(self.stack)):
return self.stack[-1]
return None
# O(1) time | O(1) space
def pop(self):
if (len(self.stack)):
sel... | class Stack:
def __init__(self):
self.stack = []
self.minMaxStack = []
def peek(self):
if len(self.stack):
return self.stack[-1]
return None
def pop(self):
if len(self.stack):
self.minMaxStack.pop()
return self.stack.pop()
... |
BIG_CONSTANT = "YES"
def group_by(xs, grouper):
groups = {}
for x in xs:
group = grouper(x)
if group not in groups:
groups[group] = []
groups[group].append(x)
return groups
print(group_by([1, 2, 3, 4, 5, 6], lambda x: "even" if x % 2 == 0 else "odd"))
| big_constant = 'YES'
def group_by(xs, grouper):
groups = {}
for x in xs:
group = grouper(x)
if group not in groups:
groups[group] = []
groups[group].append(x)
return groups
print(group_by([1, 2, 3, 4, 5, 6], lambda x: 'even' if x % 2 == 0 else 'odd')) |
NOTES = {
'notes': [
{'date': '2014-05-22T00:00:00Z', 'note': 'Second Note'},
{'date': '2014-05-21T14:02:45Z', 'note': 'First Note'}
]
}
SUBJECT = {
"subject": ['HB1-3840', 'H']
}
OWNER = {
"owner": "Owner"
}
EDITORIAL = {
"editor_group": "editorgroup",
"editor": "associate"
}... | notes = {'notes': [{'date': '2014-05-22T00:00:00Z', 'note': 'Second Note'}, {'date': '2014-05-21T14:02:45Z', 'note': 'First Note'}]}
subject = {'subject': ['HB1-3840', 'H']}
owner = {'owner': 'Owner'}
editorial = {'editor_group': 'editorgroup', 'editor': 'associate'}
seal = {'doaj_seal': True} |
def fatorial(n):
f = 1
while n != 0:
f *= n
n -= 1
return f
def dobro(n):
n *= 2
return n
def triplo(n):
n *= 3
return n
| def fatorial(n):
f = 1
while n != 0:
f *= n
n -= 1
return f
def dobro(n):
n *= 2
return n
def triplo(n):
n *= 3
return n |
#!/usr/bin/python3
# If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts
# Then the dynac system x_(n+1) = F(x_n) is Turing complete
# Proof by simulation (rule110)
a = 1
while a:
print(bin(a))
a = a ^ (a << 1) ^ (a & (a << 1)) ^ (a & (a << 1) & (a << 2))
| a = 1
while a:
print(bin(a))
a = a ^ a << 1 ^ a & a << 1 ^ a & a << 1 & a << 2 |
__author__ = "Daniel Winklehner"
__doc__ = "Find out if a number is a power of two"
def power_of_two(number):
"""
Function that checks if the input value (data) is a power of 2
(i.e. 2, 4, 8, 16, 32, ...)
"""
res = 0
while res == 0:
res = number % 2
number /= 2.0
prin... | __author__ = 'Daniel Winklehner'
__doc__ = 'Find out if a number is a power of two'
def power_of_two(number):
"""
Function that checks if the input value (data) is a power of 2
(i.e. 2, 4, 8, 16, 32, ...)
"""
res = 0
while res == 0:
res = number % 2
number /= 2.0
print('... |
load("//tools/bzl:maven_jar.bzl", "maven_jar")
def external_plugin_deps(omit_commons_codec = True):
JACKSON_VERS = "2.10.2"
maven_jar(
name = "scribejava-core",
artifact = "com.github.scribejava:scribejava-core:6.9.0",
sha1 = "ed761f450d8382f75787e8fee9ae52e7ec768747",
)
maven_j... | load('//tools/bzl:maven_jar.bzl', 'maven_jar')
def external_plugin_deps(omit_commons_codec=True):
jackson_vers = '2.10.2'
maven_jar(name='scribejava-core', artifact='com.github.scribejava:scribejava-core:6.9.0', sha1='ed761f450d8382f75787e8fee9ae52e7ec768747')
maven_jar(name='jackson-annotations', artifact... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'There is no appended list'},
{'abbr': 1,
'code': 1,
'title': 'Numbers define number of points corresponding to full coordinate '
'circles (i.e. parallels), coordinate values on each circle are '
... | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'There is no appended list'}, {'abbr': 1, 'code': 1, 'title': 'Numbers define number of points corresponding to full coordinate circles (i.e. parallels), coordinate values on each circle are multiple of the circle mesh, and extreme coordinate values given in grid... |
class InvalidSideException(Exception):
"""Invalid side"""
class NotSupportedException(Exception):
"""Not supported by dummy wallet"""
class InvalidProductException(Exception):
"""Invalid product type"""
class OutOfBoundsException(Exception):
"""Attempt to access memory outside buffer bounds"""
| class Invalidsideexception(Exception):
"""Invalid side"""
class Notsupportedexception(Exception):
"""Not supported by dummy wallet"""
class Invalidproductexception(Exception):
"""Invalid product type"""
class Outofboundsexception(Exception):
"""Attempt to access memory outside buffer bounds""" |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
seen = set()
curr = headA
while curr:
seen.add(curr)
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode:
seen = set()
curr = headA
while curr:
seen.add(curr)
curr = curr.next
cur... |
"""
Insertion Sort
Approach: Loop
Complexity: O(n2)
"""
def sort_insertion(input_arr):
print("""""""""""""""""""""""""")
print("input " + str(input_arr))
print("""""""""""""""""""""""""")
ln = len(input_arr)
i = 1 # Assuming first element is sorted
while i < ln: # n times
c = inpu... | """
Insertion Sort
Approach: Loop
Complexity: O(n2)
"""
def sort_insertion(input_arr):
print('')
print('input ' + str(input_arr))
print('')
ln = len(input_arr)
i = 1
while i < ln:
c = input_arr[i]
p = i
while p > 0 and input_arr[p - 1] > c:
input_arr[p] = in... |
""" fixtures that return an sql statement with a list of values to be inserted."""
def load_language():
""" return the sql and values of the insert queuery."""
sql = """
INSERT INTO Spanglish_Test.Language
(
`name`, `iso-639-1`
)
VALUES (%s, %s)
... | """ fixtures that return an sql statement with a list of values to be inserted."""
def load_language():
""" return the sql and values of the insert queuery."""
sql = '\n INSERT INTO Spanglish_Test.Language \n (\n `name`, `iso-639-1`\n ) \n VALUES (%s, %s)\n ... |
# Copyright 2020 Plezentek, Inc. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | load('//sqlc/private:providers.bzl', 'SQLCRelease')
load('//sqlc/private/rules_go/lib:platforms.bzl', 'PLATFORMS')
def _sqlc_toolchain_impl(ctx):
release = ctx.attr.release[SQLCRelease]
cross_compile = ctx.attr.goos != release.goos or ctx.attr.goarch != release.goarch
return [platform_common.ToolchainInfo(... |
root = {
"general" : {
"display_viewer" : False,
#The visible GPUS will be restricted to the numbers listed here. The pytorch (cuda:0) numeration will start at 0
#This is a trick to get everything onto the wanted gpus because just setting cuda:4 in the function calls will
#not work... | root = {'general': {'display_viewer': False, 'cuda_visible_devices': '1', 'save_track_results': True}, 'data': {'selection_interval': [0, 10000], 'source': {'base_folder': '/u40/zhanr110/MTA_ext_short/test', 'cam_ids': [1]}}, 'detector': {'mmdetection_config': 'detectors/mmdetection/configs/mta/faster_rcnn_r50_mta.py',... |
i=input("Enter a string: ")
list = i.split()
list.sort()
for i in list:
print(i,end=' ')
| i = input('Enter a string: ')
list = i.split()
list.sort()
for i in list:
print(i, end=' ') |
def test_one_plus_one_is_two():
assert 1 + 1 == 2 #o assert espera que algo seja verdadeiro, se for falso o teste quebrou
def test_negative_1_plus_1_is_3():
assert 1 + 1 == 3
| def test_one_plus_one_is_two():
assert 1 + 1 == 2
def test_negative_1_plus_1_is_3():
assert 1 + 1 == 3 |
values = []
for i in range(9):
values.append(int(input('')))
max_value = 0
location = 0
for i in range(9):
if values[i] > max_value:
max_value = values[i]
location = i+1
print(max_value)
print(location) | values = []
for i in range(9):
values.append(int(input('')))
max_value = 0
location = 0
for i in range(9):
if values[i] > max_value:
max_value = values[i]
location = i + 1
print(max_value)
print(location) |
"""Test whether putative triangles, specified as triples of side lengths,
in fact are possible."""
def load_triangles(filename):
"""Load triangles from filename."""
triangles = []
with open(filename) as f:
for line in f:
if line.strip():
triangles.append(tuple([int(side) ... | """Test whether putative triangles, specified as triples of side lengths,
in fact are possible."""
def load_triangles(filename):
"""Load triangles from filename."""
triangles = []
with open(filename) as f:
for line in f:
if line.strip():
triangles.append(tuple([int(side)... |
"""{{ cookiecutter.project_name }} - {{ cookiecutter.project_short_description }}"""
__version__ = "{{ cookiecutter.project_version }}"
__author__ = """{{ cookiecutter.author_name }}"""
__email__ = "{{ cookiecutter.author_email }}"
prog_name = "{{ cookiecutter.project_hyphen }}"
| """{{ cookiecutter.project_name }} - {{ cookiecutter.project_short_description }}"""
__version__ = '{{ cookiecutter.project_version }}'
__author__ = '{{ cookiecutter.author_name }}'
__email__ = '{{ cookiecutter.author_email }}'
prog_name = '{{ cookiecutter.project_hyphen }}' |
class BitcoinGoldMainNet(object):
"""Bitcoin Gold MainNet version bytes. """
NAME = "Bitcoin Gold Main Net"
COIN = "BTG"
SCRIPT_ADDRESS = 0x17 # int(0x17) = 23
PUBKEY_ADDRESS = 0x26 # int(0x26) = 38 # Used to create payment addresses
SECRET_KEY = 0x80 # int(0x80) = 128 # Used for WIF fo... | class Bitcoingoldmainnet(object):
"""Bitcoin Gold MainNet version bytes. """
name = 'Bitcoin Gold Main Net'
coin = 'BTG'
script_address = 23
pubkey_address = 38
secret_key = 128
ext_public_key = 76067358
ext_secret_key = 76066276
bip32_path = "m/44'/0'/0'/"
class Bitcoincashmainnet(... |
# OpenWeatherMap API Key
weather_api_key = "MyOpenWeatherMapAPIKey"
# Google API Key
g_key = "MyGoogleKey" | weather_api_key = 'MyOpenWeatherMapAPIKey'
g_key = 'MyGoogleKey' |
def attack():
pass
def defend():
pass
def pass_turn():
pass
def use_ability_One(kit):
pass
def use_ability_Two(kit):
pass
def end_Of_Battle():
pass | def attack():
pass
def defend():
pass
def pass_turn():
pass
def use_ability__one(kit):
pass
def use_ability__two(kit):
pass
def end__of__battle():
pass |
mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": 'c003.teste.jp@gmail.com',
"MAIL_PASSWORD": 'C003.teste'
} | mail_settings = {'MAIL_SERVER': 'smtp.gmail.com', 'MAIL_PORT': 465, 'MAIL_USE_TLS': False, 'MAIL_USE_SSL': True, 'MAIL_USERNAME': 'c003.teste.jp@gmail.com', 'MAIL_PASSWORD': 'C003.teste'} |
class Solution:
def maxArea(self, height) -> int:
left=0
right=len(height)-1
res=min(height[left],height[right])*(right-left)
while right>left:
res=max(res,(right-left)*min(height[right],height[left]))
if height[left]<height[right]:
left+=1
... | class Solution:
def max_area(self, height) -> int:
left = 0
right = len(height) - 1
res = min(height[left], height[right]) * (right - left)
while right > left:
res = max(res, (right - left) * min(height[right], height[left]))
if height[left] < height[right]:
... |
# Copyright (c) 2021, Omid Erfanmanesh, All rights reserved.
class RuntimeMode:
TRAIN = 0
TUNING = 1
CROSS_VAL = 2
FEATURE_IMPORTANCE = 3
| class Runtimemode:
train = 0
tuning = 1
cross_val = 2
feature_importance = 3 |
#
# Example file for HelloWorld
#
def main():
print("Hello World")
name = input("What is your name? ")
print("Nice to meet you,", name)
if __name__ == "__main__":
main()
| def main():
print('Hello World')
name = input('What is your name? ')
print('Nice to meet you,', name)
if __name__ == '__main__':
main() |
"""Node class module for Binary Tree."""
class Node(object):
"""The Node class."""
def __init__(self, value):
"""Initialization of node object."""
self.value = value
self.left = None
self.right = None
def __str__(self):
"""Return a string representation of the nod... | """Node class module for Binary Tree."""
class Node(object):
"""The Node class."""
def __init__(self, value):
"""Initialization of node object."""
self.value = value
self.left = None
self.right = None
def __str__(self):
"""Return a string representation of the node... |
class DispatchConfig:
def __init__(self, raw_config):
self.registered_commands = {}
for package in raw_config["handlers"]:
for command in package["commands"]:
self.registered_commands[command] = {
"class": package["class"],
"fullpat... | class Dispatchconfig:
def __init__(self, raw_config):
self.registered_commands = {}
for package in raw_config['handlers']:
for command in package['commands']:
self.registered_commands[command] = {'class': package['class'], 'fullpath': '.'.join([package['package'], packag... |
"""
This program visualizes nested for loops by printing number 0 through 3
and then 0 through 3 for the nested loop.
"""
for i in range(4):
print("Outer for loop: " + str(i))
for j in range(4):
print(" Inner for loop: " + str(j)) | """
This program visualizes nested for loops by printing number 0 through 3
and then 0 through 3 for the nested loop.
"""
for i in range(4):
print('Outer for loop: ' + str(i))
for j in range(4):
print(' Inner for loop: ' + str(j)) |
"""Queue implementation using circularly linked list for storage."""
class CircularQueue:
"""Queue implementation using circularly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next'
def __init__... | """Queue implementation using circularly linked list for storage."""
class Circularqueue:
"""Queue implementation using circularly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = ('_element', '_next')
def __init... |
"set operations for multiple sequences"
def intersect(*args):
res = []
for x in args[0]: # scan the first list
for other in args[1:]: # for all other arguments
if x not in other: break # this item in each one?
else:
res.append(x) #... | """set operations for multiple sequences"""
def intersect(*args):
res = []
for x in args[0]:
for other in args[1:]:
if x not in other:
break
else:
res.append(x)
return res
def union(*args):
res = []
for seq in args:
for x in seq:
... |
msg_dict = {
'resource_not_found':
'The resource you specified was not found',
'invalid_gender':
"The gender you specified is invalid!!",
'many_invalid_fields':
'Some errors occured while validating some fields. Please check and try again',
'unique':
'The {} you inputted already exists',... | msg_dict = {'resource_not_found': 'The resource you specified was not found', 'invalid_gender': 'The gender you specified is invalid!!', 'many_invalid_fields': 'Some errors occured while validating some fields. Please check and try again', 'unique': 'The {} you inputted already exists', 'user_not_found': 'The user with... |
'''
- Leetcode problem: 23
- Difficulty: Hard
- Brief problem description:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
- Solution Summary:
- Used Resources:
--- Bo Zhou
'''
# ... | """
- Leetcode problem: 23
- Difficulty: Hard
- Brief problem description:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
- Solution Summary:
- Used Resources:
--- Bo Zhou
"""
cla... |
# Written by Ivan Sapozhkov and Denis Chagin <denis.chagin@emlid.com>
#
# Copyright (c) 2016, Emlid Limited
# All rights reserved.
#
# Redistribution and use in source and binary forms,
# with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code ... | def create_security(proto, key_mgmt, group):
if not proto:
return 'open'
if not key_mgmt:
if 'wep' in group:
return 'wep'
else:
return None
elif 'wpa-psk' in key_mgmt:
if proto == 'WPA':
return 'wpapsk'
elif proto == 'RSN':
... |
"""
Check for Office file types
ViperMonkey is a specialized engine to parse, analyze and interpret Microsoft
VBA macros (Visual Basic for Applications), mainly for malware analysis.
Author: Philippe Lagadec - http://www.decalage.info
License: BSD, see source code or documentation
Project Repository:
https://github.... | """
Check for Office file types
ViperMonkey is a specialized engine to parse, analyze and interpret Microsoft
VBA macros (Visual Basic for Applications), mainly for malware analysis.
Author: Philippe Lagadec - http://www.decalage.info
License: BSD, see source code or documentation
Project Repository:
https://github.... |
# Given a singly linked list, determine if it is a palindrome.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
fast = slow = head
# find t... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def is_palindrome(self, head: ListNode) -> bool:
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
node = Non... |
"""
Rocky is a CLI based provisioning and management tool for CloudCIX Cloud software.
Rocky is designed to operate in an out of band (OOB) network, serarated from other CloudCIX networks.
Rocky's purpose is to facilitate monitoring, testing, debug and recovery
"""
__version__ = '0.3.5'
| """
Rocky is a CLI based provisioning and management tool for CloudCIX Cloud software.
Rocky is designed to operate in an out of band (OOB) network, serarated from other CloudCIX networks.
Rocky's purpose is to facilitate monitoring, testing, debug and recovery
"""
__version__ = '0.3.5' |
with open("inputday3.txt") as f:
data = [x for x in f.read().split()]
gamma = ""
epsilon = ""
for b in range(0, len(data[0])):
one = 0
zero = 0
for c in range(0, len(data)):
if data[c][b] == '0':
zero += 1
else:
one += 1
if zero > one:
... | with open('inputday3.txt') as f:
data = [x for x in f.read().split()]
gamma = ''
epsilon = ''
for b in range(0, len(data[0])):
one = 0
zero = 0
for c in range(0, len(data)):
if data[c][b] == '0':
zero += 1
else:
one += 1
if zero > one:
gamma += '0'
... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
"""Fizzbuzz for loop variant 3"""
for x in range(1, 101):
OUTPUT = ""
if x % 3 == 0:
OUTPUT += "Fizz"
if x % 5 == 0:
OUTPUT += "Buzz"
print(OUTPUT or x)
| """Fizzbuzz for loop variant 3"""
for x in range(1, 101):
output = ''
if x % 3 == 0:
output += 'Fizz'
if x % 5 == 0:
output += 'Buzz'
print(OUTPUT or x) |
# type: ignore
__all__ = [
"readDatastoreImage",
"datastore",
]
def readDatastoreImage(*args):
raise NotImplementedError("readDatastoreImage")
def datastore(*args):
raise NotImplementedError("datastore")
| __all__ = ['readDatastoreImage', 'datastore']
def read_datastore_image(*args):
raise not_implemented_error('readDatastoreImage')
def datastore(*args):
raise not_implemented_error('datastore') |
"""
Given scores of N athletes, find their relative ranks and the people with the top
three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and
"Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The fir... | """
Given scores of N athletes, find their relative ranks and the people with the top
three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and
"Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The fir... |
"""!
@brief Collection of examples devoted to containers.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
""" | """!
@brief Collection of examples devoted to containers.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
""" |
# THIS FILE IS GENERATED FROM SCIPY SETUP.PY
short_version = '1.5.4'
version = '1.5.4'
full_version = '1.5.4'
git_revision = '19acfed431060aafaa963f7e530c95e70cd4b85c'
release = True
if not release:
version = full_version
| short_version = '1.5.4'
version = '1.5.4'
full_version = '1.5.4'
git_revision = '19acfed431060aafaa963f7e530c95e70cd4b85c'
release = True
if not release:
version = full_version |
#
# PySNMP MIB module ZYXEL-AclV2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-AclV2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:43:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
class Temperature:
def __init__(self, kelvin=None, celsius=None, fahrenheit=None):
values = [x for x in [kelvin, celsius, fahrenheit] if x]
if len(values) < 1:
raise ValueError('Need argument')
if len(values) > 1:
raise ValueError('Only one argument')
if ce... | class Temperature:
def __init__(self, kelvin=None, celsius=None, fahrenheit=None):
values = [x for x in [kelvin, celsius, fahrenheit] if x]
if len(values) < 1:
raise value_error('Need argument')
if len(values) > 1:
raise value_error('Only one argument')
if ce... |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
M = float('inf')
# dynamic programming
dp = [0] + [M] * amount
for i in range(1, amount+1):
dp[i] = 1 + min([dp[i-c] for c in coins if i >= c] or [M])
return dp[-1] if dp[-1] < M else -1
| class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
m = float('inf')
dp = [0] + [M] * amount
for i in range(1, amount + 1):
dp[i] = 1 + min([dp[i - c] for c in coins if i >= c] or [M])
return dp[-1] if dp[-1] < M else -1 |
def removeLoop(head):
ptr = head
ptr2 = head
while True :
if ptr is None or ptr2 is None or ptr2.next is None :
return
ptr = ptr.next
ptr2 = ptr2.next.next
if ptr is ptr2 :
loopNode = ptr
break
ptr = loopNode.next
count = ... | def remove_loop(head):
ptr = head
ptr2 = head
while True:
if ptr is None or ptr2 is None or ptr2.next is None:
return
ptr = ptr.next
ptr2 = ptr2.next.next
if ptr is ptr2:
loop_node = ptr
break
ptr = loopNode.next
count = 1
while... |
students = []
def read_file():
try:
f = open("students.txt", "r")
for student in read_students(f):
students.append(student)
f.close()
except Exception:
print("Could not read file")
def read_students(f):
for line in f:
yield line
read_file()
print(stu... | students = []
def read_file():
try:
f = open('students.txt', 'r')
for student in read_students(f):
students.append(student)
f.close()
except Exception:
print('Could not read file')
def read_students(f):
for line in f:
yield line
read_file()
print(student... |
def extended_euclidean_algorithm(a, b):
# Initial s = 1
s = 1
list_s = []
list_t = []
# Algorithm
while b > 0:
# Find the remainder of a, b
r = a % b
if r > 0:
# The t expression
t = (r - (a * s)) // b
list_t.append(t)
list... | def extended_euclidean_algorithm(a, b):
s = 1
list_s = []
list_t = []
while b > 0:
r = a % b
if r > 0:
t = (r - a * s) // b
list_t.append(t)
list_s.append(s)
a = b
if r > 0:
b = r
else:
break
for i in... |
WIDTH = 20
HEIGHT = 14
TITLE = 'Click Ninja'
BACKGROUND = 'board'
def destroy(s):
sound('swoosh')
if s.name == 'taco':
score(50)
else:
score(5)
# draw a splatting image at the center position of the image
image('redsplat', center=s.event_pos, size=2).fade(1.0)
s.fade(0.25)
def ... | width = 20
height = 14
title = 'Click Ninja'
background = 'board'
def destroy(s):
sound('swoosh')
if s.name == 'taco':
score(50)
else:
score(5)
image('redsplat', center=s.event_pos, size=2).fade(1.0)
s.fade(0.25)
def failure(s):
score(-20)
if s.name == 'bomb':
s.des... |
DEPTH = 3
# Action
class Action:
top = [1, 0, 0, 0]
bottom = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]
actlist = [(-1, 0), (1, 0), (0, -1), (0, 1)]
mapAct = {
actlist[0]: top,
actlist[1]: bottom,
actlist[2]: left,
actlist[3]: right
}
def go(s... | depth = 3
class Action:
top = [1, 0, 0, 0]
bottom = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]
actlist = [(-1, 0), (1, 0), (0, -1), (0, 1)]
map_act = {actlist[0]: top, actlist[1]: bottom, actlist[2]: left, actlist[3]: right}
def go(state, action, board_height, board_width):
... |
def read_csv(root, file_name, keys):
with open('{root}private_static/csv/{file_name}.csv'.format(root=root, file_name=file_name)) as file:
data = file.read()
lines = data.split("\n")
return [dict(zip(keys, line.split(','))) for i, line in enumerate(lines) if i != 0]
| def read_csv(root, file_name, keys):
with open('{root}private_static/csv/{file_name}.csv'.format(root=root, file_name=file_name)) as file:
data = file.read()
lines = data.split('\n')
return [dict(zip(keys, line.split(','))) for (i, line) in enumerate(lines) if i != 0] |
# -*- coding: utf-8 -*-
'''
Copyright 2012 Rodrigo Pinheiro Matias <rodrigopmatias@gmail.com>
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 r... | """
Copyright 2012 Rodrigo Pinheiro Matias <rodrigopmatias@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
def main():
# input
A = input()
# compute
# output
if A == 'a':
print(-1)
else:
print('a')
if __name__ == '__main__':
main()
| def main():
a = input()
if A == 'a':
print(-1)
else:
print('a')
if __name__ == '__main__':
main() |
## mv to //:WORKSPACE.bzl ocaml_configure
load("//ocaml/_bootstrap:ocaml.bzl", _ocaml_configure = "ocaml_configure")
# load("//ocaml/_bootstrap:obazl.bzl", _obazl_configure = "obazl_configure")
load("//ocaml/_rules:ocaml_repository.bzl" , _ocaml_repository = "ocaml_repository")
# load("//ocaml/_rules:opam_confi... | load('//ocaml/_bootstrap:ocaml.bzl', _ocaml_configure='ocaml_configure')
load('//ocaml/_rules:ocaml_repository.bzl', _ocaml_repository='ocaml_repository')
ocaml_configure = _ocaml_configure
ocaml_repository = _ocaml_repository |
class AthenaError(Exception):
"""base class for all athena exceptions"""
pass
class AthenaMongoError(AthenaError):
"""Class for all mongo related errors"""
pass | class Athenaerror(Exception):
"""base class for all athena exceptions"""
pass
class Athenamongoerror(AthenaError):
"""Class for all mongo related errors"""
pass |
class MetricsService:
def __init__(self, adc_data, metrics_data):
self._adc_data = adc_data
self._metrics_data = metrics_data
@property
def metrics_data(self):
return self._metrics_data
def update(self):
self._metrics_data.is_new_data_available = False
if self.... | class Metricsservice:
def __init__(self, adc_data, metrics_data):
self._adc_data = adc_data
self._metrics_data = metrics_data
@property
def metrics_data(self):
return self._metrics_data
def update(self):
self._metrics_data.is_new_data_available = False
if self.... |
#sum(iterable, start=0, /)
#Return the sum of a 'start' value (default: 0) plus an iterable of numbers
#When the iterable is empty, return the start value.
'''This function is intended specifically for use with numeric values and may
reject non-numeric types.'''
a = [1,3,5,7,9,4,6,2,8]
print(sum(a))
pr... | """This function is intended specifically for use with numeric values and may
reject non-numeric types."""
a = [1, 3, 5, 7, 9, 4, 6, 2, 8]
print(sum(a))
print(sum(a, start=4)) |
def find_accounts(search_text):
# perform search...
if not db_is_available:
return None
# returns a list of account IDs
return db_search(search_text)
accounts = find_accounts('python')
if accounts is None:
print("Error: DB not available")
else:
print("Accounts found: Would list them he... | def find_accounts(search_text):
if not db_is_available:
return None
return db_search(search_text)
accounts = find_accounts('python')
if accounts is None:
print('Error: DB not available')
else:
print('Accounts found: Would list them here...')
def db_search(search_text):
return [1, 11]
db_is_... |
fruits = ["orange", "banana", "apple", "avocado", "kiwi", "apricot",
"cherry", "grape", "coconut", "lemon", "mango", "peach",
"pear", "strawberry", "pineapple", "apple", "orange", "pear",
"grape", "banana"
]
filters = dict()
for key in fruits:
filters[key] = 1
result =... | fruits = ['orange', 'banana', 'apple', 'avocado', 'kiwi', 'apricot', 'cherry', 'grape', 'coconut', 'lemon', 'mango', 'peach', 'pear', 'strawberry', 'pineapple', 'apple', 'orange', 'pear', 'grape', 'banana']
filters = dict()
for key in fruits:
filters[key] = 1
result = set(filters.keys())
print(result) |
#module.py
def hello():
print("Hello!")
#if __name__=="__main__":
# print(__name__) | def hello():
print('Hello!') |
class IOEngine(object):
def __init__(self, node):
self.node = node
self.inputs = []
self.outputs = []
def release(self):
self.inputs = None
self.outputs = None
self.node = None
def updateInputs(self, names):
# remove prior outputs
for input... | class Ioengine(object):
def __init__(self, node):
self.node = node
self.inputs = []
self.outputs = []
def release(self):
self.inputs = None
self.outputs = None
self.node = None
def update_inputs(self, names):
for input_node in self.inputs:
... |
class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class Binary_Tree:
def __init__(self):
self.root = None
def pre_order(self):
""" root-left-right """
try:
self.values=[]
if self.ro... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binary_Tree:
def __init__(self):
self.root = None
def pre_order(self):
""" root-left-right """
try:
self.values = []
if self.root == ... |
#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | model = model()
i1 = input('op1', 'TENSOR_FLOAT32', '{1, 3, 3, 2}')
f1 = input('op2', 'TENSOR_FLOAT32', '{1, 2, 2, 4}')
b1 = input('op3', 'TENSOR_FLOAT32', '{4}')
pad0 = int32_scalar('pad0', 0)
act = int32_scalar('act', 0)
stride = int32_scalar('stride', 1)
cm = int32_scalar('channelMultiplier', 2)
output = output('op4... |
class Check_Excessive_Current(object):
def __init__(self,chain_name,cf,handlers,irrigation_io,irrigation_hash_control,get_json_object):
self.get_json_object = get_json_object
cf.define_chain(chain_name, False )
#cf.insert.log("check_excessive_current")
cf.insert.ass... | class Check_Excessive_Current(object):
def __init__(self, chain_name, cf, handlers, irrigation_io, irrigation_hash_control, get_json_object):
self.get_json_object = get_json_object
cf.define_chain(chain_name, False)
cf.insert.assert_function_reset(self.check_excessive_current)
cf.in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.