content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def is_palindrome(word):
for left in range(len(word) // 2):
right = len(word) - left - 1
if word[left] != word[right]:
return False
return True
if __name__ == "__main__":
print(is_palindrome("racecar"))
| def is_palindrome(word):
for left in range(len(word) // 2):
right = len(word) - left - 1
if word[left] != word[right]:
return False
return True
if __name__ == '__main__':
print(is_palindrome('racecar')) |
load(
"//:repositories.bzl",
"io_grpc_grpc_java",
"javax_annotation_javax_annotation_api",
"com_google_errorprone_error_prone_annotations",
"rules_proto_grpc_repos",
)
def java_repos(**kwargs):
rules_proto_grpc_repos(**kwargs)
io_grpc_grpc_java(**kwargs)
javax_annotation_javax_annotatio... | load('//:repositories.bzl', 'io_grpc_grpc_java', 'javax_annotation_javax_annotation_api', 'com_google_errorprone_error_prone_annotations', 'rules_proto_grpc_repos')
def java_repos(**kwargs):
rules_proto_grpc_repos(**kwargs)
io_grpc_grpc_java(**kwargs)
javax_annotation_javax_annotation_api(**kwargs)
com... |
def test_static_method():
class Base:
@staticmethod
def say() -> int:
return 1
class A(Base):
pass
class B(Base):
pass
a = A()
b = B()
assert a.say() == b.say()
def test_class_method():
class Base:
field = None
@classmethod
... | def test_static_method():
class Base:
@staticmethod
def say() -> int:
return 1
class A(Base):
pass
class B(Base):
pass
a = a()
b = b()
assert a.say() == b.say()
def test_class_method():
class Base:
field = None
@classmethod
... |
'''
Description:
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be ... | """
Description:
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be ... |
class AbstractTranslator:
def __init__(self, source_text, translate_from, translate_to, queue=None):
self.queue = queue
self.source_text = source_text
self.translate_from = translate_from
self.translate_to = translate_to
self.translation = ''
def _external_api_in... | class Abstracttranslator:
def __init__(self, source_text, translate_from, translate_to, queue=None):
self.queue = queue
self.source_text = source_text
self.translate_from = translate_from
self.translate_to = translate_to
self.translation = ''
def _external_api_integrati... |
with open('./data/AOC5.txt', 'r') as passport_file:
seats = [str(f) for f in passport_file.read().splitlines()]
def up_down(instruction: str, number_list):
lower, upper = split_list(number_list)
if instruction == 'F' or instruction == 'L':
return lower
elif instruction == 'B' or instruction ==... | with open('./data/AOC5.txt', 'r') as passport_file:
seats = [str(f) for f in passport_file.read().splitlines()]
def up_down(instruction: str, number_list):
(lower, upper) = split_list(number_list)
if instruction == 'F' or instruction == 'L':
return lower
elif instruction == 'B' or instruction =... |
"""Some data and functions useful for converting to Lilypond"""
pitch_level = {"do": 0,
"di": 0,
"ra": 1,
"re": 1,
"ri": 1,
"me": 2,
"mi": 2,
"fa": 3,
"fi": 3,
"se": 4,
... | """Some data and functions useful for converting to Lilypond"""
pitch_level = {'do': 0, 'di': 0, 'ra': 1, 're': 1, 'ri': 1, 'me': 2, 'mi': 2, 'fa': 3, 'fi': 3, 'se': 4, 'sol': 4, 'si': 4, 'le': 5, 'la': 5, 'li': 5, 'te': 6, 'ti': 6}
key_octave_offset = {'fis major': -3, 'gis minor': 3, 'c minor': 0, 'a minor': 2, 'eis ... |
def sums(n, k):
"""
Implement sums, which takes two positive integers n and k. It returns a list of lists containing all
the ways that a list of k positive integers can sum to n. Results can appear in any order.
Return the ways in which K positive integers can sum to N.
>>> sums(2, 2)
[[1, 1]]... | def sums(n, k):
"""
Implement sums, which takes two positive integers n and k. It returns a list of lists containing all
the ways that a list of k positive integers can sum to n. Results can appear in any order.
Return the ways in which K positive integers can sum to N.
>>> sums(2, 2)
[[1, 1]]
... |
{
'targets': [
{
'target_name': 'tinyxml2',
'type': '<(library)',
'direct_dependent_settings': {
'include_dirs': [ '.', ],
},
'sources': [
'tinyxml2.h',
'tinyxml2.cpp'
]
},
],
} | {'targets': [{'target_name': 'tinyxml2', 'type': '<(library)', 'direct_dependent_settings': {'include_dirs': ['.']}, 'sources': ['tinyxml2.h', 'tinyxml2.cpp']}]} |
# Puzzle Input ----------
with open('Day02-Input.txt', 'r') as file:
puzzle = file.read().split('\n')
with open('Day02-Test01.txt', 'r') as file:
test01 = file.read().split('\n')
# Main Code ----------
# Split the command and number into a tuple and convert to the right data type
def split_and_convert(comma... | with open('Day02-Input.txt', 'r') as file:
puzzle = file.read().split('\n')
with open('Day02-Test01.txt', 'r') as file:
test01 = file.read().split('\n')
def split_and_convert(command):
command = command.split()
return (command[0], int(command[1]))
def find_position(commands):
commands = list(map(s... |
class IDataConversionMonitor:
"""
A base class for an application-specific logger. It should be used to track errors during conversion and/or ,track conversion progress,cancel a conversion process if necessary.
Implementing a logger class is optional,but highly recommended for all but most basic data conv... | class Idataconversionmonitor:
"""
A base class for an application-specific logger. It should be used to track errors during conversion and/or ,track conversion progress,cancel a conversion process if necessary.
Implementing a logger class is optional,but highly recommended for all but most basic data converte... |
number_of_people=int(input("how many people are there for this survey? "))
survey={}
geners={"Horror":0 , "Romance":0 , "Comedy":0 , "History":0 , "Adventure":0 , "Action":0 }
geners_list=[]
for i in range(number_of_people):
temp_name=input('\nplease enter your name: ')
for j in survey:
if j==temp_name:... | number_of_people = int(input('how many people are there for this survey? '))
survey = {}
geners = {'Horror': 0, 'Romance': 0, 'Comedy': 0, 'History': 0, 'Adventure': 0, 'Action': 0}
geners_list = []
for i in range(number_of_people):
temp_name = input('\nplease enter your name: ')
for j in survey:
if j =... |
# PythonJS binding for Ace Editor http://ace.c9.io/
# by Brett Hartshorn - copyright 2013
# License: "New BSD"
class AceEditor:
def __init__(self, div_id='editor', mode='python', theme=None):
with javascript: self[...] = ace.edit( div_id )
if mode: self.setMode( mode )
if theme: self.setTheme( theme )
def set... | class Aceeditor:
def __init__(self, div_id='editor', mode='python', theme=None):
with javascript:
self[...] = ace.edit(div_id)
if mode:
self.setMode(mode)
if theme:
self.setTheme(theme)
def set_mode(self, mode):
with javascript:
s... |
class Enemy:
def __init__(self, name, desc, hp, strength, dexterity, defense, exp, coinL, coinH):
self.name = name
self.desc = desc
self.hp = hp
self.strength = strength
self.dexterity = dexterity
self.defense = defense
self.exp = exp
self.coinL = coin... | class Enemy:
def __init__(self, name, desc, hp, strength, dexterity, defense, exp, coinL, coinH):
self.name = name
self.desc = desc
self.hp = hp
self.strength = strength
self.dexterity = dexterity
self.defense = defense
self.exp = exp
self.coinL = coi... |
# using a hashtable to count individual items
# define a set of items that we want to count
items = ["apple", "pear", "orange", "banana", "apple",
"orange", "apple", "pear", "banana", "orange",
"apple", "kiwi", "pear", "apple", "orange"]
# TODO: create a hashtable object to hold the items and count... | items = ['apple', 'pear', 'orange', 'banana', 'apple', 'orange', 'apple', 'pear', 'banana', 'orange', 'apple', 'kiwi', 'pear', 'apple', 'orange']
counter = None
print(counter) |
#!/python3/bin/python3
5
x = 5
print("intial value of x \a")
print(x)
x=x + 1
print(x)
| 5
x = 5
print('intial value of x \x07')
print(x)
x = x + 1
print(x) |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 The Pybricks Authors
"""
Hardware Module: Any hub.
Description: Prints Hello world!
"""
print("Hello world!")
| """
Hardware Module: Any hub.
Description: Prints Hello world!
"""
print('Hello world!') |
RootWindow # unused class (libsyntyche/app.py:11)
StackedRootWindow # unused class (libsyntyche/app.py:22)
_.stack # unused attribute (libsyntyche/app.py:27)
run_app # unused function (libsyntyche/app.py:38)
_.eventFilter # unused method (libsyntyche/app.py:47)
obj # unused variable (libsyntyche/app.py:47)
autoco... | RootWindow
StackedRootWindow
_.stack
run_app
_.eventFilter
obj
autocomplete_file_path
_.as_bool
_.as_int
_.as_qcolor
_.as_qkey_sequence
_.as_path
_.optionxform
_.config_dir
QtOption
QtSubOptionList
QtSectionDictOption
QtSubSectionOption
eventFilter
obj
_.exec_command
MessageTray
_.add_message
Searcher
_.search_or_repla... |
# -*- coding: utf-8 -*-
if __name__ == '__main__':
cases = int(input())
for case in range(cases):
output = [float(num) for num in input().split()]
average = sum(output[1:]) / float(output[0])
count = sum(1 for num in output[1:] if float(num) > float(average))
percent = round(co... | if __name__ == '__main__':
cases = int(input())
for case in range(cases):
output = [float(num) for num in input().split()]
average = sum(output[1:]) / float(output[0])
count = sum((1 for num in output[1:] if float(num) > float(average)))
percent = round(count / output[0] * 100, 3... |
# adds in Platform column into datatable which represents on what platforms the show or movie is availble on
def plat(row):
string = ''
if row['Netflix'] == 1:
if string == '':
string+='Netflix'
else:
string+=',Netflix'
if row['Hulu'] == 1:
if string == '':
... | def plat(row):
string = ''
if row['Netflix'] == 1:
if string == '':
string += 'Netflix'
else:
string += ',Netflix'
if row['Hulu'] == 1:
if string == '':
string += 'Hulu'
else:
string += ',Hulu'
if row['Prime Video'] == 1:
... |
{
"variables": {
'v8_enable_pointer_compression': 0,
'v8_enable_31bit_smis_on_64bit_arch': 0,
},
"targets": [
{
"target_name": "turbo-linecount",
"sources": ["addon.cpp", "turbo_linecount.cpp"],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
'include_dirs': ["<!@(node -p \"requi... | {'variables': {'v8_enable_pointer_compression': 0, 'v8_enable_31bit_smis_on_64bit_arch': 0}, 'targets': [{'target_name': 'turbo-linecount', 'sources': ['addon.cpp', 'turbo_linecount.cpp'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'conditions': [... |
#In order to import and use these functions you will need the following lines of code:
#For a specific function:
# from math_functions import *function name*
#For all functions:
# import math_functions
#Note: in order to use the functions in this case you will need to write:
# math_functions.*... | def sum_ints(n, m, l, L):
s = sum([x for x in range(l, L) if x % n == 0 or x % m == 0])
return S
def int_reverse():
num = int(input('Enter an integer to reverse here: '))
temp = num
hold = 0
rev = 0
while temp > 0:
hold = temp % 10
rev = rev * 10 + hold
temp = temp -... |
# -*- coding: utf-8 -*-
"""
Module docstring
TODO:
* Write module docstring
"""
class Hand:
"""Class to represent a hand of playing cards"""
def __init__(self):
self.cards = list()
self.value = 0
self.soft_value = 0
self.blackjack = False
self.bust = False
de... | """
Module docstring
TODO:
* Write module docstring
"""
class Hand:
"""Class to represent a hand of playing cards"""
def __init__(self):
self.cards = list()
self.value = 0
self.soft_value = 0
self.blackjack = False
self.bust = False
def __str__(self):
... |
print("".strip())
print(" \t\n\r\v\f".strip())
print(" T E S T".strip())
print("abcabc".strip("ce"))
print("aaa".strip("b"))
print("abc efg ".strip("g a"))
| print(''.strip())
print(' \t\n\r\x0b\x0c'.strip())
print(' T E S T'.strip())
print('abcabc'.strip('ce'))
print('aaa'.strip('b'))
print('abc efg '.strip('g a')) |
# list of experiments exported to calling script
exps = []
# add experiments to the global list.
# a local function that keeps the internal variables from becoming global
def define_experiments():
binary = False
binaryflag = "" if binary else "--no-binary"
partfunc = "twitternew" if binary else "twitternew... | exps = []
def define_experiments():
binary = False
binaryflag = '' if binary else '--no-binary'
partfunc = 'twitternew' if binary else 'twitternew-text'
server_cmd = './obj/pqserver'
init_cmd = '%s --twitternew --verbose %s --initialize --no-populate --no-execute' % (serverCmd, binaryflag)
popu... |
# Copyright 2018 Google 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 a... | """ This template creates a logsink (logging sink). """
def create_pubsub(context, logsink_name):
""" Create the pubsub destination. """
properties = context.properties
project_id = properties.get('destinationProject', properties.get('project', context.env['project']))
dest_properties = []
if 'pubs... |
def main():
file = open('input.txt', 'r')
data = file.readlines()
gamma_rate = ''
epsilon_rate = ''
length = len(data[0]) -1
for i in range(length):
zeros = 0
ones = 0
for j in range(len(data)):
if(data[j][i] == '0' ):
zeros += 1
else:
ones += 1
if(zeros > ones):
gamma_rate += '0'
... | def main():
file = open('input.txt', 'r')
data = file.readlines()
gamma_rate = ''
epsilon_rate = ''
length = len(data[0]) - 1
for i in range(length):
zeros = 0
ones = 0
for j in range(len(data)):
if data[j][i] == '0':
zeros += 1
els... |
# file reading (in bytes mode)
f = open('exception_learning.py', 'rb')
file_content = f.read(3)
print(file_content)
file_content = f.read(3)
print(file_content)
f.seek(0)
file_content = f.read(3)
print(file_content)
f.close()
# file writing (in text mode)
f = open('new_file.txt', mode='w')
f.write('123457890')
f.seek(... | f = open('exception_learning.py', 'rb')
file_content = f.read(3)
print(file_content)
file_content = f.read(3)
print(file_content)
f.seek(0)
file_content = f.read(3)
print(file_content)
f.close()
f = open('new_file.txt', mode='w')
f.write('123457890')
f.seek(3)
f.write('aa')
f.close()
files = []
for i in range(100000):
... |
z = int(input())
while z > 0:
num = int(input())
temp = s = 0
for y in range(0 , num):
if temp == 0:
s += 1
temp = 1
else:
s -= 1
temp = 0
print(s)
z -= 1 | z = int(input())
while z > 0:
num = int(input())
temp = s = 0
for y in range(0, num):
if temp == 0:
s += 1
temp = 1
else:
s -= 1
temp = 0
print(s)
z -= 1 |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if self.value >= value:
self.insert_left(value)
else:
self.insert_right(value)
def insert_left(self, value):
if ... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if self.value >= value:
self.insert_left(value)
else:
self.insert_right(value)
def insert_left(self, value):
if sel... |
__name__ = 'debiasmedimg'
major = 0
minor = 0
patch = 0
__version__ = '{}.{}.{}'.format(major, minor, patch)
__author__ = 'Ann-Katrin Thebille'
__fname__, *_, __lname__ = __author__.lower().split(' ')
__university__ = 'uni-hamburg'
__institute__ = 'zmnh'
__domain__ = '{}{}{}.de'.format(__institute__, '.' if __unive... | __name__ = 'debiasmedimg'
major = 0
minor = 0
patch = 0
__version__ = '{}.{}.{}'.format(major, minor, patch)
__author__ = 'Ann-Katrin Thebille'
(__fname__, *_, __lname__) = __author__.lower().split(' ')
__university__ = 'uni-hamburg'
__institute__ = 'zmnh'
__domain__ = '{}{}{}.de'.format(__institute__, '.' if __univers... |
def extractCaelumLexCom(item):
'''
Parser for 'caelum-lex.com'
'''
# Wat
return False | def extract_caelum_lex_com(item):
"""
Parser for 'caelum-lex.com'
"""
return False |
ChartInfo = provider(fields=["chartname", "version", "repository"])
def _helm_chart_impl(ctx):
# make the dependencies.yaml template
requirements = "cat <<EOF\ndependencies:\n"
for dep in ctx.attr.deps:
requirements += "- name: \"%s\"\n" % (dep[ChartInfo].chartname,)
requirements += " ver... | chart_info = provider(fields=['chartname', 'version', 'repository'])
def _helm_chart_impl(ctx):
requirements = 'cat <<EOF\ndependencies:\n'
for dep in ctx.attr.deps:
requirements += '- name: "%s"\n' % (dep[ChartInfo].chartname,)
requirements += ' version: "%s"\n' % (dep[ChartInfo].version,)
... |
"""
Mi Aporte!
Tema: Map (Con lambda y operador ternario)
"""
class Empleado:
def __init__(self, nombre, cargo, salario):
self.nombre = nombre
self.cargo = cargo
self.salario = salario
def __str__(self):
return f'Mi nombre es {self.nombre} y tengo un salario de {self.salari... | """
Mi Aporte!
Tema: Map (Con lambda y operador ternario)
"""
class Empleado:
def __init__(self, nombre, cargo, salario):
self.nombre = nombre
self.cargo = cargo
self.salario = salario
def __str__(self):
return f'Mi nombre es {self.nombre} y tengo un salario de {self.salario}'... |
'''Functions for accessing databases
This library contains functions that will allow you to write
high performance code for accessing various databases. Currently
it only has access to Postgres libraries.
Specifications of the locations of the databases are assumed to be present
within the ``../config/db.json`... | """Functions for accessing databases
This library contains functions that will allow you to write
high performance code for accessing various databases. Currently
it only has access to Postgres libraries.
Specifications of the locations of the databases are assumed to be present
within the ``../config/db.json`` file.... |
class DeploymentParameter(object):
CURRENT_DESIRED = {'name': 'current.desired.state',
'description': "Desired state of the container's current task."}
CURRENT_STATE = {'name': 'current.state',
'description': "Actual state of the container's current task."}
CU... | class Deploymentparameter(object):
current_desired = {'name': 'current.desired.state', 'description': "Desired state of the container's current task."}
current_state = {'name': 'current.state', 'description': "Actual state of the container's current task."}
current_error = {'name': 'current.error.message', ... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s=list(s)
s=sorted(s)
t=list(t)
t=sorted(t)
return t==s
| class Solution(object):
def is_anagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s = list(s)
s = sorted(s)
t = list(t)
t = sorted(t)
return t == s |
# https://www.hackerrank.com/challenges/python-quest-1/problem
for i in range(
1, int(input())
): # More than 2 lines will result in 0 score. Do not leave a blank line also
print((10 ** (i) // 9) * i)
| for i in range(1, int(input())):
print(10 ** i // 9 * i) |
def prime_factors(n):
factors = {}
while n != 1:
divider = 2
while n%divider != 0: divider += 1
n /= divider
factors[divider] = factors[divider] + 1 if factors.get(divider) else 1
return ''.join(f'({divider}**{quantity})' if quantity > 1 else f'({divider})' for divider,qu... | def prime_factors(n):
factors = {}
while n != 1:
divider = 2
while n % divider != 0:
divider += 1
n /= divider
factors[divider] = factors[divider] + 1 if factors.get(divider) else 1
return ''.join((f'({divider}**{quantity})' if quantity > 1 else f'({divider})' for... |
def khan(graph):
n = len(graph)
in_degree = [0] * n
idx = [0] * n
for i in range(n):
for edge in graph[i]:
in_degree[edge] += 1
# print("The indegree is:", in_degree)
q = []
topo_sort = []
# Adding all elements with indegree zero into the queue
for i in range(... | def khan(graph):
n = len(graph)
in_degree = [0] * n
idx = [0] * n
for i in range(n):
for edge in graph[i]:
in_degree[edge] += 1
q = []
topo_sort = []
for i in range(n):
if in_degree[i] == 0:
q.append(i)
nr = 0
while q:
node = q.pop()
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
ans = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root):
... | class Solution:
ans = None
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root):
if not root:
return 0
mid = int(root == p or root == q)
left = dfs(root.left)
right = dfs(root.right... |
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
i = 0
for i in range(len(nums)):
if i == 0 or nums[i] > nums[i - 1]:
l = i + 1
r = len(nums... | class Solution:
def three_sum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
i = 0
for i in range(len(nums)):
if i == 0 or nums[i] > nums[i - 1]:
l = i + 1
r = len(nu... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
L = len(lists)
... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def merge_k_lists(self, lists):
l = len(lists)
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
results = []
... | class Solution:
def find_leaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
results = []
def distance_to_leave(node):
nonlocal results
if node is None:
return 0
distance = 1 + max(distance_to_... |
class Dispatcher:
def can_dispatch(self, request):
raise NotImplementedError()
def dispatch(self, request):
raise NotImplementedError()
class Transport:
def can_transport(self, request):
pass
def send_request(self, context, data):
raise NotImplementedError()
def ... | class Dispatcher:
def can_dispatch(self, request):
raise not_implemented_error()
def dispatch(self, request):
raise not_implemented_error()
class Transport:
def can_transport(self, request):
pass
def send_request(self, context, data):
raise not_implemented_error()
... |
print("what is your name?")
name = input()
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print(f"So, {name}, you're {age} old, {height} tall and {weight} pounds heavy.") | print('what is your name?')
name = input()
print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print('How much do you weigh?', end=' ')
weight = input()
print(f"So, {name}, you're {age} old, {height} tall and {weight} pounds heavy.") |
for row in range(4):
for col in range(8):
if row-col==0 or row+col==6:
print('*', end = '')
else:
print(' ', end = '')
print()
| for row in range(4):
for col in range(8):
if row - col == 0 or row + col == 6:
print('*', end='')
else:
print(' ', end='')
print() |
order = {
"starter": {1: "Salad", 2: "Soup"},
"main": {1: ["Burger", "Fries"], 2: ["Steak"]},
"dessert": {1: ["Ice Cream"], 2: []},
}
print(order["main"][2][0]) | order = {'starter': {1: 'Salad', 2: 'Soup'}, 'main': {1: ['Burger', 'Fries'], 2: ['Steak']}, 'dessert': {1: ['Ice Cream'], 2: []}}
print(order['main'][2][0]) |
def binary_search(array, target):
left = 0
right = len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
def t... | def binary_search(array, target):
left = 0
right = len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
def te... |
{
"targets": [
{
"target_name": "my_addon",
"sources": ["my_addon.cc"],
"include_dirs" : [ "<!(node -e \"require('nan')\")" ]
}
]
} | {'targets': [{'target_name': 'my_addon', 'sources': ['my_addon.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
owner_users = {'email': 'slam_ua@mail.ru',
'password': 'qwe123qwe'}
provider_users = {'nik.urgant@mail.ru': 'qwe123qwe',
'maks.sotnikov.62@mail.ru': 'qwe123qwe',
'provider123@i.ua': 'provider-123',
'prov... | owner_users = {'email': 'slam_ua@mail.ru', 'password': 'qwe123qwe'}
provider_users = {'nik.urgant@mail.ru': 'qwe123qwe', 'maks.sotnikov.62@mail.ru': 'qwe123qwe', 'provider123@i.ua': 'provider-123', 'provider234@i.ua': 'provider-234', 'provider345@i.ua': 'provider-345', 'provider456@i.ua': 'provider-456'}
broker = {'url... |
course_config = {
"type": "object",
"patternProperties": {"": {"type": "array", "items": {"type": "string"}}},
}
grading_stage = {
"type": ["object", "null"],
"properties": {
"image": {"type": "string"},
"env": {"type": "object"},
"entrypoint": {"type": "array", "items": {"type"... | course_config = {'type': 'object', 'patternProperties': {'': {'type': 'array', 'items': {'type': 'string'}}}}
grading_stage = {'type': ['object', 'null'], 'properties': {'image': {'type': 'string'}, 'env': {'type': 'object'}, 'entrypoint': {'type': 'array', 'items': {'type': 'string'}}, 'networking': {'type': 'boolean'... |
"""
This package contains the DirectGui system, a set of classes
responsible for drawing graphical widgets to the 2-D scene graph.
It is based on the lower-level PGui system, which is implemented in
C++.
For convenience, all of the DirectGui widgets may be imported from a
single module as follows::
from direct.gu... | """
This package contains the DirectGui system, a set of classes
responsible for drawing graphical widgets to the 2-D scene graph.
It is based on the lower-level PGui system, which is implemented in
C++.
For convenience, all of the DirectGui widgets may be imported from a
single module as follows::
from direct.gu... |
"""
The main modules in this package are:
* vnc_cfg_api_server
* gen.resource_common
* gen.resource_xsd
* vnc_cfg_ifmap
* vnc_addr_mgmt
* vnc_cfg_types
* vnc_cpu_info
"""
| """
The main modules in this package are:
* vnc_cfg_api_server
* gen.resource_common
* gen.resource_xsd
* vnc_cfg_ifmap
* vnc_addr_mgmt
* vnc_cfg_types
* vnc_cpu_info
""" |
""" Asked by: Dropbox [Medium].
Given the root to a binary search tree, find the second largest node in the tree.
""" | """ Asked by: Dropbox [Medium].
Given the root to a binary search tree, find the second largest node in the tree.
""" |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return self.data
class LinkedList:
def __init__(self, data=None):
self._head = Node(data)
self._size = 1 if data else 0
def __len__(self):
return self._size
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return self.data
class Linkedlist:
def __init__(self, data=None):
self._head = node(data)
self._size = 1 if data else 0
def __len__(self):
return self._size
... |
# Non-overlapping Intervals
'''
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2... | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]... |
"""
Sudoku Solver
URL: https://www.codewars.com/kata/sudoku-solver/python
Write a function that will solve a 9x9 Sudoku puzzle. The function
will take one argument consisting of the 2D puzzle array, with the
value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e.
det... | """
Sudoku Solver
URL: https://www.codewars.com/kata/sudoku-solver/python
Write a function that will solve a 9x9 Sudoku puzzle. The function
will take one argument consisting of the 2D puzzle array, with the
value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e.
det... |
# -----------------------------------------------------------------------------
# Name: arc.py
# Purpose: Object for storing the syntactic unit of an arc
#
# Author: Robert Snarrenberg
# Copyright: (c) 2022 by Robert Snarrenberg
# License: BSD, see license.txt
# ------------------------------... | """
Arc
====
The Arc class stores information about an arc's syntactic function."""
class Arc:
"""An arc is a syntactic unit that comprises at least two notes.
The main content of an arc is a list of note indexes. Arcs are
generated by the syntax parser.
Types include passing, neighboring, repetition... |
class Tag():
@property
def title(self) -> str:
return self._title
@title.setter
def title(self, value: str):
if not isinstance(value, str):
raise TypeError("value must be a string")
self._title = value
| class Tag:
@property
def title(self) -> str:
return self._title
@title.setter
def title(self, value: str):
if not isinstance(value, str):
raise type_error('value must be a string')
self._title = value |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
line = line.rstrip()
if not line.startswith('From ') : continue
line2 = line.split()
line3 = line2[5]
line4 = line3.split(':')
counts[line4[0]] = counts.get(line4[0], 0)... | name = input('Enter file:')
if len(name) < 1:
name = 'mbox-short.txt'
handle = open(name)
counts = dict()
for line in handle:
line = line.rstrip()
if not line.startswith('From '):
continue
line2 = line.split()
line3 = line2[5]
line4 = line3.split(':')
counts[line4[0]] = counts.get(li... |
def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0] # best to choose a random element as the pivot
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
def... | def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
def find_maximum_number(items):
""" Exercise 4... |
"""
Implementation of the public HTTP APIs related to locating a user based
on provided data.
"""
| """
Implementation of the public HTTP APIs related to locating a user based
on provided data.
""" |
def remove_duplicated(uris):
temp = []
result = []
for uri in uris:
if uri not in temp:
result.append(uri)
temp.append(uri)
return result
uris = ['1234', '2222', '2222', '1234', '323232', '1234', '1234', 'dfddf', 'dfddf', '2222', '2323']
uris = remove_duplicated(uris)
print(... | def remove_duplicated(uris):
temp = []
result = []
for uri in uris:
if uri not in temp:
result.append(uri)
temp.append(uri)
return result
uris = ['1234', '2222', '2222', '1234', '323232', '1234', '1234', 'dfddf', 'dfddf', '2222', '2323']
uris = remove_duplicated(uris)
print(u... |
"""Package for db repository.
"""
class Repository(object):
"""Abstract repository class.
"""
def fingerprint_count(self):
pass
def property_count(self, property_name, property_value):
pass
def save_fingerprint(self, fingerprint):
pass
def identical... | """Package for db repository.
"""
class Repository(object):
"""Abstract repository class.
"""
def fingerprint_count(self):
pass
def property_count(self, property_name, property_value):
pass
def save_fingerprint(self, fingerprint):
pass
def identical_count(self, fing... |
class StateFieldRegistry:
def __init__(self):
self.fields = {}
""" Set a single value in the SFR. """
def set(self, key: str, value):
self.fields[key] = value
""" Returns None if [key] is not in SFR """
def get(self, key: str):
return self.fields.get(key)
""" SFR as ... | class Statefieldregistry:
def __init__(self):
self.fields = {}
' Set a single value in the SFR. '
def set(self, key: str, value):
self.fields[key] = value
' Returns None if [key] is not in SFR '
def get(self, key: str):
return self.fields.get(key)
' SFR as a dictionary... |
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... | """THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
N, P = map(int, input().split())
D = list(map(int, input().split()))
L = [0] * N
F = 1
for I in range(N - 1, -1, -1):
if P % D[I] ... | """
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
(n, p) = map(int, input().split())
d = list(map(int, input().split()))
l = [0] * N
f = 1
for i in range(N - 1, -1, -1):
if P % D[I] != 0:
L[I] = P // D[I] + 1
print('YE... |
class TokenMetaClass(type):
@classmethod
def __prepare__(metaCls, name, bases):
cls = super().__prepare__(metaCls, name, bases)
cls["__slots__"] = ()
return cls
def __contains__(self, item: "Token") -> bool:
return self is type(item)
class Token(metaclass=TokenMetaClass):... | class Tokenmetaclass(type):
@classmethod
def __prepare__(metaCls, name, bases):
cls = super().__prepare__(metaCls, name, bases)
cls['__slots__'] = ()
return cls
def __contains__(self, item: 'Token') -> bool:
return self is type(item)
class Token(metaclass=TokenMetaClass):
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
c=0
... | class Solution(object):
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
c = 0
head = tail = list_node(0)
while l1 != None or l2 != None or c != 0:
tail.next = list_node(0)
tail ... |
# -*- coding: utf-8 -*-
class TemperatureConversionClass(object):
def __init__(self , Choice):
self.Choice = Choice
while True:
Degree = int(input('Enter the value to convert : '))
if self.Choice == 'CF':
print('{} F' , self.celsius_to_fahrenheit(Degr... | class Temperatureconversionclass(object):
def __init__(self, Choice):
self.Choice = Choice
while True:
degree = int(input('Enter the value to convert : '))
if self.Choice == 'CF':
print('{} F', self.celsius_to_fahrenheit(Degree))
break
... |
VERSION_MAJOR = "0"
VERSION_MINOR = "5"
VERSION_TINY = "0"
VERSION = "%s.%s.%s" % (VERSION_MAJOR, VERSION_MINOR, VERSION_TINY)
| version_major = '0'
version_minor = '5'
version_tiny = '0'
version = '%s.%s.%s' % (VERSION_MAJOR, VERSION_MINOR, VERSION_TINY) |
for i in range(1,100):
if i % 15 == 0:
print("FizzBuzz,", end=' ')
elif i%3==0:
print("Fizz,", end=" ")
elif i%5==0:
print("Buzz,",end=' ')
else:
print(i,",",end=" ")
print(100) | for i in range(1, 100):
if i % 15 == 0:
print('FizzBuzz,', end=' ')
elif i % 3 == 0:
print('Fizz,', end=' ')
elif i % 5 == 0:
print('Buzz,', end=' ')
else:
print(i, ',', end=' ')
print(100) |
'''
Created on Aug 29, 2015
@author: kevinchien
'''
CACHED_PREFIX_USER = 'user'
CACHED_PREFIX_AUTH = 'auth'
CACHED_PREFIX_PROFILE = 'profile'
CACHED_PREFIX_SERVC = 'servc'
| """
Created on Aug 29, 2015
@author: kevinchien
"""
cached_prefix_user = 'user'
cached_prefix_auth = 'auth'
cached_prefix_profile = 'profile'
cached_prefix_servc = 'servc' |
#
# PySNMP MIB module VIDEOFRAME-SIGMON-VM0010-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VIDEOFRAME-SIGMON-VM0010-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:34:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
"""
https://leetcode.com/problems/maximum-subarray/
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
sum = nums[0]
current_max = nums[0]
for index in rang... | """
https://leetcode.com/problems/maximum-subarray/
"""
class Solution(object):
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
sum = nums[0]
current_max = nums[0]
for index in ra... |
input_file = 'input.txt'
def process_input():
with open(input_file) as f:
content = f.readlines()
# stripping whitespace
stripped = [x.strip() for x in content]
return stripped
def line_set_op(elements, op):
# for each 'group' (separated by double whitespace),
# creates a character set for each lin... | input_file = 'input.txt'
def process_input():
with open(input_file) as f:
content = f.readlines()
stripped = [x.strip() for x in content]
return stripped
def line_set_op(elements, op):
join_and_collapse = []
buffer = []
for line in elements:
if not line:
join_and_co... |
class CyclesVisibilitySettings:
camera = None
diffuse = None
glossy = None
scatter = None
shadow = None
transmission = None
| class Cyclesvisibilitysettings:
camera = None
diffuse = None
glossy = None
scatter = None
shadow = None
transmission = None |
#! python3
print("Task 9.1")
class Restaurant():
"""Class about opening restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type.title()
def describe_restaurant(self):
print(f'My restaurant is ... | print('Task 9.1')
class Restaurant:
"""Class about opening restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type.title()
def describe_restaurant(self):
print(f'My restaurant is {self.restaur... |
#!/usr/bin/env python3
with open('day23-input.txt') as f:
day23_input_lines = f.read().split("\n")
def parse_instructions(lines):
return [line.replace(",", "").split() for line in lines]
def run_instructions(instructions, registers):
addr = 0
while addr < len(instructions):
line = instructi... | with open('day23-input.txt') as f:
day23_input_lines = f.read().split('\n')
def parse_instructions(lines):
return [line.replace(',', '').split() for line in lines]
def run_instructions(instructions, registers):
addr = 0
while addr < len(instructions):
line = instructions[addr]
instr = ... |
"""
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
"""
# 2018-6-27
# Maximal Rectangel
# Build on the last question
... | """
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
"""
class Solution:
def maximal_rectangle(self, matrix):
... |
# -*- encoding: utf-8 -*-
"""
@File Name : python_class_test.py
@Create Time : 2022/2/21 11:50
@Description :
@Version :
@License : MIT
@Author : diklios
@Contact Email : diklios5768@gmail.com
@Github : https://github.com/diklios5768
@Blog :
@... | """
@File Name : python_class_test.py
@Create Time : 2022/2/21 11:50
@Description :
@Version :
@License : MIT
@Author : diklios
@Contact Email : diklios5768@gmail.com
@Github : https://github.com/diklios5768
@Blog :
@Motto : All our... |
"A file to test providers not defined in the same file."
DepProviderInfo = provider(
doc = "This provider does something.",
)
| """A file to test providers not defined in the same file."""
dep_provider_info = provider(doc='This provider does something.') |
prefix = "++" # The bot's prefix; default is ++, can be changed
token = "" # The bot's token, create an application at discord.com/developers
osu_key = "" # osu! API key, create one at osu.ppy.sh/p/api
| prefix = '++'
token = ''
osu_key = '' |
"""
66. Plus One
Easy
2313
3185
Add to List
Share
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assum... | """
66. Plus One
Easy
2313
3185
Add to List
Share
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assum... |
# coding=utf-8
# created by Ge Zhang @ Mar 25, 2020
# filters for graph(code snippets)
KEY_LIBS = ['statsmodels', 'gensim', 'keras',
'sklearn', 'xgboost', 'scipy', 'pandas']
def key_lib(graph):
funcs = graph['funcs']
heads = [f.split('.')[0] for f in funcs]
if any([h in KEY_LIBS for h in head... | key_libs = ['statsmodels', 'gensim', 'keras', 'sklearn', 'xgboost', 'scipy', 'pandas']
def key_lib(graph):
funcs = graph['funcs']
heads = [f.split('.')[0] for f in funcs]
if any([h in KEY_LIBS for h in heads]):
return True
return False |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Hewlett Packard Enterprise Development LP
#
# 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
#
# U... | manifest = {'Name': 'ospfv2_packet_mismatch_monitor', 'Description': 'OSPFv2 Packet Mismatch', 'Version': '1.0', 'Author': 'Aruba Networks'}
parameter_definitions = {'vrf_name': {'Name': 'Vrf Name', 'Description': 'Vrf to be Monitor', 'Type': 'String', 'Default': 'default'}, 'ospf_process_id': {'Name': 'OSPFv2 process ... |
"""Custom exception class for handling extra arguments."""
class SAMLAuthError(Exception):
extra = None
def __init__(self, msg, extra=None):
self.message = msg
self.extra = extra
| """Custom exception class for handling extra arguments."""
class Samlautherror(Exception):
extra = None
def __init__(self, msg, extra=None):
self.message = msg
self.extra = extra |
class Config:
URLS = [
'https://learning.oreilly.com/videos/ios-augmented-reality/9781788479332',
'https://learning.oreilly.com/videos/the-complete-arkit/9781789958775',
'https://learning.oreilly.com/videos/ios-12-and/100000006A0477/',
]
DOMAIN = ''
OUTPUT_FOLDER = './Downloa... | class Config:
urls = ['https://learning.oreilly.com/videos/ios-augmented-reality/9781788479332', 'https://learning.oreilly.com/videos/the-complete-arkit/9781789958775', 'https://learning.oreilly.com/videos/ios-12-and/100000006A0477/']
domain = ''
output_folder = './Downloader'
username = 'you@email.com'... |
#
# PySNMP MIB module SDLC-OPT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SDLC-OPT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:01:34 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,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
class Email():
# Simple object to hold email data
def __init__(self):
self.sender_name = ""
self.sender_email = ""
self.receiver_name = ""
self.receiver_email = ""
self.date = ""
self.time = ""
self.datetime_hotmail_format = ""
self.subject = "... | class Email:
def __init__(self):
self.sender_name = ''
self.sender_email = ''
self.receiver_name = ''
self.receiver_email = ''
self.date = ''
self.time = ''
self.datetime_hotmail_format = ''
self.subject = ''
self.body = ''
def __str__(se... |
BUFFER_SIZE = 1 << 10
def get_str(bytes):
try:
return bytes.decode()
except:
return bytes
def read_all(stream):
stream.seek(0)
parts = []
while True:
part = stream.read(BUFFER_SIZE)
if not part:
break
parts.append(part)
... | buffer_size = 1 << 10
def get_str(bytes):
try:
return bytes.decode()
except:
return bytes
def read_all(stream):
stream.seek(0)
parts = []
while True:
part = stream.read(BUFFER_SIZE)
if not part:
break
parts.append(part)
return ''.join((get_st... |
def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
nlist = [int(x) for x in input("Enter element to sort: ").split()]
bubbleSort(... | def bubble_sort(nlist):
for passnum in range(len(nlist) - 1, 0, -1):
for i in range(passnum):
if nlist[i] > nlist[i + 1]:
temp = nlist[i]
nlist[i] = nlist[i + 1]
nlist[i + 1] = temp
nlist = [int(x) for x in input('Enter element to sort: ').split()]... |
def serialize_sqla(data, serialize_date=True):
"""
Serialiation function to serialize any dicts or lists.
This is needed for conversion of sqlalchemy objects to JSON format.
"""
# If has to_dict this is asumed working and it is used
if hasattr(data, 'to_dict'):
return data.to_dict(seria... | def serialize_sqla(data, serialize_date=True):
"""
Serialiation function to serialize any dicts or lists.
This is needed for conversion of sqlalchemy objects to JSON format.
"""
if hasattr(data, 'to_dict'):
return data.to_dict(serialize_date=serialize_date)
if hasattr(data, 'isoformat')... |
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
nums[::2], nums[1::2] = nums[:n], nums[n:]
return nums
| class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
(nums[::2], nums[1::2]) = (nums[:n], nums[n:])
return nums |
"""
Validate the given sudoku solution.
https://www.codewars.com/kata/sudoku-solution-validator/python
"""
def validSolution(board):
"""Check if the given board is a valid sudoku solution. Expects an input as a list of rows."""
# Create sets with expected values
rows = [set(range(1, 10)) for _ in range(0,... | """
Validate the given sudoku solution.
https://www.codewars.com/kata/sudoku-solution-validator/python
"""
def valid_solution(board):
"""Check if the given board is a valid sudoku solution. Expects an input as a list of rows."""
rows = [set(range(1, 10)) for _ in range(0, 9)]
cols = [set(range(1, 10)) for ... |
__author__ = 'Shane'
class CSSFile:
def __init__(self, src):
self.src = src
self.classes = []
def addClass(self, cssClass):
self.classes.append(cssClass)
def render(self):
fileString = ""
for each in self.classes:
fileString += each.render() + "\n"
return fileString | __author__ = 'Shane'
class Cssfile:
def __init__(self, src):
self.src = src
self.classes = []
def add_class(self, cssClass):
self.classes.append(cssClass)
def render(self):
file_string = ''
for each in self.classes:
file_string += each.render() + '\n'
... |
# 22002 | Sandwich for Breakfast (Evan intro)
sm.setSpeakerID(1013101)
sm.sendNext("Did you feed Bulldog? You should have some breakfast now then, Evan. Today's breakfast is Handmade Sandwich. I've brought it with me. Hee hee. I was going to eat it myself if you didn't agree to feed Bulldog")
if sm.sendAskYesNo("Here... | sm.setSpeakerID(1013101)
sm.sendNext("Did you feed Bulldog? You should have some breakfast now then, Evan. Today's breakfast is Handmade Sandwich. I've brought it with me. Hee hee. I was going to eat it myself if you didn't agree to feed Bulldog")
if sm.sendAskYesNo("Here, I'll give you this #bSandwich#k, so #bgo talk ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2020 Colton Hughes <colton.hughes@firemon.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limi... | ansible_metadata = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.0'}
documentation = '\n---\nmodule: win_move_user\nversion_added: "2.9.10"\nshort_description: Moves AD User objects between OUs and CNs\ndescription:\n - The module win_move_user moves Active Directory User objects betwee... |
#
# PySNMP MIB module TRAPEZE-NETWORKS-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.