content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#from .core import DummyInput
#from .core import Input
#from .defaults import create_input, create_pipe_input
__all__ = [
# Base.
"Input",
"DummyInput",
# Defaults.
"create_input",
"create_pipe_input",
]
| __all__ = ['Input', 'DummyInput', 'create_input', 'create_pipe_input'] |
# AC
A,B,C = map(int, input().split())
if C == 0:
if A > B:
print("Takahashi")
else:
print("Aoki")
if C == 1:
if A < B:
print("Aoki")
else:
print("Takahashi")
| (a, b, c) = map(int, input().split())
if C == 0:
if A > B:
print('Takahashi')
else:
print('Aoki')
if C == 1:
if A < B:
print('Aoki')
else:
print('Takahashi') |
# The least common multiple (L.C.M.) of two numbers
# is the smallest positive integer that is perfectly
# divisible by the two given numbers.
def LCM_Funct(x,y):
if x > y:
greater = x
else:
greater = y
while(True):
if (greater % x == 0 ) and ( greater % y == 0 ):
... | def lcm__funct(x, y):
if x > y:
greater = x
else:
greater = y
while True:
if greater % x == 0 and greater % y == 0:
lcm = greater
break
greater += 1
return lcm
num1 = 33675858
num2 = 79887686
print('The LCM of', num1, 'and', num... |
"""
Widgets from Evaluate category
"""
NAME = "Evaluate"
DESCRIPTION = "Evaluate classification/regression performance."
BACKGROUND = "#C3F3F3"
ICON = "icons/Category-Evaluate.svg"
PRIORITY = 5
| """
Widgets from Evaluate category
"""
name = 'Evaluate'
description = 'Evaluate classification/regression performance.'
background = '#C3F3F3'
icon = 'icons/Category-Evaluate.svg'
priority = 5 |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
mod = 1000000007
def find(i, p):
if p... | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
mod = 1000000007
def find(i, p):
if p[i] == i:
return ... |
"""
1474. Delete N Nodes After M Nodes of a Linked List
Given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way:
Start with the head as the current node.
Keep the first m nodes starting with the current node.
Remove the next n nodes
Keep repeating s... | """
1474. Delete N Nodes After M Nodes of a Linked List
Given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way:
Start with the head as the current node.
Keep the first m nodes starting with the current node.
Remove the next n nodes
Keep repeating s... |
class ShoutterDiv2:
def count(self, s, t):
c = 0
for n, (i, j) in enumerate(zip(s, t)):
for k, l in zip(s[n + 1 :], t[n + 1 :]):
if i <= k <= j or k <= i <= l:
c += 1
return c
| class Shoutterdiv2:
def count(self, s, t):
c = 0
for (n, (i, j)) in enumerate(zip(s, t)):
for (k, l) in zip(s[n + 1:], t[n + 1:]):
if i <= k <= j or k <= i <= l:
c += 1
return c |
t = int(input())
def fill_lists(numbers, colors):
go_up, go_down = [], []
for i in range(len(numbers)):
if colors[i] == 'R':
if numbers[i] > len(numbers):
return [], [], False
go_up.append(numbers[i])
else:
if numbers[i] < 1:
... | t = int(input())
def fill_lists(numbers, colors):
(go_up, go_down) = ([], [])
for i in range(len(numbers)):
if colors[i] == 'R':
if numbers[i] > len(numbers):
return ([], [], False)
go_up.append(numbers[i])
else:
if numbers[i] < 1:
... |
# Time: O(n)
# Space: O(n)
# hash table
class Solution(object):
def isConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return max(nums)-min(nums)+1 == len(nums) == len(set(nums))
# Time: O(nlogn)
# Space: O(1)
# sort
class Solution2(object):
def is... | class Solution(object):
def is_consecutive(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return max(nums) - min(nums) + 1 == len(nums) == len(set(nums))
class Solution2(object):
def is_consecutive(self, nums):
"""
:type nums: List[int]
... |
# following description appears in levenshtein distance offered by git
# at https://github.com/git/git/blob/master/levenshtein.c
# This function implements the Damerau-Levenshtein algorithm to
# calculate a distance between strings.
#
# Basically, it says how many letters need to be swapped, substituted,
# dele... | def levenshtein(string1, string2, swap=0, substitution=2, insertion=1, deletion=3):
"""
This is levenshtein distance calculation utility taken from
https://github.com/git/git/blob/master/levenshtein.c
@param string1:
@param string2:
@param swap:
@param substitution:
@param insertion:
... |
#!/usr/bin/python
# title :text_expansion.py
# description :This script contains the definition of a recursive function
# that expands a given text (to a max level) based on the
# pre-defined mapping.
# author :Hongbo Wang
# date :20170820
# version ... | def expand_text(string, mapping, loop):
"""
Find mapping recursively until the max loop
:param string: the text that contains space-separated words to expand
:param mapping: the dictionary needed to find out mapping
:param loop: the maximum rounds of looking up the dictionary
:type string: str
... |
class StandardIWH:
def __init__(self, w: float) -> None:
"""Standard Inertia Weight Handler.
Parameters
----------
w : float
Inertia weight.
"""
self.w = w
def __call__(self, iteration: int) -> float:
"""Returns the inertia weight unchang... | class Standardiwh:
def __init__(self, w: float) -> None:
"""Standard Inertia Weight Handler.
Parameters
----------
w : float
Inertia weight.
"""
self.w = w
def __call__(self, iteration: int) -> float:
"""Returns the inertia weight unchanged.... |
def gcd(a, b):
x, y, u, v = 0, 1, 1, 0
while a:
q, r = b // a, b % a
m, n = x - u * q, y - v * q
b, a, x, y, u, v = a, r, u, v, m, n
return b, x, y
def inv(a, m):
b, x, _ = gcd(a, m)
if b != 1:
return None
else:
return x % m
def enc(txt, k):
return... | def gcd(a, b):
(x, y, u, v) = (0, 1, 1, 0)
while a:
(q, r) = (b // a, b % a)
(m, n) = (x - u * q, y - v * q)
(b, a, x, y, u, v) = (a, r, u, v, m, n)
return (b, x, y)
def inv(a, m):
(b, x, _) = gcd(a, m)
if b != 1:
return None
else:
return x % m
def enc(t... |
class Minimax():
def __init__(self, depth, board, captures, moves, parent, alpha, beta):
self.depth = depth
self.board = board
self.captures = captures
self.moves = moves
self.parent = parent
self.alpha = alpha
self.beta = beta
| class Minimax:
def __init__(self, depth, board, captures, moves, parent, alpha, beta):
self.depth = depth
self.board = board
self.captures = captures
self.moves = moves
self.parent = parent
self.alpha = alpha
self.beta = beta |
class Solution:
def minArea(self, image: List[List[str]], x: int, y: int) -> int:
if len(image) == 0 or len(image[0]) == 0 :
return 0
left, right, up, down = 0, 0, 0, 0
start, end = 0, y
while start + 1 < end :
mid = (start + end) //2
if ... | class Solution:
def min_area(self, image: List[List[str]], x: int, y: int) -> int:
if len(image) == 0 or len(image[0]) == 0:
return 0
(left, right, up, down) = (0, 0, 0, 0)
(start, end) = (0, y)
while start + 1 < end:
mid = (start + end) // 2
if s... |
# Video Quality Weights (vqw)
# At this file you can set the weighted order of the quality
# of the streams you prefer. This means that the first available will be served.
#
twitchVQW = [
"480p30",
"360p30",
"160p30",
"720p60",
"720p30",
"chunked",
"audio_only"
]
vimeoVQW = [
"360p",
... | twitch_vqw = ['480p30', '360p30', '160p30', '720p60', '720p30', 'chunked', 'audio_only']
vimeo_vqw = ['360p', '240p', '480p', '540p', '720p', '1080p']
dailymotion_vqw = ['480', '380', '240', '144', '720', '1080']
yt_vqw = [22, 43, 18, 135, 91, 92, 93, 94, 95, 96]
dlive_vqw = ['480p', '360p', '720p', 'src']
peertube_vqw... |
files = [
"top_level.vhd",
"interface_mngr.vhd",
"filter.vhd",
"../wb_irq/debounce.vhd",
"../wb_irq/rstgen_syscon.vhd",
"irq_mngr.vhd",
"../wb_irq/imx51_wb16_wrapper.vhd",
"../obtr_hdl/mult9x9.vhd",
"../obtr_hdl/hsvfilter.vhd"
]
| files = ['top_level.vhd', 'interface_mngr.vhd', 'filter.vhd', '../wb_irq/debounce.vhd', '../wb_irq/rstgen_syscon.vhd', 'irq_mngr.vhd', '../wb_irq/imx51_wb16_wrapper.vhd', '../obtr_hdl/mult9x9.vhd', '../obtr_hdl/hsvfilter.vhd'] |
class BigOne():
def __init__(self):
self.bla = 'bla!'
def hello(self):
print('hello!')
class SmallOne():
def check(self, bigOneName):
bigOneName.hello()
testBig = BigOne()
testSmall = SmallOne()
testSmall.check(testBig) | class Bigone:
def __init__(self):
self.bla = 'bla!'
def hello(self):
print('hello!')
class Smallone:
def check(self, bigOneName):
bigOneName.hello()
test_big = big_one()
test_small = small_one()
testSmall.check(testBig) |
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
d = {}
ans = 0
for i in range(n):
if(a[i]==0):
if(b[i]==0):
ans+=1
continue
if(-b[i]/a[i] in d):
d[-b[i]/a[i]]+=1
else:
d[-b[i]/a[i]]=1
if(len(d)!=0): ans += max... | n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
d = {}
ans = 0
for i in range(n):
if a[i] == 0:
if b[i] == 0:
ans += 1
continue
if -b[i] / a[i] in d:
d[-b[i] / a[i]] += 1
else:
d[-b[i] / a[i]] = 1
if len(d) != 0:
an... |
class InvoicePermissionSetterMixin:
def __init__(self):
if self.__class__.__name__[:5] == 'Sales':
self.permissions_required = ['sales_permissions']
else:
self.permissions_required = ['purchase_permissions']
return super().__init__(); | class Invoicepermissionsettermixin:
def __init__(self):
if self.__class__.__name__[:5] == 'Sales':
self.permissions_required = ['sales_permissions']
else:
self.permissions_required = ['purchase_permissions']
return super().__init__() |
n= input('NUMS= ').split(',')
n=list(map(lambda x: int(x),n))
indx=input('INDEX= ').split(',')
indx=list(map(lambda x: int(x),indx))
a=0
raw=[]
print(type(indx[1]))
for i in indx:
raw.insert(i,n[a])
a+=1
print(raw)
| n = input('NUMS= ').split(',')
n = list(map(lambda x: int(x), n))
indx = input('INDEX= ').split(',')
indx = list(map(lambda x: int(x), indx))
a = 0
raw = []
print(type(indx[1]))
for i in indx:
raw.insert(i, n[a])
a += 1
print(raw) |
del_items(0x80082CB0)
SetType(0x80082CB0, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80082CCC)
SetType(0x80082CCC, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80082CD8)
SetType(0x80082CD8, "void Remove96__Fv()")
del_items(0x80082D10)
SetType(0x80082D10, "void AppMain()")
del_items(0x80082DD4)
SetType... | del_items(2148019376)
set_type(2148019376, 'int GetTpY__FUs(unsigned short tpage)')
del_items(2148019404)
set_type(2148019404, 'int GetTpX__FUs(unsigned short tpage)')
del_items(2148019416)
set_type(2148019416, 'void Remove96__Fv()')
del_items(2148019472)
set_type(2148019472, 'void AppMain()')
del_items(2148019668)
set... |
input = open(
'/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', "r").read()
input = input.split("\n\n")
countForEachGroup = []
for i in input:
listOfAnswersToWhichAnsweredYes = []
x = i.split("\n")
if "" in x:
x.remove("")
numberOfRepeatingChars = len(set.intersection(*[set(e) for... | input = open('/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', 'r').read()
input = input.split('\n\n')
count_for_each_group = []
for i in input:
list_of_answers_to_which_answered_yes = []
x = i.split('\n')
if '' in x:
x.remove('')
number_of_repeating_chars = len(set.intersection(*[set(e) ... |
filename_prefix = 'Rebuttal-SawyerLift-ADR-BC-Smoothing'
xlabel = 'Environment steps (2M)'
ylabel = "Average Discounted Rewards"
max_step = 2000000
max_y_axis_value = 110
legend = False
data_key = "train_ep/rew_discounted"
bc_y_value = 34.77
plot_labels = {
"Ours": [
'Rebuttal_Ours_Lift_1234_smart-river-67... | filename_prefix = 'Rebuttal-SawyerLift-ADR-BC-Smoothing'
xlabel = 'Environment steps (2M)'
ylabel = 'Average Discounted Rewards'
max_step = 2000000
max_y_axis_value = 110
legend = False
data_key = 'train_ep/rew_discounted'
bc_y_value = 34.77
plot_labels = {'Ours': ['Rebuttal_Ours_Lift_1234_smart-river-671', 'Rebuttal_O... |
class BaseConnector:
def __init__(self):
self._action_results = []
self._containers = []
self._artifacts = []
self._config = {}
self._is_poll_now = False
self._state = {}
def is_poll_now(self):
return self._is_poll_now
def add_action_result(self, act... | class Baseconnector:
def __init__(self):
self._action_results = []
self._containers = []
self._artifacts = []
self._config = {}
self._is_poll_now = False
self._state = {}
def is_poll_now(self):
return self._is_poll_now
def add_action_result(self, ac... |
first_number = 1+1+6
second_number=105+10
total= first_number + second_number
print(total)
x = 10
print(x)
| first_number = 1 + 1 + 6
second_number = 105 + 10
total = first_number + second_number
print(total)
x = 10
print(x) |
# Small alphabet o using function
def for_o():
""" *'s printed in the shape of o """
for row in range(5):
for col in range(5):
if row%4 ==0 and col %4 !=0 or row%4 !=0 and col %4 ==0:
print('*',end=' ')
else:
print(' ',end=' ')
pri... | def for_o():
""" *'s printed in the shape of o """
for row in range(5):
for col in range(5):
if row % 4 == 0 and col % 4 != 0 or (row % 4 != 0 and col % 4 == 0):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_o():
""" ... |
# Copyright 2021 The Bazel Authors. 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 la... | """Helper function to accept either a label or a directory_file_path as dict
"""
load('//nodejs/private/providers:directory_file_path_info.bzl', 'directory_file_path')
def maybe_directory_file_path(name, value):
"""Pass-through a value or convert a dict with a single key/value pair to a directory_file_path and ret... |
class Solution:
def arrangeWords(self, text: str) -> str:
s = text.split()
s[0] = s[0].lower()
n = len(s)
lis = [(len(s[i]), i) for i in range(n)]
lis.sort()
ans = []
ans.append(s[lis[0][1]].title())
for i in range(1, n):
ans.appen... | class Solution:
def arrange_words(self, text: str) -> str:
s = text.split()
s[0] = s[0].lower()
n = len(s)
lis = [(len(s[i]), i) for i in range(n)]
lis.sort()
ans = []
ans.append(s[lis[0][1]].title())
for i in range(1, n):
ans.append(s[lis... |
# Filter the beat at 3kHz
filtered = beat.low_pass_filter(3000)
# Mix loop2 with a reversed, panned version
loop = loop2.reverse().pan(-0.5).overlay(loop2.pan(0.5))
# Mix our filtered beat with the new loop at -3dB
final = filtered.overlay(loop2 - 3, loop=True) | filtered = beat.low_pass_filter(3000)
loop = loop2.reverse().pan(-0.5).overlay(loop2.pan(0.5))
final = filtered.overlay(loop2 - 3, loop=True) |
class LetterDigitCount(object):
def __init__(self, sentence):
self.sentence = sentence
def counter(self):
d = {"DIGITS": 0, "LETTERS": 0}
for x in self.sentence:
if x.isdigit():
d["DIGITS"] += 1
elif x.isalpha():
d["LETTERS"] += 1
... | class Letterdigitcount(object):
def __init__(self, sentence):
self.sentence = sentence
def counter(self):
d = {'DIGITS': 0, 'LETTERS': 0}
for x in self.sentence:
if x.isdigit():
d['DIGITS'] += 1
elif x.isalpha():
d['LETTERS'] += 1... |
"""
*Function*
An operator which produces a substance.
"""
| """
*Function*
An operator which produces a substance.
""" |
def get_max_possible(coins, amount=0, turn=True):
if not coins:
return amount
if turn:
alt_1 = get_max_possible(coins[1:], amount + coins[0], False)
alt_2 = get_max_possible(coins[:-1], amount + coins[-1], False)
return max(alt_1, alt_2)
first, last = coins[0], coins[-1]
... | def get_max_possible(coins, amount=0, turn=True):
if not coins:
return amount
if turn:
alt_1 = get_max_possible(coins[1:], amount + coins[0], False)
alt_2 = get_max_possible(coins[:-1], amount + coins[-1], False)
return max(alt_1, alt_2)
(first, last) = (coins[0], coins[-1])
... |
load(":common.bzl", _zip_src = "zip_src", _pkg_merge = "pkg_merge", _cue_deps_attr = "cue_deps_attr")
def _cue_cmd_outputs(output_name):
"""Get map of cue_cmd outputs.
Note that the arguments to this function are named after attributes on the rule.
Args:
output_name: The rule's `output_name` attribut... | load(':common.bzl', _zip_src='zip_src', _pkg_merge='pkg_merge', _cue_deps_attr='cue_deps_attr')
def _cue_cmd_outputs(output_name):
"""Get map of cue_cmd outputs.
Note that the arguments to this function are named after attributes on the rule.
Args:
output_name: The rule's `output_name` attribute
... |
# to check if value is in the list
def check(list, value):
if value in list:
return True
return False
| def check(list, value):
if value in list:
return True
return False |
class YarhBase:
def __init__(self, parent):
self.parent = parent
def html(self):
raise NotImplementedError()
def yarh(self):
raise NotImplementedError()
def findparent(self, **kwargs):
keys = ["type"]
findable = False
for kwarg in kwargs:
i... | class Yarhbase:
def __init__(self, parent):
self.parent = parent
def html(self):
raise not_implemented_error()
def yarh(self):
raise not_implemented_error()
def findparent(self, **kwargs):
keys = ['type']
findable = False
for kwarg in kwargs:
... |
# -*- coding:utf-8 -*-
"""
-------------------------------------------------------------------------------
Project Name : ESEP
File Name : reynolds.py
Start Date : 2022-03-25 07:46
... | """
-------------------------------------------------------------------------------
Project Name : ESEP
File Name : reynolds.py
Start Date : 2022-03-25 07:46
Contri... |
"""
Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function.
That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a ha... | """
Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function.
That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a ha... |
class Eleve:
def __init__(self, nom, prenom, notes=list()):
self.nom = str(nom)
self.prenom = str(prenom)
self.notes = notes
def ajouterNote(self, x):
self.notes.append(x)
def moyenne(self):
tot = sum(self.notes)
if tot == 0:
return 0
ret... | class Eleve:
def __init__(self, nom, prenom, notes=list()):
self.nom = str(nom)
self.prenom = str(prenom)
self.notes = notes
def ajouter_note(self, x):
self.notes.append(x)
def moyenne(self):
tot = sum(self.notes)
if tot == 0:
return 0
r... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 10:57:56 2020
@author: celine.gross
"""
puzzle = [15,5,1,4,7,0]
def nth_number(data, n):
# Store initial numbers read aloud
numbers = {d:[i+1] for i, d in enumerate(data)}
last = data[-1]
# Start deducing new numbers until nth
for i in range(len(d... | """
Created on Tue Dec 15 10:57:56 2020
@author: celine.gross
"""
puzzle = [15, 5, 1, 4, 7, 0]
def nth_number(data, n):
numbers = {d: [i + 1] for (i, d) in enumerate(data)}
last = data[-1]
for i in range(len(data) + 1, n + 1):
if len(numbers[last]) == 1:
last = 0
else:
... |
#To use this classes we need to change the variable export FLASK_ENV=...(development, production or testing) in the terminal
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = "Super_secret_nobody_knows_key"
DB_NAME = "production-db"
DB_USERNAME = "root"
DB_PASSWORD =... | class Config(object):
debug = False
testing = False
secret_key = 'Super_secret_nobody_knows_key'
db_name = 'production-db'
db_username = 'root'
db_password = 'example'
uploads = 'Fabricio/Programacion/Flask/Blog_website/static/img'
session_cookie_secure = True
class Productionconfig(Con... |
def insertionSort(lst,n):
for i in range(1,n):
temp = lst[i]
j = i-1
while(lst[j]>temp and j>=0):
lst[j+1]=lst[j]
j=j-1
lst[j+1]=temp
lst = list(map(int,input().split()))
n = len(lst)
print('Before : ',lst)
insertionSort(lst,n)
print('After : ',lst) | def insertion_sort(lst, n):
for i in range(1, n):
temp = lst[i]
j = i - 1
while lst[j] > temp and j >= 0:
lst[j + 1] = lst[j]
j = j - 1
lst[j + 1] = temp
lst = list(map(int, input().split()))
n = len(lst)
print('Before : ', lst)
insertion_sort(lst, n)
print('A... |
expected_output = {
'evi': {
103: {
'bd_id': {
103: {
'dg_addr': {
'10.3.1.254': {
'source': {
'V:2000103 Vlan103': {
'eth_tag': 0,
... | expected_output = {'evi': {103: {'bd_id': {103: {'dg_addr': {'10.3.1.254': {'source': {'V:2000103 Vlan103': {'eth_tag': 0, 'mac_addr': '549f.c6f4.53bf', 'valid': True}, 'V:2000103 20.0.101.1': {'eth_tag': 0, 'mac_addr': '0000.1111.2222', 'valid': True}}}, '10:3:1::254': {'source': {'V:2000103 Vlan103': {'eth_tag': 0, '... |
button_style = """
QPushButton {
color: rgb(212, 212, 212);
border: none;
background-color: rgb(51, 59, 72);
text-align: center;
}
QPushButton:hover {
color: rgb(255,255,255);
background-color: rgb(63, 73, 89);
}
... | button_style = '\n QPushButton {\n color: rgb(212, 212, 212);\n border: none;\n background-color: rgb(51, 59, 72);\n text-align: center;\n }\n\n QPushButton:hover {\n color: rgb(255,255,255);\n background-color: rgb(63, 73, 89);\n ... |
"""In gym, the RAM is represented as an 128-element array, where each element in the array can range from 0 to 255
The atari_dict below is organized as so:
key: the name of the game
value: the game dictionary
Game dictionary is organized as:
key: state variable name
value: the element in the RAM array... | """In gym, the RAM is represented as an 128-element array, where each element in the array can range from 0 to 255
The atari_dict below is organized as so:
key: the name of the game
value: the game dictionary
Game dictionary is organized as:
key: state variable name
value: the element in the RAM array... |
class A:
pass
class B(A):
pass
assert issubclass(A, A)
assert issubclass(B, A)
assert not issubclass(A, B)
class MCNotSubClass(type):
def __subclasscheck__(self, subclass):
return False
class NotSubClass(metaclass=MCNotSubClass):
pass
class InheritedNotSubClass(NotSubClass):
pass
... | class A:
pass
class B(A):
pass
assert issubclass(A, A)
assert issubclass(B, A)
assert not issubclass(A, B)
class Mcnotsubclass(type):
def __subclasscheck__(self, subclass):
return False
class Notsubclass(metaclass=MCNotSubClass):
pass
class Inheritednotsubclass(NotSubClass):
pass
assert... |
# Copyright (c) 2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#### Printable characters utilities
def is_printable(b):
return b >= 32 and b < 127
def prchr_(b):
if is_printable(b):
... | def is_printable(b):
return b >= 32 and b < 127
def prchr_(b):
if is_printable(b):
return chr(b)
else:
return '.'
prchr = [prchr_(x) for x in range(256)]
def printable(s):
return ''.join((PRCHR[x] for x in s)) |
# Created by MechAviv
# Map ID :: 940011100
# Eastern Region of Pantheon : East Sanctum
sm.showEffect("Effect/Direction10.img/effect/tuto/BalloonMsg2/0", 1200, 0, -120, -2, -2, False, 0)
sm.sendDelay(1200)
sm.setSpeakerID(3000132)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendNext("Just put that on your little... | sm.showEffect('Effect/Direction10.img/effect/tuto/BalloonMsg2/0', 1200, 0, -120, -2, -2, False, 0)
sm.sendDelay(1200)
sm.setSpeakerID(3000132)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendNext('Just put that on your little finger. ')
sm.setSpeakerID(3000132)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker... |
"""Print vs. Return in Functions
Here are two valid functions. One returns a value and one simply prints a value, without returning anything. Test run this code and experiment to understand the difference.
"""
# this prints something, but does not return anything
def show_plus_ten(num):
print(num + 10)
# this re... | """Print vs. Return in Functions
Here are two valid functions. One returns a value and one simply prints a value, without returning anything. Test run this code and experiment to understand the difference.
"""
def show_plus_ten(num):
print(num + 10)
def add_ten(num):
return num + 10
print('Calling show_plus_... |
# Created by Martin Strohalm, Thermo Fisher Scientific
# init main repository
CONVERTERS = {}
def register(tag):
"""Registers converter by given tag."""
def reg(cls):
"""Registers given class."""
CONVERTERS[tag] = cls
CONVERTERS[tag.lower()] = cls
CONVERTERS[ta... | converters = {}
def register(tag):
"""Registers converter by given tag."""
def reg(cls):
"""Registers given class."""
CONVERTERS[tag] = cls
CONVERTERS[tag.lower()] = cls
CONVERTERS[tag.upper()] = cls
return cls
return reg
class Valueconverter(object):
"""
T... |
__author__ = 'hs634'
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self):
self.root = None
def add_node(self, data):
return Node(data)
def insert(self, root, data):... | __author__ = 'hs634'
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Binarytree(object):
def __init__(self):
self.root = None
def add_node(self, data):
return node(data)
def insert(self, root, data):
... |
class ProcessPriorityClass(Enum,IComparable,IFormattable,IConvertible):
"""
Indicates the priority that the system associates with a process. This value,together with the priority value of each thread of the process,determines each thread's base priority level.
enum ProcessPriorityClass,values: AboveNormal... | class Processpriorityclass(Enum, IComparable, IFormattable, IConvertible):
"""
Indicates the priority that the system associates with a process. This value,together with the priority value of each thread of the process,determines each thread's base priority level.
enum ProcessPriorityClass,values: AboveNormal... |
print ("Calculator")
n1 = int(input("Give the first number:"))
n2 = int(input("Give the second number:"))
while True:
print ("(1) +\n(2) -\n(3) *\n(4) /\n(5) Change numbers\n(6) Quit\nCurrent numbers: ", n1,n2)
choice = int (input("Please select something(1 - 6):"))
if (choice == 1 ):
result = ... | print('Calculator')
n1 = int(input('Give the first number:'))
n2 = int(input('Give the second number:'))
while True:
print('(1) +\n(2) -\n(3) *\n(4) /\n(5) Change numbers\n(6) Quit\nCurrent numbers: ', n1, n2)
choice = int(input('Please select something(1 - 6):'))
if choice == 1:
result = n1 + n2
... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n ) :
C = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] ;
for i in range ( n + 1 ) :
... | def f_gold(n):
c = [[0 for x in range(n + 1)] for y in range(n + 1)]
for i in range(n + 1):
for j in range(min(i, n) + 1):
if j == 0 or j == i:
C[i][j] = 1
else:
C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
maxvalue = 0
for i in range(n + 1):
... |
TEXT = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
URL = "http://www.pythonchallenge.com/pc/def/map.html"
def shiftby2(s):
shifted = ord(s)
if ('a' ... | text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
url = 'http://www.pythonchallenge.com/pc/def/map.html'
def shiftby2(s):
shifted = ord(s)
if 'a' <=... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyPydeps(PythonPackage):
"""Python module dependency visualization."""
homepage = "https://pypi.python.org... | class Pypydeps(PythonPackage):
"""Python module dependency visualization."""
homepage = 'https://pypi.python.org/project/pydeps'
url = 'https://pypi.io/packages/source/p/pydeps/pydeps-1.7.1.tar.gz'
version('1.9.0', sha256='ba9b8c7d72cb4dfd3f4dd6b8a250c240d15824850a415fd428f2660ed371361f')
version('1... |
# https://www.hackerrank.com/challenges/validating-named-email-addresses/problem?h_r=profile
#input
n = int(input())
e =[input() for _ in range(n)]
#name
name = [i.split()[0] for i in e]
#user
user = [i.split()[1].split('@')[0].replace('<','') for i in e]
#email
email = [i.split()[1].split('@')[1].split('.')[0] for i ... | n = int(input())
e = [input() for _ in range(n)]
name = [i.split()[0] for i in e]
user = [i.split()[1].split('@')[0].replace('<', '') for i in e]
email = [i.split()[1].split('@')[1].split('.')[0] for i in e]
exts = [i.split()[1].split('@')[1].split('.')[1].replace('>', '') for i in e]
r = list(zip(name, user, email, ex... |
"""
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Example counter
@copyright: See LICENSE
"""
class Counter:
def __init__(self, value=0):
self.value = value
def decrement(self):
self.value -= 1
def increment(self):
self.value += 1
def getvalue(self):
return self.val... | """
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Example counter
@copyright: See LICENSE
"""
class Counter:
def __init__(self, value=0):
self.value = value
def decrement(self):
self.value -= 1
def increment(self):
self.value += 1
def getvalue(self):
return self.v... |
def skew(genome):
cg = 0
list_cg = []
for i in range(len(genome)):
if genome[i] == 'C':
cg-= 1
if genome[i] == 'G':
cg += 1
list_cg.append(cg)
return list_cg
def min_skew(genome):
skew_rel = skew(genome)
minimo = min(skew_rel)
a = [i+1 for i i... | def skew(genome):
cg = 0
list_cg = []
for i in range(len(genome)):
if genome[i] == 'C':
cg -= 1
if genome[i] == 'G':
cg += 1
list_cg.append(cg)
return list_cg
def min_skew(genome):
skew_rel = skew(genome)
minimo = min(skew_rel)
a = [i + 1 for ... |
# Imprimiendo todas las letras excepto la 'p' and 's'
i = 0
a = 'datospordatos'
while i < len(a):
if a[i] == 'p' or a[i] == 's':
i += 1
continue
print('letra actual :', a[i])
i += 1 | i = 0
a = 'datospordatos'
while i < len(a):
if a[i] == 'p' or a[i] == 's':
i += 1
continue
print('letra actual :', a[i])
i += 1 |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... | data_dic = {1: '(74904.4 * b.wall_temperature_waterwall[t, 1] +11301.8 * b.wall_temperature_waterwall[t, 2] +2427.54 * b.wall_temperature_waterwall[t, 3] +2891.35 * b.wall_temperature_waterwall[t, 4] -28320.8 * b.wall_temperature_waterwall[t, 5] +171.944 * b.w... |
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * n
for bk in bookings:
res[bk[0] - 1] += bk[2]
if bk[1] < n:
res[bk[1]] -= bk[2]
for i in range(1, n):
res[i] += res[... | class Solution:
def corp_flight_bookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * n
for bk in bookings:
res[bk[0] - 1] += bk[2]
if bk[1] < n:
res[bk[1]] -= bk[2]
for i in range(1, n):
res[i] += res[i - 1]
... |
n = int(input('DIGITE UM NUMERO'))
n2 = int(input('Digite outro'))
r = n + n2
print(r)
| n = int(input('DIGITE UM NUMERO'))
n2 = int(input('Digite outro'))
r = n + n2
print(r) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# References:
# http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
# http://stackoverflow.com/questions/606191/convert-byte-array-to-python-string
# some utf8 characters conflict with the format of XML, which causes error while parsin... | def hex_string_to_string(hexString):
bytes = []
hex_str = ''.join(hexString.split('%'))
for i in range(0, len(hexStr), 2):
bytes.append(chr(int(hexStr[i:i + 2], 16)))
try:
string = ''.join(bytes).decode('utf-8')
except UnicodeDecodeError:
string = u'Sorry! Something wrong wit... |
def ConsoleGenerator():
num = input()
while len(num):
yield float(num)
num = input()
total_sum = 0
for number in ConsoleGenerator():
total_sum += number
print(f'Sum of entered numbers is {total_sum}')
| def console_generator():
num = input()
while len(num):
yield float(num)
num = input()
total_sum = 0
for number in console_generator():
total_sum += number
print(f'Sum of entered numbers is {total_sum}') |
def third_party_workspace():
native.new_git_repository(
name = "aerospike_common",
build_file = str(Label("//third_party:aerospike-common.BUILD")),
commit = "5b459384e6bd98b0fe39e63ab1604c0359ae9507",
remote = "https://github.com/aerospike/aerospike-common.git"
)
native.new_... | def third_party_workspace():
native.new_git_repository(name='aerospike_common', build_file=str(label('//third_party:aerospike-common.BUILD')), commit='5b459384e6bd98b0fe39e63ab1604c0359ae9507', remote='https://github.com/aerospike/aerospike-common.git')
native.new_http_archive(name='lua', build_file=str(label('... |
class Testclass():
def main(self):
variable = True
if __name__ == "__main__":
module_level_attribute = True
| class Testclass:
def main(self):
variable = True
if __name__ == '__main__':
module_level_attribute = True |
class Node:
def __init__(self, value):
self.value = value
self.next_element = None
#Cycles through the linked list and prints out each value
def display(self):
while self != None:
print(self.value)
self = self.next_element
#Creates a lis... | class Node:
def __init__(self, value):
self.value = value
self.next_element = None
def display(self):
while self != None:
print(self.value)
self = self.next_element
lang1 = node('Python')
lang2 = node('Java')
lang3 = node('JavaScript')
lang4 = node('C++')
lang1.... |
"""is_valid module."""
def is_valid(exp: str) -> bool:
"""Validate if expression is a valid identifier.
Args:
exp: string to be validated
Returns:
True: if is a valid identifier.
False: if is not a valid identifier.
"""
if not isinstance(exp, str):
return False
... | """is_valid module."""
def is_valid(exp: str) -> bool:
"""Validate if expression is a valid identifier.
Args:
exp: string to be validated
Returns:
True: if is a valid identifier.
False: if is not a valid identifier.
"""
if not isinstance(exp, str):
return False
... |
order_total = 247
# ternary operator
discount = 25 if order_total > 100 else 0
print(order_total, discount)
| order_total = 247
discount = 25 if order_total > 100 else 0
print(order_total, discount) |
class TokenStream(object):
class _Mark(object):
def __init__(self, parent, pos):
self.__parent = parent
self.__pos = pos
#
def resetToMark(self):
self.__parent._pos = self.__pos
#
#
def __init__(self, tokens:list):
self._data = list(tokens)
self._pos = 0
#
def __iter__(self):
for v i... | class Tokenstream(object):
class _Mark(object):
def __init__(self, parent, pos):
self.__parent = parent
self.__pos = pos
def reset_to_mark(self):
self.__parent._pos = self.__pos
def __init__(self, tokens: list):
self._data = list(tokens)
se... |
#=================================================================#
class BdryData(object):
"""
Information for boundary conditions
"""
def __init__(self):
self.bsaved = {}
self.Asaved = {}
def __repr__(self):
return ", ".join("'{}': {}".format(attr, value) for attr, value i... | class Bdrydata(object):
"""
Information for boundary conditions
"""
def __init__(self):
self.bsaved = {}
self.Asaved = {}
def __repr__(self):
return ', '.join(("'{}': {}".format(attr, value) for (attr, value) in self.__dict__.items()))
class Convectiondata(object):
"""... |
# Problem0009 - Special Pythagorean triplet
#
# https://github.com/agileshaw/Project-Euler
def product():
for i in range(1000):
for j in range(i+1, 1000):
for k in range(j+1, 1000):
if i*i + j*j == k*k and i + j + k == 1000:
return i * j * k
if __name__ ==... | def product():
for i in range(1000):
for j in range(i + 1, 1000):
for k in range(j + 1, 1000):
if i * i + j * j == k * k and i + j + k == 1000:
return i * j * k
if __name__ == '__main__':
result = product()
print('The product of the special pythagorean... |
#CvModName.py
modName = "BUG Mod"
displayName = "BUG Mod"
modVersion = "4.4 [Build 2220]"
civName = "BtS"
civVersion = "3.13-3.19"
def getName():
return modName
def getDisplayName():
return displayName
def getVersion():
return modVersion
def getNameAndVersion():
return modName + " " + modVersion
def getDispl... | mod_name = 'BUG Mod'
display_name = 'BUG Mod'
mod_version = '4.4 [Build 2220]'
civ_name = 'BtS'
civ_version = '3.13-3.19'
def get_name():
return modName
def get_display_name():
return displayName
def get_version():
return modVersion
def get_name_and_version():
return modName + ' ' + modVersion
def ... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
try:
number = int(input("Find the square root of an integer: "))
guess = float(input("Initial guess: "))
tolerance = float(input("Tolerance: "))
original_guess = guess
count = 0
previous = 0.0
while abs(previous - guess) > tolerance:
previous = guess
quotient = number / gue... | try:
number = int(input('Find the square root of an integer: '))
guess = float(input('Initial guess: '))
tolerance = float(input('Tolerance: '))
original_guess = guess
count = 0
previous = 0.0
while abs(previous - guess) > tolerance:
previous = guess
quotient = number / guess... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 16:57:10 2021
@author: Administrator
"""
| """
Created on Sat May 15 16:57:10 2021
@author: Administrator
""" |
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.word_id = -1
self.palindrome_word_ids = []
class Trie:
def __init__(self):
self.root = TrieNode()
@staticmethod
def is_palindrome(word: str) -> bool:
retur... | class Trienode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.word_id = -1
self.palindrome_word_ids = []
class Trie:
def __init__(self):
self.root = trie_node()
@staticmethod
def is_palindrome(word: str) -> bool:
return word[:] == ... |
# encoding: utf-8
# module parser
# from /usr/lib/python3.5/lib-dynload/parser.cpython-35m-x86_64-linux-gnu.so
# by generator 1.145
""" This is an interface to Python's internal parser. """
# no imports
# Variables with simple values
__copyright__ = 'Copyright 1995-1996 by Virginia Polytechnic Institute & State\nUniv... | """ This is an interface to Python's internal parser. """
__copyright__ = 'Copyright 1995-1996 by Virginia Polytechnic Institute & State\nUniversity, Blacksburg, Virginia, USA, and Fred L. Drake, Jr., Reston,\nVirginia, USA. Portions copyright 1991-1995 by Stichting Mathematisch\nCentrum, Amsterdam, The Netherlands.'
... |
#
# PySNMP MIB module RIVERSTONE-NOTIFICATIONS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-NOTIFICATIONS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:57:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class Solution:
def reformat(self, s: str) -> str:
"""String.
Running time: O(n) where n == len(s).
"""
a, n = [], []
for i in s:
if 'a' <= i <= 'z':
a.append(i)
else:
n.append(i)
if abs(len(a)-len(n)) > 1:
... | class Solution:
def reformat(self, s: str) -> str:
"""String.
Running time: O(n) where n == len(s).
"""
(a, n) = ([], [])
for i in s:
if 'a' <= i <= 'z':
a.append(i)
else:
n.append(i)
if abs(len(a) - len(n)) > ... |
# Demonstrates simple function
#combines first name and last name with a blank between
def printName(firstName, lastName):
fullName = firstName + " " + lastName
print(fullName)
#Adds one to a number and print it
def printIncrement(number):
number = number + 1
print("The number is now ",number)
first ... | def print_name(firstName, lastName):
full_name = firstName + ' ' + lastName
print(fullName)
def print_increment(number):
number = number + 1
print('The number is now ', number)
first = 'Ivan'
last = 'Smith'
print_name(first, last)
print_name('Joe', 'Evans')
float(6)
float(7.0)
number = 7
print_incremen... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
input()
a='0'+input()+'0'
print('YNEOS'[a.count('000')>0 or a.count('11')>0::2]) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
input()
a = '0' + input() + '0'
print('YNEOS'[a.count('000') > 0 or a.count('11') > 0::2]) |
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
SCREEN_TITLE = "Arcade Community Platformer"
# Constants used to scale our sprites from their original size
TILE_SCALING = 0.5
CHARACTER_SCALING = TILE_SCALING * 2
COIN_SCALING = TILE_SCALING
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
# Shooting ... | screen_width = 1024
screen_height = 768
screen_title = 'Arcade Community Platformer'
tile_scaling = 0.5
character_scaling = TILE_SCALING * 2
coin_scaling = TILE_SCALING
sprite_pixel_size = 128
grid_pixel_size = SPRITE_PIXEL_SIZE * TILE_SCALING
sprite_scaling_laser = 0.8
shoot_speed = 15
bullet_speed = 12
bullet_damage ... |
class RiotRefuseError(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class RiotTimeoutError(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class RiotAuthError(Exception):
"""Usually raised when the client is not authenticate... | class Riotrefuseerror(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class Riottimeouterror(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class Riotautherror(Exception):
"""Usually raised when the client is not authentica... |
#!/usr/bin/env python2
# coding: utf-8
class MountPointIndex(str):
def __new__(clz, s):
if isinstance(s, int):
s = '{s:0>3}'.format(s=s)
if len(s) != 3 or not (0 <= int(s) <= 999):
raise ValueError('invalid mount point index: {s}'.format(s=s))
return super(Mount... | class Mountpointindex(str):
def __new__(clz, s):
if isinstance(s, int):
s = '{s:0>3}'.format(s=s)
if len(s) != 3 or not 0 <= int(s) <= 999:
raise value_error('invalid mount point index: {s}'.format(s=s))
return super(MountPointIndex, clz).__new__(clz, s) |
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
"""
dp[i][j] means the max profit can achieve at days j with at most j transcations
|1.T[i][j-1] do nothing at jth day
dp[... | class Solution(object):
def max_profit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
'\n dp[i][j] means the max profit can achieve at days j with at most j transcations\n |1.T[i][j-1] do nothing at jth day\n ... |
'''
Exploring your working directory
50xp
In order to import data into Python, you should first have an idea of what files
are in your working directory.
IPython, which is running on DataCamp's servers, has a bunch of cool commands,
including its magic commands. For example, starting a line with ! gives you
complete ... | """
Exploring your working directory
50xp
In order to import data into Python, you should first have an idea of what files
are in your working directory.
IPython, which is running on DataCamp's servers, has a bunch of cool commands,
including its magic commands. For example, starting a line with ! gives you
complete ... |
#!/usr/bin/env python
"""
Udacity conference server-side Python App Engine app user settings
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '727907205051-573gc5ahpho4tq7tloct49fpttktkkg8.apps.googleusercontent.com'
| """
Udacity conference server-side Python App Engine app user settings
"""
web_client_id = '727907205051-573gc5ahpho4tq7tloct49fpttktkkg8.apps.googleusercontent.com' |
class A:
...
print(A.__bases__) # (<class 'object'>,)
| class A:
...
print(A.__bases__) |
#creating a dictionary
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
# changing or adding elements in dictionary
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
#deleting elements from dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}... | my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(3))
print(squares)
print(squares.popitem())
print(squares)
del squares[2]
print(squares)
s... |
# An array of numbers arranged on a regular grid with a variable number of axes
a = [
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
]
] | a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] |
autoref_rst = """
Graphics
========
.. index ::
single: Graphics
This is the reference documentation for the graphics modules.
"""
__all__ = ['spikeparams', 'spikeplot', 'spikesum', 'spiketimehistogram'] | autoref_rst = '\nGraphics\n========\n.. index :: \n single: Graphics\n\nThis is the reference documentation for the graphics modules.\n'
__all__ = ['spikeparams', 'spikeplot', 'spikesum', 'spiketimehistogram'] |
device = '/dev/sandschreiber'
gcode_directory = u'gcodes'
listen = '0.0.0.0'
port = 8080
| device = '/dev/sandschreiber'
gcode_directory = u'gcodes'
listen = '0.0.0.0'
port = 8080 |
# Lesson 1
def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(iterative_factorial(5))
# "Recursion" is the act of calling a function from within itself. Some functions naturally work better recursively.
# Recursion is easier to work out if you write... | def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(iterative_factorial(5))
def factorial(n):
if n > 1:
return n * factorial(n - 1)
else:
return 1
print(factorial(5)) |
'''
Counting inversions. An inversion in an array a[] is a pair of entries
a[i] and a[j] such that i < j but a[i] > a[j]. Given an array,
design a linearithmic algorithm to count the number of inversions.
'''
def count_inversions(arr):
N = len(arr)
aux = arr.copy()
def count_and_sort(arr):
count ... | """
Counting inversions. An inversion in an array a[] is a pair of entries
a[i] and a[j] such that i < j but a[i] > a[j]. Given an array,
design a linearithmic algorithm to count the number of inversions.
"""
def count_inversions(arr):
n = len(arr)
aux = arr.copy()
def count_and_sort(arr):
count =... |
a = int(input())
for _ in range(a):
greater = []
smaller = []
temp = input().strip()
while not temp:
temp = input().strip()
x, y = [int(x) for x in temp.split()]
for __ in range(x-1):
t = int(input())
if t > y:
greater.append(t)
else:
small... | a = int(input())
for _ in range(a):
greater = []
smaller = []
temp = input().strip()
while not temp:
temp = input().strip()
(x, y) = [int(x) for x in temp.split()]
for __ in range(x - 1):
t = int(input())
if t > y:
greater.append(t)
else:
s... |
#Calculator using python
#Nader Mahbub Lhan Nabil
#naderkhan2507@gmail.com
welmassage = "[PyCalculator by Nader Mahbub Khan}"
print(welmassage)
print("=====================================================================")
print("INPUT SECTION")
print("============================================================... | welmassage = '[PyCalculator by Nader Mahbub Khan}'
print(welmassage)
print('=====================================================================')
print('INPUT SECTION')
print('=====================================================================')
num1 = float(input('Please enter the first number: '))
num2 = float(in... |
data = []
with open("./test_sampled.txt") as f:
for line in f:
data.append(line.strip())
index = 0
while index < 4000:
with open("test_sampled_" + str(index) + "_" + str(index+500) + ".txt", "w") as wf:
for d in range(index, index+500):
wf.write(data[d]+'\n')
index += 500
| data = []
with open('./test_sampled.txt') as f:
for line in f:
data.append(line.strip())
index = 0
while index < 4000:
with open('test_sampled_' + str(index) + '_' + str(index + 500) + '.txt', 'w') as wf:
for d in range(index, index + 500):
wf.write(data[d] + '\n')
index += 500 |
class Validator():
n = None
k = None
h = None
def are_valid_parameters(self, args):
return self.validate_arguments(args) and \
self.validate_file_name(args[1]) and \
self.validate_instance_no(args[2]) and \
self.validate_param_h(args[3])
def par... | class Validator:
n = None
k = None
h = None
def are_valid_parameters(self, args):
return self.validate_arguments(args) and self.validate_file_name(args[1]) and self.validate_instance_no(args[2]) and self.validate_param_h(args[3])
def parameters(self):
return (self.n, self.k, self.h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.