content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""Binary Tree level order traversal 2"""
class Node:
def __init__(self, id):
self.id = id
self.left = None
self.right = None
def __repr__(self):
return f'Node: {self.id}'
def build_bin_tree(root):
if not root:
return
queue = []
queue.append(root)
... | """Binary Tree level order traversal 2"""
class Node:
def __init__(self, id):
self.id = id
self.left = None
self.right = None
def __repr__(self):
return f'Node: {self.id}'
def build_bin_tree(root):
if not root:
return
queue = []
queue.append(root)
bin... |
#help(object)
#the object will be the built-in functions
#it returns the object details clearly
print(help('print'))
| print(help('print')) |
#
# PySNMP MIB module AI198CLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AI198CLC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:57 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, single_value_constraint, value_size_constraint) ... |
def lineplot(x_data, y_data, x_label="", y_label="", title=""):
# Create the plot object
_, ax = plt.subplots()
# Plot the best fit line, set the linewidth (lw), color and
# transparency (alpha) of the line
ax.plot(x_data, y_data, lw = 2, color = '#539caf', alpha = 1)
# Label the axes and prov... | def lineplot(x_data, y_data, x_label='', y_label='', title=''):
(_, ax) = plt.subplots()
ax.plot(x_data, y_data, lw=2, color='#539caf', alpha=1)
ax.set_title(title)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label) |
# https://app.codesignal.com/arcade/intro/level-2/2mxbGwLzvkTCKAJMG
def almostIncreasingSequence(sequence):
out_of_place = 0
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
out_of_place += 1
if i+2 < len(sequence) and sequence[i] >= sequence[i + 2]:
... | def almost_increasing_sequence(sequence):
out_of_place = 0
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
out_of_place += 1
if i + 2 < len(sequence) and sequence[i] >= sequence[i + 2]:
out_of_place += 1
return c < 3 |
"""OAuth 2.0 WSGI server middleware providing MyProxy certificates as access tokens
"""
__author__ = "R B Wilkinson"
__date__ = "12/12/11"
__copyright__ = "(C) 2011 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__revisi... | """OAuth 2.0 WSGI server middleware providing MyProxy certificates as access tokens
"""
__author__ = 'R B Wilkinson'
__date__ = '12/12/11'
__copyright__ = '(C) 2011 Science and Technology Facilities Council'
__license__ = 'BSD - see LICENSE file in top-level directory'
__contact__ = 'Philip.Kershaw@stfc.ac.uk'
__revisi... |
class ContentIsEmpty(Exception):
def __str__(self) -> str:
return "No string was passed for content. You must add a text content to a DiscordResponse"
def __repr__(self) -> str:
return "No string was passed for content. You must add a text content to a DiscordResponse"
class InvalidDiscordRes... | class Contentisempty(Exception):
def __str__(self) -> str:
return 'No string was passed for content. You must add a text content to a DiscordResponse'
def __repr__(self) -> str:
return 'No string was passed for content. You must add a text content to a DiscordResponse'
class Invaliddiscordres... |
'''bytes and bytearray both do not supports slicing and repitition'''
# Convert a List to bytes
lst = [1,2,3,234] # bytes cannot be more than '255'
print(lst)
print(type(lst))
b = bytes(lst) # Converting a List to create bytes
print(b) # OutPut: b'\x01\x02\x03\xea'
print(type(b)) ... | """bytes and bytearray both do not supports slicing and repitition"""
lst = [1, 2, 3, 234]
print(lst)
print(type(lst))
b = bytes(lst)
print(b)
print(type(b))
print(len(b))
b1 = bytearray(lst)
print(b1)
print(type(b1))
b1[3] = 22
print(b1)
print(len(b1)) |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Recursive approach using merge sort. Time O(nlogn). Space O(n) since it's recursive approach. To make it iterative, implement the merge sort iteratively
class Solution(object... | class Solution(object):
def sort_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
(fast_node, slow_node) = (head.next, head)
while fastNode and fastNode.next:
fast_node = fastNod... |
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
sampleDict['location'] = sampleDict.pop('city')
print(sampleDict) | sample_dict = {'name': 'Kelly', 'age': 25, 'salary': 8000, 'city': 'New york'}
sampleDict['location'] = sampleDict.pop('city')
print(sampleDict) |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
x, y = [], []
for i in s:
x.append(s.index(i))
for i in t:
y.append(t.index(i))
if x == y:
return True
return False
| class Solution:
def is_isomorphic(self, s: str, t: str) -> bool:
(x, y) = ([], [])
for i in s:
x.append(s.index(i))
for i in t:
y.append(t.index(i))
if x == y:
return True
return False |
def is_paired(input_string):
stack = []
for char in input_string:
if char in "{([":
stack += [char]
elif(char == "}"):
if (stack[-1:] == ["{"]):
stack.pop()
else:
return False
elif(char == ")"):
if (stack[-1:] == ["("]):
stack.pop()
else:
return False
elif(char == "]"):
if (s... | def is_paired(input_string):
stack = []
for char in input_string:
if char in '{([':
stack += [char]
elif char == '}':
if stack[-1:] == ['{']:
stack.pop()
else:
return False
elif char == ')':
if stack[-1:] == ... |
def test_top_tv_should_contain_100_entries(ia):
chart = ia.get_top250_tv()
assert len(chart) == 250
def test_top_tv_entries_should_have_rank(ia):
movies = ia.get_top250_tv()
for rank, movie in enumerate(movies):
assert movie['top tv 250 rank'] == rank + 1
def test_top_tv_entries_should_have_... | def test_top_tv_should_contain_100_entries(ia):
chart = ia.get_top250_tv()
assert len(chart) == 250
def test_top_tv_entries_should_have_rank(ia):
movies = ia.get_top250_tv()
for (rank, movie) in enumerate(movies):
assert movie['top tv 250 rank'] == rank + 1
def test_top_tv_entries_should_have_... |
# https://www.hearthpwn.com/news/8230-mysteries-of-the-phoenix-druid-and-hunter-puzzles
# Baloon_Merchant 0
# Armor_Vender 1
# Barrens_Blacksmith 2
# Darkshire_Alchemist 3
# Shady_dealer 4
# Master_Swordsmith 5
# Drakkari_Enchanter 6
# dalaran_mage 7
# bloodsail_corsair 8
# violet_apprentice 9
# silver_hand_knight 10
... | goods_action_list = [(0, 5), (0, 1), (6, 3), (2, 0), (12, 10), (0, 5), (0, 1), (6, 3), (2, 9), (0, 5)]
action_list = [5, 1, 3, 0, 10, 5, 1, 3, 9, 5, 3, 2, 8, 11, 1, 6, 13, 1, 3, 12, 6, 8, 1, 6, 1, 4, 11, 4, 3, 2, 1, 13, 3, 11, 3, 5, 5, 1, 10, 2, 5, 7, 2, 5, 8, 1, 3, 13, 1, 3, 6, 10, 0, 1, 12, 5, 0, 4, 7, 0, 1, 3, 11, 5... |
# 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 writing, software
# distributed under t... | detect_system3_result = [('system', 'product', 'serial', 'Empty'), ('system', 'product', 'name', 'S2915'), ('system', 'product', 'vendor', 'Tyan Computer Corporation'), ('system', 'product', 'version', 'REFERENCE'), ('system', 'product', 'uuid', '83462C81-52BA-11CB-870F'), ('system', 'motherboard', 'name', 'S2915'), ('... |
case_1 = """somevar = 4
anotherVar = 5
def function(a, b):
some function
some very small function
which will
be considered good;
function(4, 5)"""
case_2 = """somevar = 4
anotherVar = 5
def func... | case_1 = 'somevar = 4\n anotherVar = 5\n def function(a, b):\n some function\n some very small function\n which will\n be considered good;\n function(4, 5)'
case_2 = 'somevar = 4\n anotherVar = 5\n def fun... |
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
perimeter = 0
A.sort(reverse=True)
for k in range(len(A)-2):
if self.fun(A[k], A[k+1], A[k+2]):
perimeter = max(perimeter, A[k] + A[k+1] + A[k+2])
return perimeter
return peri... | class Solution:
def largest_perimeter(self, A: List[int]) -> int:
perimeter = 0
A.sort(reverse=True)
for k in range(len(A) - 2):
if self.fun(A[k], A[k + 1], A[k + 2]):
perimeter = max(perimeter, A[k] + A[k + 1] + A[k + 2])
return perimeter
... |
'''
It is important to have some understanding of what commonly-used functions are doing under the hood. Though you may already know how to compute variances, this is a beginner course that does not assume so. In this exercise, we will explicitly compute the variance of the petal length of Iris veriscolor using the equ... | """
It is important to have some understanding of what commonly-used functions are doing under the hood. Though you may already know how to compute variances, this is a beginner course that does not assume so. In this exercise, we will explicitly compute the variance of the petal length of Iris veriscolor using the equ... |
class Singleton:
ans = None
@staticmethod
def instance():
if '_instance' not in Singleton.__dict__:
Singleton._instance = Singleton()
return Singleton._instance
s1 = Singleton.instance()
s2 = Singleton.instance()
s1.ans = 10
assert s1 is s2
assert s1.ans == s2.ans
print("Test Passed")
| class Singleton:
ans = None
@staticmethod
def instance():
if '_instance' not in Singleton.__dict__:
Singleton._instance = singleton()
return Singleton._instance
s1 = Singleton.instance()
s2 = Singleton.instance()
s1.ans = 10
assert s1 is s2
assert s1.ans == s2.ans
print('Test Pa... |
"""
Created on Fri Nov 12 12:28:01 2021
@author: DW
"""
class ORR_Tafel:
"""Class for calculating Tafel plots of the ORR scans"""
def __init__():
pass
def export(
ORR_dest_dir,
rTFxy,
i,
TFll,
dest_file,
TFfit,
): # noqa : F821
TafelD... | """
Created on Fri Nov 12 12:28:01 2021
@author: DW
"""
class Orr_Tafel:
"""Class for calculating Tafel plots of the ORR scans"""
def __init__():
pass
def export(ORR_dest_dir, rTFxy, i, TFll, dest_file, TFfit):
tafel_dir = ORR_dest_dir.joinpath('TAFEL')
TafelDir.mkdir(parents=Tru... |
class Game:
def __init__(self, id):
# initially player 1's move is false
self.p1Went = False
# initially player 2's move is false
self.p2Went = False
self.ready = False
# current game's id
self.id = id
# two players move, initially none[player1's move,... | class Game:
def __init__(self, id):
self.p1Went = False
self.p2Went = False
self.ready = False
self.id = id
self.moves = [None, None]
self.wins = [0, 0]
self.ties = 0
def get_player_move(self, p):
return self.moves[p]
def play(self, player, ... |
########################## THE TOON LAND PROJECT ##########################
# Filename: _BarkingBoulevard.py
# Created by: Cody/Fd Green Cat Fd (February 19th, 2013)
####
# Description:
#
# The Barking Boulevard added Python implementation.
####
filepath = __filebase__ + '/toonland/playground/funnyfarm/maps/%s'
sidewa... | filepath = __filebase__ + '/toonland/playground/funnyfarm/maps/%s'
sidewalk_texture = loader.loadTexture(filepath % 'sidewalkyellow.jpg')
for tunnel_node in render.findAllMatches('**/linktunnel*'):
tunnelNode.find('**/tunnel_floor*').setTexture(sidewalkTexture, 1)
toon_hq = render.find('**/tb42:toon_landmark_hqFF_D... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = None
if isinstance(data, list) and len(data) > 0:
self.data = data.pop(0)
for item in data:
self.AddNode(item)
else:
self.data = data
... | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = None
if isinstance(data, list) and len(data) > 0:
self.data = data.pop(0)
for item in data:
self.AddNode(item)
else:
self.data = data
... |
"""
Copyright 2020 The Secure, Reliable, and Intelligent Systems Lab, ETH Zurich
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 appl... | """
Copyright 2020 The Secure, Reliable, and Intelligent Systems Lab, ETH Zurich
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 appl... |
total_amount = float(input('Enter Groupon payment amount: '))
tickets = round((total_amount * 0.5875), 2) # 58.75% for ticket sales
concessions = round((total_amount * 0.4125), 2) # 41.25% for concession sales
print()
print(f'GL 4005: {tickets}')
print(f'GL 4200: {concessions}')
input('Press enter to exit: ') # ke... | total_amount = float(input('Enter Groupon payment amount: '))
tickets = round(total_amount * 0.5875, 2)
concessions = round(total_amount * 0.4125, 2)
print()
print(f'GL 4005: {tickets}')
print(f'GL 4200: {concessions}')
input('Press enter to exit: ') |
# ECE 486 Project
# Ali Saad, Disha Shetty, Pooja
# Mips Simulation
# Professor Zeshan Chishti
# Open memory image file and read it(take it's inputs)
# Need to change the numbers in the file from Hex to binary
# Then parse it to get Rs, Rt, Rd intaking the correct numbers
# To run the correct operation ... | f = open('sample_memory_image.txt', 'r')
for x in f:
scale = 16
num_of_bits = 32
y = bin(int(x, scale))[2:].zfill(num_of_bits)
print(y)
" this is how you comment out a section\n# An idea of switch Statement for opcode after parsing \nopcode = {\n # Arithmetic Instructions\n '000000' : ADDRdRsRt,\n... |
"""
utilapi.
A Cloud Util api.
"""
__version__ = "0.1.0"
__author__ = 'Kishore'
__credits__ = 'Tealpod' | """
utilapi.
A Cloud Util api.
"""
__version__ = '0.1.0'
__author__ = 'Kishore'
__credits__ = 'Tealpod' |
#!/bin/python3
# -*- coding: utf-8 -*-
"""
Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in
the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def cou... | """
Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in
the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def count_bits(n):
return '{0:b}'.format(n).... |
start = int(input('Choose the start of the Aritimetic Progression: '))
rate = int(input('Choose the rate of the Aritimetic Progression: '))
cont = 10
while cont != 0:
print(start)
start = start + rate
cont = cont - 1
| start = int(input('Choose the start of the Aritimetic Progression: '))
rate = int(input('Choose the rate of the Aritimetic Progression: '))
cont = 10
while cont != 0:
print(start)
start = start + rate
cont = cont - 1 |
# This program is about Quick Sort
# an advanced version of Bubble Sort
# Time complexity is O(nlog(n))
# Version 1
class SQList:
def __init__(self, lis=None):
self.r = lis
# define a method to exchange elements
def swap(self, i, j):
temp = self.r[i]
self.r[i] = self.r[j]
... | class Sqlist:
def __init__(self, lis=None):
self.r = lis
def swap(self, i, j):
temp = self.r[i]
self.r[i] = self.r[j]
self.r[j] = temp
def quick_sort(self):
self.qsort(0, len(self.r) - 1)
def qsort(self, low, high):
if low < high:
pivot = s... |
"""
Description: Functions that handle country codes and country names.
"""
__author__ = ["Karolina Pantazatou"]
__credits__ = "ICOS Carbon Portal"
__license__ = "GPL-3.0"
__version__ = "0.1.0"
__maintainer__ = "ICOS Carbon Portal, elaborated products team"
__email__ = ['info@icos-cp.eu', ... | """
Description: Functions that handle country codes and country names.
"""
__author__ = ['Karolina Pantazatou']
__credits__ = 'ICOS Carbon Portal'
__license__ = 'GPL-3.0'
__version__ = '0.1.0'
__maintainer__ = 'ICOS Carbon Portal, elaborated products team'
__email__ = ['info@icos-cp.eu', 'karolina.pantazatou@nate... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"api_key": "apiKey",
"api_version": "apiVersion",
"binding_from": "bindingFrom",
"config_map_key_ref": "configMapKeyRef... | snake_to_camel_case_table = {'api_key': 'apiKey', 'api_version': 'apiVersion', 'binding_from': 'bindingFrom', 'config_map_key_ref': 'configMapKeyRef', 'kafka_admin_url': 'kafkaAdminUrl', 'num_partitions': 'numPartitions', 'replication_factor': 'replicationFactor', 'secret_key_ref': 'secretKeyRef', 'topic_name': 'topicN... |
'''
File: 1038.py
File Created: 2021-01-12 13:43:24 -08:00
Author: Taowyoo (caoyxsh@outlook.com)
Brief: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
-----
Last Modified: 2021-01-12 13:43:57 -08:00
Modified By: Taowyoo (caoyxsh@outlook.com>)
-----
Copyright 2020 - 2021
'''
# Definition for a ... | """
File: 1038.py
File Created: 2021-01-12 13:43:24 -08:00
Author: Taowyoo (caoyxsh@outlook.com)
Brief: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
-----
Last Modified: 2021-01-12 13:43:57 -08:00
Modified By: Taowyoo (caoyxsh@outlook.com>)
-----
Copyright 2020 - 2021
"""
class Solution:
... |
def fibonacci_iterative(n):
a = 0
b = 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(0, n - 1):
c = a + b
a = b
b = c
return b
for i in range(0, 20):
print(fibonacci_iterative(i))
| def fibonacci_iterative(n):
a = 0
b = 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(0, n - 1):
c = a + b
a = b
b = c
return b
for i in range(0, 20):
print(fibonacci_iterative(i)) |
#
# PySNMP MIB module PW-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PW-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
numbers=[0, 1, 153, 370, 371, 407]
def is_sum_of_cubes(s):
res=[]
temp=""
for i in s:
if i.isdigit():
temp+=i
else:
res.extend([temp[i:i+3] for i in range(0, len(temp), 3) if int(temp[i:i+3]) in numbers])
temp=""
res.extend([temp[i:i+3] for i in range(... | numbers = [0, 1, 153, 370, 371, 407]
def is_sum_of_cubes(s):
res = []
temp = ''
for i in s:
if i.isdigit():
temp += i
else:
res.extend([temp[i:i + 3] for i in range(0, len(temp), 3) if int(temp[i:i + 3]) in numbers])
temp = ''
res.extend([temp[i:i + 3... |
###############################################
# Main UI component sizes
###############################################
COLS = 6
ROWS = 6
CELL_WIDTH = 50
CELL_HEIGHT = CELL_WIDTH
TOTAL_DICE = 7
WINDOW_WIDTH = CELL_WIDTH * TOTAL_DICE
ROLL_DICE_LABEL_WIDTH = WINDOW_WIDTH
ROLL_DICE_LABEL_HEIGHT = CELL_HEIGHT
DICE_... | cols = 6
rows = 6
cell_width = 50
cell_height = CELL_WIDTH
total_dice = 7
window_width = CELL_WIDTH * TOTAL_DICE
roll_dice_label_width = WINDOW_WIDTH
roll_dice_label_height = CELL_HEIGHT
dice_strip_top = ROLL_DICE_LABEL_HEIGHT
dice_strip_width = WINDOW_WIDTH
dice_strip_height = CELL_HEIGHT
col_label_strip_top = DICE_ST... |
class FrontMiddleBackQueue:
def __init__(self):
self.f = deque()
self.b = deque()
def pushFront(self, val: int) -> None:
self.f.appendleft(val)
self._balance()
def pushMiddle(self, val: int) -> None:
if len(self.f) > len(self.b):
self.b.appendleft(self.... | class Frontmiddlebackqueue:
def __init__(self):
self.f = deque()
self.b = deque()
def push_front(self, val: int) -> None:
self.f.appendleft(val)
self._balance()
def push_middle(self, val: int) -> None:
if len(self.f) > len(self.b):
self.b.appendleft(sel... |
class Contact:
def __init__(self, firstname, middlename, address, mobile, lastname, nickname, title, company, home_phone_number,
work_phone_number, fax_number, email_1,
email_2, email_3, bday, bmonth, byear, aday, amonth, ayear, address_2, phone_2, notes):
self.firstname =... | class Contact:
def __init__(self, firstname, middlename, address, mobile, lastname, nickname, title, company, home_phone_number, work_phone_number, fax_number, email_1, email_2, email_3, bday, bmonth, byear, aday, amonth, ayear, address_2, phone_2, notes):
self.firstname = firstname
self.middlename... |
n = int(input())
res = 1
f = 1
for i in range(1, n + 1):
f *= i
res += 1 / f
print(res) | n = int(input())
res = 1
f = 1
for i in range(1, n + 1):
f *= i
res += 1 / f
print(res) |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def print_tree(self):
if self.left:
self.left.print_tree()
print(self.data),
if self.right:
self.right.print_tree()
def min_num(node):
current... | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def print_tree(self):
if self.left:
self.left.print_tree()
(print(self.data),)
if self.right:
self.right.print_tree()
def min_num(node):
curren... |
class EdgeData(object):
"""Class used to store edge settings.
Attributes
----------
type: str
Shape of edge: 'Triangular', 'Rectangular', 'Custom, 'User Q'
distance_m: float
Distance to shore, in m.
cust_coef: float
Custom coefficient provided by user.
number_ensembl... | class Edgedata(object):
"""Class used to store edge settings.
Attributes
----------
type: str
Shape of edge: 'Triangular', 'Rectangular', 'Custom, 'User Q'
distance_m: float
Distance to shore, in m.
cust_coef: float
Custom coefficient provided by user.
number_ensembl... |
# -*- coding: utf-8 -*-
"""
author :: @adityac8
"""
## SET PATHS ACCORDING TO WHERE DATA SHOULD BE STORED
# This is where all audio files reside and features will be extracted
audio_ftr_path='D:/workspace/aditya_akshita/temp/dcase_data'
# We now tell the paths for audio, features and texts.
wav_dev_fd = audio_ftr_p... | """
author :: @adityac8
"""
audio_ftr_path = 'D:/workspace/aditya_akshita/temp/dcase_data'
wav_dev_fd = audio_ftr_path + '/audio/dev'
wav_eva_fd = audio_ftr_path + '/audio/eva'
dev_fd = audio_ftr_path + '/features/dev'
eva_fd = audio_ftr_path + '/features/eva'
label_csv = '../../dependencies/keras_aud/utils/dcase16_tas... |
# pylint: skip-file
# flake8: noqa
def main():
'''
ansible oc module for project
'''
module = AnsibleModule(
argument_spec=dict(
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
state=dict(default='present', type='str',
... | def main():
"""
ansible oc module for project
"""
module = ansible_module(argument_spec=dict(kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), name=dict(def... |
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if root.left is None and root.right is None:
return root.val == sum
new_sum = sum - root.val
return self.hasPathSum(root.left, new_sum) or self.hasPathSum(root.ri... | class Solution:
def has_path_sum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if root.left is None and root.right is None:
return root.val == sum
new_sum = sum - root.val
return self.hasPathSum(root.left, new_sum) or self.hasPathSum(root... |
def diagonal_sum(n):
"""
Finds the diagonal sum of a spiral of n by n
An example:
>>> diagonal_sum(5)
101
:param n: Number of rows and columns of the grid
:type n int
:return: Total of the numbers along the diagonal
:rtype: int
"""
count = 1
last = 1
total = last
... | def diagonal_sum(n):
"""
Finds the diagonal sum of a spiral of n by n
An example:
>>> diagonal_sum(5)
101
:param n: Number of rows and columns of the grid
:type n int
:return: Total of the numbers along the diagonal
:rtype: int
"""
count = 1
last = 1
total = last
... |
# O(P + S)
class Solution(object):
def findAnagrams(self, s, p):
p_count, cur_count, result = [0]*26, [0]*26, []
for c in p:
p_count[self._char2ind(c)] += 1
p_len = len(p)
a_start = 0
for i, c in enumerate(s):
c_ind = self._char2ind(c)
... | class Solution(object):
def find_anagrams(self, s, p):
(p_count, cur_count, result) = ([0] * 26, [0] * 26, [])
for c in p:
p_count[self._char2ind(c)] += 1
p_len = len(p)
a_start = 0
for (i, c) in enumerate(s):
c_ind = self._char2ind(c)
if ... |
model_raw_data = [
{
"Field": "Description",
"model_id": "",
"host_strain": "",
"host_strain_full": "",
"engraftment_site": "",
"engraftment_type": "",
"sample_type": "",
"sample_state": "",
"passage_number": "",
"publications": ""
... | model_raw_data = [{'Field': 'Description', 'model_id': '', 'host_strain': '', 'host_strain_full': '', 'engraftment_site': '', 'engraftment_type': '', 'sample_type': '', 'sample_state': '', 'passage_number': '', 'publications': ''}, {'Field': 'Example', 'model_id': '', 'host_strain': '', 'host_strain_full': '', 'engraft... |
def convert_into_24hr(time_12hr):
if time_12hr[-2:] == "AM":
remove_am = time_12hr.replace('AM', '')
if time_12hr[:2] == "12":
x = remove_am.replace('12', '00')
return x
return remove_am
elif time_12hr[-2:] == "PM":
remove_pm = time_12hr.replace('PM', ''... | def convert_into_24hr(time_12hr):
if time_12hr[-2:] == 'AM':
remove_am = time_12hr.replace('AM', '')
if time_12hr[:2] == '12':
x = remove_am.replace('12', '00')
return x
return remove_am
elif time_12hr[-2:] == 'PM':
remove_pm = time_12hr.replace('PM', '')
... |
#https://www.lintcode.com/problem/wildcard-matching/description?_from=ladder&&fromId=1
class Solution:
"""
@param s: A string
@param p: A string includes "?" and "*"
@return: is Match?
"""
def isMatch(self, s, p):
# write your code here
memo = {}
return self.dfs(s, 0, p... | class Solution:
"""
@param s: A string
@param p: A string includes "?" and "*"
@return: is Match?
"""
def is_match(self, s, p):
memo = {}
return self.dfs(s, 0, p, 0, memo)
def dfs(self, s, sIndex, p, pIndex, memo):
if pIndex == len(p):
return sIndex == ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 2 00:59:53 2017
@author: azkei
"""
# | """
Created on Fri Jun 2 00:59:53 2017
@author: azkei
""" |
#Ex.14
num = int(input())
if num >= 0:
res = pow(num, 1/2)
else:
res = pow(num, 2)
print(res)
| num = int(input())
if num >= 0:
res = pow(num, 1 / 2)
else:
res = pow(num, 2)
print(res) |
# https://github.com/EricCharnesky/CIS2001-Winter2022/blob/main/Week5-StacksAndQueues/main.py
class Stack:
# O(1)
def __init__(self):
self._data = []
# O(1)
def push(self, item):
self._data.append(item)
# O(1)
def pop(self):
return self._data.pop()
# O(1)
de... | class Stack:
def __init__(self):
self._data = []
def push(self, item):
self._data.append(item)
def pop(self):
return self._data.pop()
def peek(self):
return self._data[len(self._data) - 1]
def is_empty(self):
return len(self._data) == 0
def __len__(s... |
class Hello:
def __init__(self):
self._message = 'Hello world!'
def get_message(self):
return self._message
def main(self):
message = self.get_message()
print(message)
Hello().main()
| class Hello:
def __init__(self):
self._message = 'Hello world!'
def get_message(self):
return self._message
def main(self):
message = self.get_message()
print(message)
hello().main() |
"""Heuristic demonstrating conversion of the PhoenixZIPReport from Siemens.
It only cares about converting a series with have PhoenixZIPReport in their
series_description and outputs **only to sourcedata**.
"""
def create_key(template, outtype=('nii.gz',), annotation_classes=None):
if template is None or not tem... | """Heuristic demonstrating conversion of the PhoenixZIPReport from Siemens.
It only cares about converting a series with have PhoenixZIPReport in their
series_description and outputs **only to sourcedata**.
"""
def create_key(template, outtype=('nii.gz',), annotation_classes=None):
if template is None or not temp... |
"""
Author: Tong
Time: --2021
"""
dataset_map = {"seq-clinc150": "c", "seq-maven": "m", "seq-webred": "w"}
def generate_cmd():
cmd_list = []
info_list = []
for dataset in ["seq-clinc150"]:
for ptm in ["bert"]:
info = "{description}_{var}_{var1}_{var2}".format(description="e10",... | """
Author: Tong
Time: --2021
"""
dataset_map = {'seq-clinc150': 'c', 'seq-maven': 'm', 'seq-webred': 'w'}
def generate_cmd():
cmd_list = []
info_list = []
for dataset in ['seq-clinc150']:
for ptm in ['bert']:
info = '{description}_{var}_{var1}_{var2}'.format(description='e10', var=da... |
"""pyavreceiver errors."""
class AVReceiverError(Exception):
"""Base class for library errors."""
class AVReceiverInvalidArgumentError(AVReceiverError):
"""Invalid argument error."""
class AVReceiverIncompatibleDeviceError(AVReceiverError):
"""Invalid argument error."""
class QosTooHigh(AVReceiverEr... | """pyavreceiver errors."""
class Avreceivererror(Exception):
"""Base class for library errors."""
class Avreceiverinvalidargumenterror(AVReceiverError):
"""Invalid argument error."""
class Avreceiverincompatibledeviceerror(AVReceiverError):
"""Invalid argument error."""
class Qostoohigh(AVReceiverError)... |
class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
n = len(indexes)
changes = []
for i in range(n):
idx = indexes[i]
source = sources[i]
target = targets[i]
m = len(source)
... | class Solution:
def find_replace_string(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
n = len(indexes)
changes = []
for i in range(n):
idx = indexes[i]
source = sources[i]
target = targets[i]
m = len(source)... |
#proof of concept
def set_logger(custom_log):
set_logger.__custom_logger = custom_log
def log(text):
set_logger.__custom_logger.log(text)
| def set_logger(custom_log):
set_logger.__custom_logger = custom_log
def log(text):
set_logger.__custom_logger.log(text) |
# Semigroup + identity property = Monoid
# The number 0 works well as an identity element for addition
print(2 + 0 == 2)
# Monoids don't have to be numbers | print(2 + 0 == 2) |
cx_db = 'plocal://localhost:2424/na_server'
cx_version = 'wild_type'
initial_drop = False
model_version = "Givon17"
| cx_db = 'plocal://localhost:2424/na_server'
cx_version = 'wild_type'
initial_drop = False
model_version = 'Givon17' |
deps = [
"pip", # install dependencies
"pyglet", # rendering engine
"pyjsparser", # javascript parser
]
| deps = ['pip', 'pyglet', 'pyjsparser'] |
for tt in range(int(input())):
n,m,k = map(int,input().split())
k1 = m-1 + m*(n-1)
if k1 == k:
print('YES')
else:
print('NO') | for tt in range(int(input())):
(n, m, k) = map(int, input().split())
k1 = m - 1 + m * (n - 1)
if k1 == k:
print('YES')
else:
print('NO') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_stack_n.py
# Create Date: 2015-07-26 10:53:38
# Usage: AC_stack_n.py
# Descripton:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = ... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def invert_tree(self, root):
stack = [root]
while stack:
node = stack.pop()
if node:
(node.left, node.right) = (node.right, no... |
def to_digits(n):
list = []
while n:
list.append(n%10)
n //= 10
list.reverse()
return list
def main():
print(to_digits(123))
# Expected output : [1, 2, 3]
print(to_digits(99999))
# Expected output : [9, 9, 9, 9, 9]
print(to_digits(123023))
# Expected output : [1, 2, 3, 0, 2, 3]
if __name__ == '__... | def to_digits(n):
list = []
while n:
list.append(n % 10)
n //= 10
list.reverse()
return list
def main():
print(to_digits(123))
print(to_digits(99999))
print(to_digits(123023))
if __name__ == '__main__':
main() |
#
# PySNMP MIB module LM-SENSORS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LM-SENSORS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:58:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
# https://cses.fi/problemset/task/1618
def zeros(n):
return 0 if n < 5 else zeros(n // 5) + n // 5
print(zeros(int(input())))
| def zeros(n):
return 0 if n < 5 else zeros(n // 5) + n // 5
print(zeros(int(input()))) |
class Solution:
"""
@param ages:
@return: nothing
"""
def numFriendRequests(self, ages):
counts = [0] * 121
presum = [0] * 121
for age in ages:
counts[age] += 1
for i in range(1, 121):
presum[i] = presum[i - 1] + counts[i]
... | class Solution:
"""
@param ages:
@return: nothing
"""
def num_friend_requests(self, ages):
counts = [0] * 121
presum = [0] * 121
for age in ages:
counts[age] += 1
for i in range(1, 121):
presum[i] = presum[i - 1] + counts[i]
total = 0... |
"""
test_tui_tools
--------------
Test module for testint TUI_tools
"""
#check_quest_info
#automatic_questioner
#get_default
#get_default3
#automatic_questioner3
#
#
#selection_list_options
#selection_options
#confirmation_question
#simple_input
#
#general_questioner
def test():
pass
| """
test_tui_tools
--------------
Test module for testint TUI_tools
"""
def test():
pass |
"""Constants for YT-MX0404V2 component."""
DOMAIN = "yt_mx0404v2"
DEFAULT_NAME = "YT-MX0404V2"
DEFAULT_PORT = 23
DEFAULT_RECONNECT_INTERVAL = 10
DEFAULT_POLLING_INTERVAL = 3
CONNECTION_TIMEOUT = 10
CONF_INPUTS1 = "input1"
CONF_INPUTS2 = "input2"
CONF_INPUTS3 = "input3"
CONF_INPUTS4 = "input4"
DEFAULT_INPUTS1 = "I... | """Constants for YT-MX0404V2 component."""
domain = 'yt_mx0404v2'
default_name = 'YT-MX0404V2'
default_port = 23
default_reconnect_interval = 10
default_polling_interval = 3
connection_timeout = 10
conf_inputs1 = 'input1'
conf_inputs2 = 'input2'
conf_inputs3 = 'input3'
conf_inputs4 = 'input4'
default_inputs1 = 'Input 1... |
#Title:-DiameterOfBinaryTree
#Explanation:-https://www.youtube.com/watch?v=v8U4Wi6ZwKE&list=PLmpbOouoNZaP5M275obyC44n3I3nCFk8Q&index=12
#Author : Tanay Chauli
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to find height of a tree
def height(root... | class Newnode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def height(root, ans):
if root == None:
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
ans[0] = max(ans[0], left_height + right_height)
return 1... |
class BallastControl:
def __init__(self, mass: float, center_of_mass: tuple, center_of_buoyancy: tuple):
# initialize syringe controls
self.constant_mass = mass
self.constant_COM = center_of_mass
self.constant_COB = center_of_buoyancy
| class Ballastcontrol:
def __init__(self, mass: float, center_of_mass: tuple, center_of_buoyancy: tuple):
self.constant_mass = mass
self.constant_COM = center_of_mass
self.constant_COB = center_of_buoyancy |
#
# PySNMP MIB module DRAFT-MSDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DRAFT-MSDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:54:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
# Simon McLain 208-03-11 Phython Tutorial 4.7.2
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
| def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print('if you put', voltage, 'volts through it.')
print('-- Lovely plumage, the', type)
print("-- It's", state, '!') |
n = int(input())
combinations = 0
for x1 in range(0, n + 1):
for x2 in range(0, n + 1):
for x3 in range(0, n + 1):
for x4 in range(0, n + 1):
for x5 in range(0, n + 1):
if x1 + x2 + x3 + x4 + x5 == n:
combinations += 1
print(combinati... | n = int(input())
combinations = 0
for x1 in range(0, n + 1):
for x2 in range(0, n + 1):
for x3 in range(0, n + 1):
for x4 in range(0, n + 1):
for x5 in range(0, n + 1):
if x1 + x2 + x3 + x4 + x5 == n:
combinations += 1
print(combination... |
PP_names = {1: 'H.pbe-rrkjus_psl.0.1.UPF', 2: 'He_ONCV_PBE-1.0.upf',
3: 'li_pbe_v1.4.uspp.F.UPF', 4: 'Be_ONCV_PBE-1.0.upf',
5: 'B.pbe-n-kjpaw_psl.0.1.UPF', 6: 'C_pbe_v1.2.uspp.F.UPF',
7: 'N.pbe.theos.UPF', 8: 'O.pbe-n-kjpaw_psl.0.1.UPF',
9: 'f_pbe_v1.4.uspp.F.UPF', 10: 'N... | pp_names = {1: 'H.pbe-rrkjus_psl.0.1.UPF', 2: 'He_ONCV_PBE-1.0.upf', 3: 'li_pbe_v1.4.uspp.F.UPF', 4: 'Be_ONCV_PBE-1.0.upf', 5: 'B.pbe-n-kjpaw_psl.0.1.UPF', 6: 'C_pbe_v1.2.uspp.F.UPF', 7: 'N.pbe.theos.UPF', 8: 'O.pbe-n-kjpaw_psl.0.1.UPF', 9: 'f_pbe_v1.4.uspp.F.UPF', 10: 'Ne.pbe-n-kjpaw_psl.1.0.0.UPF', 11: 'Na_pbe_v1.usp... |
'''
1. Write a Python function that takes two lists and returns True if they have at least one common member.
2. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Blac... | """
1. Write a Python function that takes two lists and returns True if they have at least one common member.
2. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Blac... |
class System():
#A full System
def __init__(self):
# Empty Clock Domain
self.clk_domain = None
# Empty memory containers
self.memories = []
self.mem_mode = None
self.mem_ranges = []
self.mem_ctrl = None
self.system_port = None
# Empty ... | class System:
def __init__(self):
self.clk_domain = None
self.memories = []
self.mem_mode = None
self.mem_ranges = []
self.mem_ctrl = None
self.system_port = None
self.cpu = None
self.membus = None
self.l2bus = None
self.l2cache = None |
test = { 'name': 'q1',
'points': 0,
'suites': [ { 'cases': [ {'code': '>>> pairwise_multiply([2, 3, 4], [10, 20, 30]) == [20, 60, 120]\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> pairwise_multiply(list(range(1, 10)), list(range(9, 0, -1))) == [9, 16, 21, 2... | test = {'name': 'q1', 'points': 0, 'suites': [{'cases': [{'code': '>>> pairwise_multiply([2, 3, 4], [10, 20, 30]) == [20, 60, 120]\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> pairwise_multiply(list(range(1, 10)), list(range(9, 0, -1))) == [9, 16, 21, 24, 25, 24, 21, 16, 9]\nTrue', 'hidden': False, 'locked'... |
# Problem code
def hammingWeight(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
# Setup
a = 23
print("Number of set bits in 23:")
b = hammingWeight(a)
print(b)
| def hamming_weight(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
a = 23
print('Number of set bits in 23:')
b = hamming_weight(a)
print(b) |
def goodbye():
return 'Good Bye'
def main():
print(goodbye())
if __name__ == '__main__':
main()
| def goodbye():
return 'Good Bye'
def main():
print(goodbye())
if __name__ == '__main__':
main() |
class Solution:
def numSub(self, s: str) -> int:
s = s.split('0')
res = 0
for x in s:
y = len(x)
res += (y + 1) * y // 2
return res
if __name__ == '__main__':
s = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111... | class Solution:
def num_sub(self, s: str) -> int:
s = s.split('0')
res = 0
for x in s:
y = len(x)
res += (y + 1) * y // 2
return res
if __name__ == '__main__':
s = '111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111... |
"""Modules for fetching traces from a trace file."""
__all__=['CSVFileRequestHandler',
'FileRequestHandlerFactory',
'TEXTFileRequestHandler',
'ContextMonkeyFileCache',
'FileSchemaFactory',
'XMLFileRequestHandler',
'FileRequestHandler',
'JSONFileRequ... | """Modules for fetching traces from a trace file."""
__all__ = ['CSVFileRequestHandler', 'FileRequestHandlerFactory', 'TEXTFileRequestHandler', 'ContextMonkeyFileCache', 'FileSchemaFactory', 'XMLFileRequestHandler', 'FileRequestHandler', 'JSONFileRequestHandler', 'YAMLFileRequestHandler'] |
"""
Handlers
========
Placeholder for interface that takes requests from the rx queue and provides
results in the tx queue.
.. Copyright:
Copyright 2019 Wirepas Ltd under Apache License, Version 2.0.
See file LICENSE for full license details.
"""
| """
Handlers
========
Placeholder for interface that takes requests from the rx queue and provides
results in the tx queue.
.. Copyright:
Copyright 2019 Wirepas Ltd under Apache License, Version 2.0.
See file LICENSE for full license details.
""" |
# Problem Number: 187
# Time complexity: O((N-l)l)
# Space Complexity: O((N-l)l)
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
n=len(s)
l=10
all_str=set()
output= set()
for i in range(n-l+1):
temp= s[i:i+l]
if temp ... | class Solution:
def find_repeated_dna_sequences(self, s: str) -> List[str]:
n = len(s)
l = 10
all_str = set()
output = set()
for i in range(n - l + 1):
temp = s[i:i + l]
if temp in all_str:
output.add(temp)
all_str.add(temp... |
#!/usr/bin/env python
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... | """Wrapper objects for WebKit-specific utility routines."""
class Mockconfig(object):
def __init__(self, default_configuration='Release'):
self._default_configuration = default_configuration
def build_directory(self, configuration):
return '/build'
def build_dumprendertree(self, configur... |
def link_codable() -> str:
return """
public class Link: Codable {
public var _add: String
public init(link: String) {
self._add = link
}
}
public class UnLink: Codable {
public var _del: String
public init(unLink: String) {
self._del = unLink
}
}
public enum CreateOrLink<T... | def link_codable() -> str:
return '\npublic class Link: Codable {\n public var _add: String\n public init(link: String) {\n self._add = link\n }\n}\n\npublic class UnLink: Codable {\n public var _del: String\n public init(unLink: String) {\n self._del = unLink\n }\n}\n\npublic enum C... |
# -*- coding: utf-8 -*-
def journal_context(record={}, params={}):
for k, v in params.items():
record["JOURNAL_" + k] = v
return record
| def journal_context(record={}, params={}):
for (k, v) in params.items():
record['JOURNAL_' + k] = v
return record |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '9/5/2020 3:52 AM'
num = 5
num //= 2
print(num) | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '9/5/2020 3:52 AM'
num = 5
num //= 2
print(num) |
# pedindo um cateto oposto e um cateto adjacente
co = float(input('Cateto Oposto: '))
ca = float(input('Cateto Adjacente: '))
# calculando os cateto para encontrar um hipotenusa
hi = (co ** 2 + ca ** 2) / 0.5
# mostrando a hipotenusa dos catetos
print(f'Cateto oposto: {co}, cateto Adjacente {ca}')
print(f'Hipotenusa: {... | co = float(input('Cateto Oposto: '))
ca = float(input('Cateto Adjacente: '))
hi = (co ** 2 + ca ** 2) / 0.5
print(f'Cateto oposto: {co}, cateto Adjacente {ca}')
print(f'Hipotenusa: {hi}') |
def solution(s: str) -> str:
if all(i.islower() for i in s):
return s
return ''.join(' ' + i if i.isupper() else i for i in s)
| def solution(s: str) -> str:
if all((i.islower() for i in s)):
return s
return ''.join((' ' + i if i.isupper() else i for i in s)) |
a = [1, 2, 3, 4, 5]
n = len(a)
d = 4
print(a[d:] + a[:d]) | a = [1, 2, 3, 4, 5]
n = len(a)
d = 4
print(a[d:] + a[:d]) |
human_years = 10
catYears_1st_year = 15
catYears_2nd_year = 9
catYears_older = 4
dogYears_1st_year = 15
dogYears_2st_year = 9
dogYears_older = 5
if human_years == 1:
print(human_years, catYears_1st_year, dogYears_1st_year)
if human_years == 2:
print(human_years, catYears_1st_year + catYears_2nd_year, dogYears_1... | human_years = 10
cat_years_1st_year = 15
cat_years_2nd_year = 9
cat_years_older = 4
dog_years_1st_year = 15
dog_years_2st_year = 9
dog_years_older = 5
if human_years == 1:
print(human_years, catYears_1st_year, dogYears_1st_year)
if human_years == 2:
print(human_years, catYears_1st_year + catYears_2nd_year, dogY... |
class Validator():
@classmethod
def validate(cls, value):
raise NotImplementedError()
class Transformer():
@classmethod
def transform(cls, value):
raise NotImplementedError()
class BooleanStringValidator(Validator):
"""Validate a string is in boolean type."""
@classmethod
... | class Validator:
@classmethod
def validate(cls, value):
raise not_implemented_error()
class Transformer:
@classmethod
def transform(cls, value):
raise not_implemented_error()
class Booleanstringvalidator(Validator):
"""Validate a string is in boolean type."""
@classmethod
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
node= None
while(head != null ):
next= head.next
head.ne... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
node = None
while head != null:
next = head.next
head.next = node
node = head
... |
EDGES_BODY_25 = [
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[1, 5],
[5, 6],
[6, 7],
[1, 8],
[8, 9],
[9, 10],
[10, 11],
[11, 22],
[22, 23],
[11, 24],
[8, 12],
[12, 13],
[13, 14],
[14, 19],
[19, 20],
[14, 21],
[0, 15],
[15, 17],
[0, 16],
... | edges_body_25 = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [10, 11], [11, 22], [22, 23], [11, 24], [8, 12], [12, 13], [13, 14], [14, 19], [19, 20], [14, 21], [0, 15], [15, 17], [0, 16], [16, 18]]
edges_face = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9],... |
#
# PySNMP MIB module CTRON-APPN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-APPN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
l = [4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777]
n = int(input())
for i in l:
if n%i==0:
print("YES")
break
else:
print("NO") | l = [4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777]
n = int(input())
for i in l:
if n % i == 0:
print('YES')
break
else:
print('NO') |
class InvalidSign(Exception):
pass
class InvalidCoordinate(Exception):
pass
class PreoccupiedCell(Exception):
pass
class GameStatus(Exception):
def __init__(self, sign):
self.sign = sign
class Victory(GameStatus):
pass
class Draw(GameStatus):
pass | class Invalidsign(Exception):
pass
class Invalidcoordinate(Exception):
pass
class Preoccupiedcell(Exception):
pass
class Gamestatus(Exception):
def __init__(self, sign):
self.sign = sign
class Victory(GameStatus):
pass
class Draw(GameStatus):
pass |
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
index = 0
length = len(arr)
while index < length:
if arr[index]== 0:
arr.pop(-1)
arr.ins... | class Solution:
def duplicate_zeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
index = 0
length = len(arr)
while index < length:
if arr[index] == 0:
arr.pop(-1)
arr.insert(in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.