content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Hey:
def __init__(jose, name="mours"):
jose.name = name
def get_name(jose):
return jose.name
class Person(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, *args, **kwargs):
self.website... | class Hey:
def __init__(jose, name='mours'):
jose.name = name
def get_name(jose):
return jose.name
class Person(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, *args, **kwargs):
self.we... |
# Autor: Anuj Sharma (@optider)
# Github Profile: https://github.com/Optider/
# Problem Link: https://leetcode.com/problems/contains-duplicate/
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums :
if count.get(n) != None :
ret... | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums:
if count.get(n) != None:
return True
count[n] = 1
return False |
{
'target_defaults': {
'win_delay_load_hook': 'false',
'conditions': [
['OS=="win"', {
'msvs_disabled_warnings': [
4530, # C++ exception handler used, but unwind semantics are not enabled
4506, # no definition for inline function
],
}],
],
},
'targets'... | {'target_defaults': {'win_delay_load_hook': 'false', 'conditions': [['OS=="win"', {'msvs_disabled_warnings': [4530, 4506]}]]}, 'targets': [{'target_name': 'fs_admin', 'defines': ['NAPI_VERSION=<(napi_build_version)'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_... |
DEBUG = True
USE_TZ = True
SECRET_KEY = "dummy"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"rest_framework",
"django_filters",
"belt",
"tests.app",
]... | debug = True
use_tz = True
secret_key = 'dummy'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'rest_framework', 'django_filters', 'belt', 'tests.app']
site_id = 1
root_urlconf = 'tests... |
#!/usr/bin/env python
''' This module provides configuration options for OS project. No more magic numbers! '''
BLOCK_SIZE = 16 # words
WORD_SIZE = 4 # bytes
# length od RS in blocks
RESTRICTED_LENGTH = 1
# length of DS in blocks
DS_LENGTH = 6
# timer value
TIMER_VALUE = 10
# buffer size
BUFFER_SIZE = 16
# num... | """ This module provides configuration options for OS project. No more magic numbers! """
block_size = 16
word_size = 4
restricted_length = 1
ds_length = 6
timer_value = 10
buffer_size = 16
hd_blocks_size = 500
root_priority = 40
vm_priority = 50
loader_priority = 60
interrupt_priority = 70
print_priority = 70
running_... |
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [float('inf')] * n
dp[0] = 0
tail = 1
for i in range(n):
limit = min(n, i + nums[i] + 1)
for j in range(tail, limit):
dp[j] = min(dp[j], dp[i] + 1)
... | class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [float('inf')] * n
dp[0] = 0
tail = 1
for i in range(n):
limit = min(n, i + nums[i] + 1)
for j in range(tail, limit):
dp[j] = min(dp[j], dp[i] + 1)
... |
#! /usr/bin/python3
# Description: Data_Ghost, concealing data into spaces and tabs making it imperceptable to human eyes.
# Author: Ajay Dyavathi
# Github: Radical Ajay
class Ghost():
def __init__(self, file_name, output_format='txt'):
''' Converts ascii text to spaces and tabs '''
self.file_name... | class Ghost:
def __init__(self, file_name, output_format='txt'):
""" Converts ascii text to spaces and tabs """
self.file_name = file_name
self.output_format = output_format
def ascii2bin(self, asc):
""" Converting ascii to bianry """
return ''.join(('{:08b}'.format(ord... |
class Solution:
def defangIPaddr(self, address: str) -> str:
i=0
j=0
strlist=list(address)
defang=[]
while i< len(strlist):
if strlist[i] == '.':
defang.append('[')
defang.append('.')
defang.append(']')
... | class Solution:
def defang_i_paddr(self, address: str) -> str:
i = 0
j = 0
strlist = list(address)
defang = []
while i < len(strlist):
if strlist[i] == '.':
defang.append('[')
defang.append('.')
defang.append(']')
... |
class Node:
def __init__(self, path, libgraphql_type, location, name):
self.path = path
self.parent = None
self.children = []
self.libgraphql_type = libgraphql_type
self.location = location
self.name = name
def __repr__(self):
return "%s(%s)" % (self.libg... | class Node:
def __init__(self, path, libgraphql_type, location, name):
self.path = path
self.parent = None
self.children = []
self.libgraphql_type = libgraphql_type
self.location = location
self.name = name
def __repr__(self):
return '%s(%s)' % (self.lib... |
class Contact:
def __init__(self, first_name, last_name, nickname, address, mobile, email):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.address = address
self.mobile = mobile
self.email = email
| class Contact:
def __init__(self, first_name, last_name, nickname, address, mobile, email):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.address = address
self.mobile = mobile
self.email = email |
count = int(input())
title = 0
while count > 0:
title += 1
if '666' in str(title):
count -= 1
print(title)
| count = int(input())
title = 0
while count > 0:
title += 1
if '666' in str(title):
count -= 1
print(title) |
#!/usr/bin/env python3
USER = r'server\user'
PASSWORD = 'server_password'
HOSTNAME = 'hostname.goes.here.com'
DOMAIN = 'domain.goes.here.com'
FROM_ADDR = 'emailyouwanttosendmessagesfrom@something.com'
| user = 'server\\user'
password = 'server_password'
hostname = 'hostname.goes.here.com'
domain = 'domain.goes.here.com'
from_addr = 'emailyouwanttosendmessagesfrom@something.com' |
def createKafkaSecurityGroup(ec2, vpc):
sec_group_kafka = ec2.create_security_group(
GroupName='kafka', Description='kafka sec group', VpcId=vpc.id)
sec_group_kafka.authorize_ingress(
IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
... | def create_kafka_security_group(ec2, vpc):
sec_group_kafka = ec2.create_security_group(GroupName='kafka', Description='kafka sec group', VpcId=vpc.id)
sec_group_kafka.authorize_ingress(IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp... |
# STRAND SORT
# It is a recursive comparison based sorting technique which sorts in increasing order.
# It works by repeatedly pulling sorted sub-lists out of the list to be sorted and merging them
# with a result array.
# Algorithm:
# Create a empty strand (list) and append the first element to it popping it from th... | def merge(arr1, arr2):
merged_list = []
while len(arr1) and len(arr2):
if arr1[0] < arr2[0]:
merged_list.append(arr1.pop(0))
else:
merged_list.append(arr2.pop(0))
merged_list += arr1
merged_list += arr2
return merged_list
def strand(arr):
s = [arr.pop(0)]... |
class Proceso:
def __init__(self,tiempo_de_llegada,t,id):
self.t=t
self.tiempo_de_llegada=tiempo_de_llegada
self.id=id
self.inicio=0
self.fin=0
self.T=0
self.E=0
self.P=0
self.tRestantes = t
| class Proceso:
def __init__(self, tiempo_de_llegada, t, id):
self.t = t
self.tiempo_de_llegada = tiempo_de_llegada
self.id = id
self.inicio = 0
self.fin = 0
self.T = 0
self.E = 0
self.P = 0
self.tRestantes = t |
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
list_before = db.get_contact_list()
contact.id_contact = app.contact.get_next_id(list_before)
app.contact.create(contact)
assert len(list_before) + 1 == len(db.get_contact_list())
list_after = db.get_contact_list()
... | def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
list_before = db.get_contact_list()
contact.id_contact = app.contact.get_next_id(list_before)
app.contact.create(contact)
assert len(list_before) + 1 == len(db.get_contact_list())
list_after = db.get_contact_list()
... |
# solution 1: Brute Force
# time complexity: O(n^2)
# space complexity: O(1)
def twoNumberSum(arr, n):
for i in range(len(arr) - 1):
firstNum = arr[i]
for j in range(i + 1, len(arr)):
secondNum = arr[j]
if firstNum + secondNum == n:
return [first... | def two_number_sum(arr, n):
for i in range(len(arr) - 1):
first_num = arr[i]
for j in range(i + 1, len(arr)):
second_num = arr[j]
if firstNum + secondNum == n:
return [firstNum, secondNum]
return []
print(two_number_sum([3, 5, -4, 8, 11, 1, -1, 6], 10)) |
class InvalidMovementException(Exception):
pass
class InvalidMovementTargetException(InvalidMovementException):
pass
class InvalidMovimentOriginException(InvalidMovementException):
pass | class Invalidmovementexception(Exception):
pass
class Invalidmovementtargetexception(InvalidMovementException):
pass
class Invalidmovimentoriginexception(InvalidMovementException):
pass |
FORM_CONTENT_TYPES = [
'application/x-www-form-urlencoded',
'multipart/form-data'
]
| form_content_types = ['application/x-www-form-urlencoded', 'multipart/form-data'] |
def numb_of_char(a):
d = {}
for char in set(a):
d[char] = a.count(char)
return d
a = numb_of_char(str(input("Input the word please: ")))
print(a)
| def numb_of_char(a):
d = {}
for char in set(a):
d[char] = a.count(char)
return d
a = numb_of_char(str(input('Input the word please: ')))
print(a) |
class Vector2D:
def __init__(self, v: List[List[int]]):
def getIt():
for row in v:
for val in row:
yield val
self.it = iter(getIt())
self.val = next(self.it, None)
def next(self) -> int:
result = self.val
... | class Vector2D:
def __init__(self, v: List[List[int]]):
def get_it():
for row in v:
for val in row:
yield val
self.it = iter(get_it())
self.val = next(self.it, None)
def next(self) -> int:
result = self.val
self.val = nex... |
n = int(input())
line = list(map(int, input().split()))
l = {}
res = ""
for i, j in enumerate(line):
l[j] = i+1
for k in range(n):
res += str(l[k+1]) + " "
print(res.rstrip()) | n = int(input())
line = list(map(int, input().split()))
l = {}
res = ''
for (i, j) in enumerate(line):
l[j] = i + 1
for k in range(n):
res += str(l[k + 1]) + ' '
print(res.rstrip()) |
valor = int(input())
for i in range(valor+1):
if(i%2 != 0):
print(i) | valor = int(input())
for i in range(valor + 1):
if i % 2 != 0:
print(i) |
# https://leetcode.com/problems/delete-and-earn/
class Solution:
def deleteAndEarn(self, nums: list[int]) -> int:
num_profits = dict()
for num in nums:
num_profits[num] = num_profits.get(num, 0) + num
sorted_nums = sorted(num_profits.keys())
second_last_profit = 0
... | class Solution:
def delete_and_earn(self, nums: list[int]) -> int:
num_profits = dict()
for num in nums:
num_profits[num] = num_profits.get(num, 0) + num
sorted_nums = sorted(num_profits.keys())
second_last_profit = 0
last_profit = num_profits[sorted_nums[0]]
... |
class BaseStorage(object):
def get_rule(self, name):
raise NotImplementedError()
def get_ruleset(self, name):
raise NotImplementedError()
| class Basestorage(object):
def get_rule(self, name):
raise not_implemented_error()
def get_ruleset(self, name):
raise not_implemented_error() |
# https://projecteuler.net/problem=19
def is_leap(year):
if year%4 != 0:
return False
if year%100 == 0 and year%400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
if month == 4 or month == 6 or m... | def is_leap(year):
if year % 4 != 0:
return False
if year % 100 == 0 and year % 400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
if month == 4 or month == 6 or month == 9 or (month == 11):
... |
class Config:
ngram = 2
train_set = "data/rmrb.txt"
modified_train_set = "data/rmrb_modified.txt"
test_set = ""
model_file = ""
param_file = ""
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 | class Config:
ngram = 2
train_set = 'data/rmrb.txt'
modified_train_set = 'data/rmrb_modified.txt'
test_set = ''
model_file = ''
param_file = ''
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 |
def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return (len(a) <= len(b))
def analisar(e, i, s):
a, b = e
if(diferenca_tamanhos(a, ... | def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return len(a) <= len(b)
def analisar(e, i, s):
(a, b) = e
if diferenca_tamanhos(a, ... |
class Solution:
def allPossibleFBT(self, N):
def constr(N):
if N == 1: yield TreeNode(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = TreeNode(0)
m.left = l
... | class Solution:
def all_possible_fbt(self, N):
def constr(N):
if N == 1:
yield tree_node(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = tree_node(0)
... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | def find_decision(obj):
if obj[7] > 0:
if obj[6] <= 5:
if obj[2] <= 1:
if obj[10] <= 13:
if obj[3] > 0:
if obj[16] <= 2:
return 'False'
elif obj[16] > 2:
if... |
macs_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org... | macs_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/w... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
VERIFIED_OP_REFERENCES = [
'Abs-1',
'Acos-1',
'Add-1',
'Asin-1',
'Asinh-3',
'Assign-6',
'AvgPool-1',
'BatchNormInference-5',
'BatchToSpace-2',
'BinaryConvolution-1',
'Broadcast-1',
'Broadcast-3'... | verified_op_references = ['Abs-1', 'Acos-1', 'Add-1', 'Asin-1', 'Asinh-3', 'Assign-6', 'AvgPool-1', 'BatchNormInference-5', 'BatchToSpace-2', 'BinaryConvolution-1', 'Broadcast-1', 'Broadcast-3', 'Bucketize-3', 'Ceiling-1', 'CTCGreedyDecoder-1', 'CTCGreedyDecoderSeqLen-6', 'Concat-1', 'Convert-1', 'ConvertLike-1', 'Conv... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This dictionary of GPU information was captured from a run of
# Telemetry on a Linux workstation with NVIDIA GPU. It helps test
# telemetry.internal.platfo... | fake_gpu_info = {'feature_status': {'flash_stage3d': 'enabled', 'gpu_compositing': 'enabled', 'video_decode': 'unavailable_software', 'flash_3d': 'enabled', 'webgl': 'enabled', 'video_encode': 'enabled', 'multiple_raster_threads': 'enabled_on', '2d_canvas': 'unavailable_software', 'rasterization': 'disabled_software', ... |
for i in range(int(input())):
number_of_candies = int(input())
candies_weights = list(map(int, input().split()))
bob_pos = number_of_candies - 1
alice_pos = 0
bob_current_weight = 0
alice_current_weight = 0
last_equal_candies_total_number = 0
while alice_pos <= bob_pos:
if al... | for i in range(int(input())):
number_of_candies = int(input())
candies_weights = list(map(int, input().split()))
bob_pos = number_of_candies - 1
alice_pos = 0
bob_current_weight = 0
alice_current_weight = 0
last_equal_candies_total_number = 0
while alice_pos <= bob_pos:
if alice_... |
# --------------
# Code starts here
# Create the lists
class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio']
class_2 = ['hilary mason', 'carla gentry', 'corinna cortes']
# Concatenate both the strings
new_class = class_1+class_2
print(new_class)
# Append the list
new_class.append('p... | class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio']
class_2 = ['hilary mason', 'carla gentry', 'corinna cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('peter warden')
print(new_class)
new_class.remove('carla gentry')
print(new_class)
courses = {'math': 65, 'english'... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:31:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
samples = {
"2_brother_plays": {
"question_parts": [range(1, 13), range(13, 17)],
"sp_parts": [range(20, 43), range(50, 60)]
}
}
| samples = {'2_brother_plays': {'question_parts': [range(1, 13), range(13, 17)], 'sp_parts': [range(20, 43), range(50, 60)]}} |
# coding = utf-8
# Create date: 2018-11-05
# Author :Hailong
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
stdin, stdout, st... | def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
(stdin, stdout, stderr) = client.exec_command(command, timeout=10)
output = ... |
#Datos de entrada
num=int(input("Ingrese un numero: "))
# Proceso
if num==10:
print("Calificacion: A")
elif num==9:
print("Calificacion: B")
elif num==8:
print("Calificacion: C")
elif num==7 and num==6:
print("Calificacion: D")
elif num<=5 and num>=0:
print("Calificacion: F")
| num = int(input('Ingrese un numero: '))
if num == 10:
print('Calificacion: A')
elif num == 9:
print('Calificacion: B')
elif num == 8:
print('Calificacion: C')
elif num == 7 and num == 6:
print('Calificacion: D')
elif num <= 5 and num >= 0:
print('Calificacion: F') |
ribbon_needed = 0
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
length, width, height = [int(item) for item in line.split("x")]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_side = min(dimensions)
ribbon_n... | ribbon_needed = 0
with open('input.txt', 'r') as puzzle_input:
for line in puzzle_input:
(length, width, height) = [int(item) for item in line.split('x')]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_sid... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor =... | class Solution:
def hamming_distance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hamming_distance(self, x: int, y: int) -> int:
xo... |
def setIntersectionCount(group):
return len(set.intersection(*group))
groupList = []
tempGroup = []
with open("./6/input.txt") as inputFile:
for line in inputFile:
line = line.replace("\n","")
if len(line) > 0:
tempGroup.append(set(line))
else:
groupList.append(tempGroup)
tempGroup = []
if len(tempGr... | def set_intersection_count(group):
return len(set.intersection(*group))
group_list = []
temp_group = []
with open('./6/input.txt') as input_file:
for line in inputFile:
line = line.replace('\n', '')
if len(line) > 0:
tempGroup.append(set(line))
else:
groupList.app... |
# If you're new to file handling, be sure to check out with_open.py first!
# You'll also want to check out read_text.py before this example. This one is a bit more advanced.
with open('read_csv.csv', 'r') as states_file:
# Instead of leaving the file contents as a string, we're splitting the file into a list... | with open('read_csv.csv', 'r') as states_file:
states = states_file.read().split('\n')
for (index, state) in enumerate(states):
states[index] = state.split(',')
for state in states[1:]:
print('\n---{0}---'.format(state[0]))
for (index, info) in enumerate(state[1:]):
print('{0}:\t{1}'.for... |
class Student:
studentLevel = 'first year computer science 2020/2021 session'
studentCounter = 0
registeredCourse='csc102'
def __init__(self, thename, thematricno, thesex,thehostelname,theage,thecsc102examscore):
self.name = thename
self.matricno = thematricno
self.sex = thesex
... | class Student:
student_level = 'first year computer science 2020/2021 session'
student_counter = 0
registered_course = 'csc102'
def __init__(self, thename, thematricno, thesex, thehostelname, theage, thecsc102examscore):
self.name = thename
self.matricno = thematricno
self.sex =... |
def say_hi(name,age):
print("Hello " + name + ", you are " + age)
say_hi("Mike", "35")
def cube(num): # function
return num*num*num
result = cube(4) # variable
print(result)
| def say_hi(name, age):
print('Hello ' + name + ', you are ' + age)
say_hi('Mike', '35')
def cube(num):
return num * num * num
result = cube(4)
print(result) |
#
# PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
# written by abraham on aug 24
def dyear2date(dyear):
year = int(dyear)
month_lengths = [31,28,31,30,31,30,31,31,30,31,30,31]
days_before_months = [0,31,59,90,120,151,181,212,243,273,304,334]
days_into_year_f = (dyear-year)*365
days_into_year_i = int(days_into_year_f)
for i in range(12):
if days_before_mo... | def dyear2date(dyear):
year = int(dyear)
month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days_before_months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
days_into_year_f = (dyear - year) * 365
days_into_year_i = int(days_into_year_f)
for i in range(12):
if d... |
# file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb')
file = open('encrypt_eye.png', 'rb')
image = file.read()
file.close()
image = bytearray(image)
key = 48
for index, value in enumerate(image):
image[index] = value^key
file = open('2eye.png','wb')
... | file = open('encrypt_eye.png', 'rb')
image = file.read()
file.close()
image = bytearray(image)
key = 48
for (index, value) in enumerate(image):
image[index] = value ^ key
file = open('2eye.png', 'wb')
file.write(image)
file.close() |
n=int(input())
c = 1
while c**2 < n:
print(c**2)
c += 1
| n = int(input())
c = 1
while c ** 2 < n:
print(c ** 2)
c += 1 |
# CPU: 0.06 s
possessed, found, condition = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
div, mod = divmod(possessed, condition)
count += div
possessed = div + mod
print(count)
| (possessed, found, condition) = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
(div, mod) = divmod(possessed, condition)
count += div
possessed = div + mod
print(count) |
print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0)
| print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0) |
class Dummy():
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class DummyData():
def __init__(self):
self.results = [
Dummy({
'name': 'PA',
'age': 29,
'city': 'Paris'... | class Dummy:
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class Dummydata:
def __init__(self):
self.results = [dummy({'name': 'PA', 'age': 29, 'city': 'Paris'}), dummy({'name': 'Cairo', 'age': 0, 'city': 'Muizenberg'}), dum... |
array = []
for _ in range(int(input())):
command = input().strip().split(" ")
cmd_type = command[0]
if (cmd_type == "print"):
print(array)
elif (cmd_type == "sort"):
array.sort()
elif (cmd_type == "reverse"):
array.reverse()
elif (cmd_type == "pop"):
array.pop()
... | array = []
for _ in range(int(input())):
command = input().strip().split(' ')
cmd_type = command[0]
if cmd_type == 'print':
print(array)
elif cmd_type == 'sort':
array.sort()
elif cmd_type == 'reverse':
array.reverse()
elif cmd_type == 'pop':
array.pop()
elif ... |
class AuthError(Exception):
pass
class JsonError(Exception):
pass
| class Autherror(Exception):
pass
class Jsonerror(Exception):
pass |
# 3. Define a function to check whether a number is even
def even(num):
if num%2 == 0:
return True
else:
return False
print(even(4))
print(even(-5))
| def even(num):
if num % 2 == 0:
return True
else:
return False
print(even(4))
print(even(-5)) |
class OverlapResult:
def __init__(self, overlap_map: dict[tuple[float, float], int]):
self._overlap_map = overlap_map
self._overlaps = overlap_map_to_overlaps(overlap_map)
@property
def overlaps(self) -> int:
return self._overlaps
@property
def overlap_map(self) -> dict[tu... | class Overlapresult:
def __init__(self, overlap_map: dict[tuple[float, float], int]):
self._overlap_map = overlap_map
self._overlaps = overlap_map_to_overlaps(overlap_map)
@property
def overlaps(self) -> int:
return self._overlaps
@property
def overlap_map(self) -> dict[tu... |
class Config:
def __init__(self, config_file_name):
self.config_file_name = config_file_name
| class Config:
def __init__(self, config_file_name):
self.config_file_name = config_file_name |
# @AUTHOR : lonsty
# @DATE : 2020/3/28 18:01
class CookiesExpiredException(Exception):
pass
class NoImagesException(Exception):
pass
class ContentParserError(Exception):
pass
class UserNotFound(Exception):
pass
| class Cookiesexpiredexception(Exception):
pass
class Noimagesexception(Exception):
pass
class Contentparsererror(Exception):
pass
class Usernotfound(Exception):
pass |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"WorldArea",
"VoxelLight",
"VoxelLightNode",
"VoxelLevelGenerator",
"VoxelLevelGeneratorFlat",
"VoxelSurfaceMerger",
"VoxelSurfaceSimple",
... | def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return ['WorldArea', 'VoxelLight', 'VoxelLightNode', 'VoxelLevelGenerator', 'VoxelLevelGeneratorFlat', 'VoxelSurfaceMerger', 'VoxelSurfaceSimple', 'VoxelSurface', 'VoxelLibraryMerger', 'VoxelLibrarySimple', 'VoxelLib... |
# The Pokemon class should receive a name (string) and health (int) upon initialization.
# It should also have a method called pokemon_details that returns the information about the pokemon:
# "{pokemon_name} with health {pokemon_health}"
class Pokemon:
def __init__(self, name: str, health: int) -> None:
... | class Pokemon:
def __init__(self, name: str, health: int) -> None:
self.name = name
self.health = health
def pokemon_details(self) -> str:
return f'{self.name} with health {self.health}' |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_mem_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp"
],
"include... | {'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_mem_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp'], 'include_dirs': ['../gdal/ogr/ogrsf_frmts/mem']}]... |
_base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py']
model = dict(
pretrains=dict(
detector= # noqa: E251
'https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth' # noqa: E501
))
data_root = 'data/MOT17/'
test_set = 'test'
data = dict... | _base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py']
model = dict(pretrains=dict(detector='https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth'))
data_root = 'data/MOT17/'
test_set = 'test'
data = dict(train=dict(ann_file=data_root + 'annotations/train_coco... |
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that ... | class Moduledocfragment(object):
documentation = '\n\noptions:\n docker_host:\n description:\n - "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the\n TCP connection string. For example, \'tcp://192.0.2.23:2376\'. If TLS is used ... |
DEFAULT_MIRRORS = {
"bitbucket": [
"https://bitbucket.org/{repository}/get/{commit}.tar.gz",
],
"buildifier": [
"https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}",
],
"github": [
"https://github.com/{repository}/archive/{commit}.tar.gz",
],
... | default_mirrors = {'bitbucket': ['https://bitbucket.org/{repository}/get/{commit}.tar.gz'], 'buildifier': ['https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}'], 'github': ['https://github.com/{repository}/archive/{commit}.tar.gz'], 'pypi': ['https://files.pythonhosted.org/packages/source/{... |
class Animal():
edad:int
patas:int
ruido:str
nombre: str
kgComida: float = 0
def __init__(self, edad, patas, ruido, nombre):
self.edad =edad
self.patas = patas
self.ruido = ruido
self.nombre = nombre
def comer(self, alimento):
self.kgComida += alimento... | class Animal:
edad: int
patas: int
ruido: str
nombre: str
kg_comida: float = 0
def __init__(self, edad, patas, ruido, nombre):
self.edad = edad
self.patas = patas
self.ruido = ruido
self.nombre = nombre
def comer(self, alimento):
self.kgComida += ali... |
maxWeight = 30
value = [15, 7, 10, 5, 8, 17]
weight = [15, 3, 2, 5, 9, 20]
def bag(pos, selected):
# calcula o total
totalValue = 0
pesoTotal = 0
for i in selected:
totalValue += value[i]
pesoTotal += weight[i]
if pesoTotal > maxWeight:
return (0,0)
if pos >= len(weight):
return (totalValue, pesoT... | max_weight = 30
value = [15, 7, 10, 5, 8, 17]
weight = [15, 3, 2, 5, 9, 20]
def bag(pos, selected):
total_value = 0
peso_total = 0
for i in selected:
total_value += value[i]
peso_total += weight[i]
if pesoTotal > maxWeight:
return (0, 0)
if pos >= len(weight):
return... |
ADDED_KARMA_TO_MEMBER = "Gave {} karma to {}, their karma is now at {}."
REMOVED_KARMA_FROM_MEMBER = "Removed {} karma from {}, their karma is now at {}."
LIST_KARMA_OWN = "You currently have {} karma."
LIST_KARMA_OBJECT = "\"{}\" currently has {} karma."
LIST_KARMA_MEMBER = "{} currently has {} karma."
KARMA_TOP_STA... | added_karma_to_member = 'Gave {} karma to {}, their karma is now at {}.'
removed_karma_from_member = 'Removed {} karma from {}, their karma is now at {}.'
list_karma_own = 'You currently have {} karma.'
list_karma_object = '"{}" currently has {} karma.'
list_karma_member = '{} currently has {} karma.'
karma_top_start =... |
# simple test function that uses python 3 features (e.g., f-strings)
# see https://github.com/localstack/localstack/issues/264
def handler(event, context):
# the following line is Python 3.6+ specific
msg = f"Successfully processed {event}" # noqa This code is Python 3.6+ only
return event
| def handler(event, context):
msg = f'Successfully processed {event}'
return event |
def deco1(func):
print("before myfunc() called.")
func()
print("after myfunc() called.")
def myfunc():
print("myfunc() called.")
deco1(myfunc)
| def deco1(func):
print('before myfunc() called.')
func()
print('after myfunc() called.')
def myfunc():
print('myfunc() called.')
deco1(myfunc) |
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = dict()
def add_item(self, item_name, quantity, price):
if item_name != None and quantity >= 1:
self.items.update({item_name: quantity})
if quantity and price >= 1:
self.total += (quantity * price)
def re... | class Shoppingcart(object):
def __init__(self):
self.total = 0
self.items = dict()
def add_item(self, item_name, quantity, price):
if item_name != None and quantity >= 1:
self.items.update({item_name: quantity})
if quantity and price >= 1:
self.total += ... |
def solution(bridge_length, weight, truck_weights):
answer = 0
# { weight, time }
wait = truck_weights[:]
bridge = []
passed = 0
currWeight = 0
while True:
if passed == len(truck_weights) and len(wait) == 0: return answer
answer += 1
# sth needs to be passed
... | def solution(bridge_length, weight, truck_weights):
answer = 0
wait = truck_weights[:]
bridge = []
passed = 0
curr_weight = 0
while True:
if passed == len(truck_weights) and len(wait) == 0:
return answer
answer += 1
if bridge:
if bridge[0]['t'] + b... |
def check_difference():
pass
def update_benchmark():
pass
| def check_difference():
pass
def update_benchmark():
pass |
# while True:
# # ejecuta esto
# print("Hola")
real = 7
print("Entre un numero entre el 1 y el 10")
guess = int(input())
# =/=
while guess != real:
print("Ese no es el numero")
print("Entre un numero entre el 1 y el 10")
guess = int(input())
# el resto
print("Yay! Lo sacastes!")
| real = 7
print('Entre un numero entre el 1 y el 10')
guess = int(input())
while guess != real:
print('Ese no es el numero')
print('Entre un numero entre el 1 y el 10')
guess = int(input())
print('Yay! Lo sacastes!') |
class Foo:
def bar(self):
return "a"
if __name__ == "__main__":
f = Foo()
b = f.bar()
print(b) | class Foo:
def bar(self):
return 'a'
if __name__ == '__main__':
f = foo()
b = f.bar()
print(b) |
'''
Speed: 95.97%
Memory: 24.96%
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution(object):
def longestValidParentheses(self, s):
ans=0
stack=[-1]
for i in range(len(s)):
if(s[i]=='('):
stack.append(i)
else:
stack.pop()
... | """
Speed: 95.97%
Memory: 24.96%
Time complexity: O(n)
Space complexity: O(n)
"""
class Solution(object):
def longest_valid_parentheses(self, s):
ans = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack... |
def greet():
print("Hi")
def greet_again(message):
print(message)
def greet_again_with_type(message):
print(type(message))
print(message)
greet()
greet_again("Hello Again")
greet_again_with_type("One Last Time")
greet_again_with_type(1234)
# multiple types
def multiple_types(x):
if x < 0:
... | def greet():
print('Hi')
def greet_again(message):
print(message)
def greet_again_with_type(message):
print(type(message))
print(message)
greet()
greet_again('Hello Again')
greet_again_with_type('One Last Time')
greet_again_with_type(1234)
def multiple_types(x):
if x < 0:
return -1
el... |
# Authentication & API Keys
# Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or maliciou... | api_key = 'string' |
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
p1, p2 = nums[0], nums[nums[0]]
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[nums[p2]]
p2 = 0
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[p2]
return... | class Solution:
def find_duplicate(self, nums: List[int]) -> int:
(p1, p2) = (nums[0], nums[nums[0]])
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[nums[p2]]
p2 = 0
while nums[p1] != nums[p2]:
p1 = nums[p1]
p2 = nums[p2]
... |
class A:
def a(self):
return 'a'
class B(A, object):
def b(self):
return 'b'
class Inherit(A):
def a(self):
return 'c'
| class A:
def a(self):
return 'a'
class B(A, object):
def b(self):
return 'b'
class Inherit(A):
def a(self):
return 'c' |
def sum_of_squares(n):
return sum(i ** 2 for i in range(1, n+1))
def square_of_sum(n):
return sum(range(1, n+1)) ** 2
| def sum_of_squares(n):
return sum((i ** 2 for i in range(1, n + 1)))
def square_of_sum(n):
return sum(range(1, n + 1)) ** 2 |
Credits = [
('Bootstrap', 'https://getbootstrap.com', 'The Bootstrap team', 'MIT'),
('Bottle', 'http://bottlepy.org', 'Marcel Hellkamp', 'MIT'),
('Cheroot', 'https://github.com/cherrypy/cheroot', 'CherryPy Team', 'BSD 3-Clause "New" or "Revised" License'),
('Click', 'https://github.com/pallets/click', '... | credits = [('Bootstrap', 'https://getbootstrap.com', 'The Bootstrap team', 'MIT'), ('Bottle', 'http://bottlepy.org', 'Marcel Hellkamp', 'MIT'), ('Cheroot', 'https://github.com/cherrypy/cheroot', 'CherryPy Team', 'BSD 3-Clause "New" or "Revised" License'), ('Click', 'https://github.com/pallets/click', 'Pallets', 'BSD 3-... |
def repleace_pattern(t,s,r):
assert len(t) > 0
assert len(s) > 0
assert len(r) > 0
assert len(t) >= len(s)
n = len(t)
m = len(s)
k = len(r)
idx = -1
for i in range(0, n):
if t[i] == s[0]:
pattern = True
for j in range(1,m):
... | def repleace_pattern(t, s, r):
assert len(t) > 0
assert len(s) > 0
assert len(r) > 0
assert len(t) >= len(s)
n = len(t)
m = len(s)
k = len(r)
idx = -1
for i in range(0, n):
if t[i] == s[0]:
pattern = True
for j in range(1, m):
if t[i + ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
x_depth = None
x_parent = None... | class Solution:
def is_cousins(self, root: TreeNode, x: int, y: int) -> bool:
x_depth = None
x_parent = None
x_found = 0
y_depth = None
y_parent = None
y_found = 0
def dfs(node, parent, depth):
nonlocal x_depth, x_parent, x_found, y_depth, y_foun... |
#
# Copyright (C) 2009 Mendix. All rights reserved.
#
SUCCESS = 0
# Starting the Mendix Runtime can fail in both a temporary or permanent way.
# Some of the errors can be fixed with some help of the user.
#
# The default m2ee cli program will only handle a few of these cases, by
# providing additional hints or intera... | success = 0
start_no_existing_db = 2
start_invalid_db_structure = 3
start_missing_mf_constant = 4
start_admin_1 = 5
start_invalid_state = 6
start_missing_dtap = 7
start_missing_basepath = 8
start_missing_runtimepath = 9
start_invalid_license = 10
start_security_disabled = 11
start_startup_action_failed = 12
start_no_mo... |
def count_words(sentence):
sentence = sentence.lower()
words = {}
shit = ',\n:!&@$%^&._'
for s in shit:
sentence = sentence.replace(s, ' ')
for w in sentence.split():
if w.endswith('\''):
w = w[:-1]
if w.startswith('\''):
w = w[1:]
words... | def count_words(sentence):
sentence = sentence.lower()
words = {}
shit = ',\n:!&@$%^&._'
for s in shit:
sentence = sentence.replace(s, ' ')
for w in sentence.split():
if w.endswith("'"):
w = w[:-1]
if w.startswith("'"):
w = w[1:]
words[w] = wor... |
ID = {"Worldwide":0,
"AF": 1,
"AL": 2,
"DZ": 3,
"AD": 5,
"AO": 6,
"AI": 7,
"AG": 9,
"AR": 10,
"AM": 11,
"AW": 12,
"AT": 14,
"AZ": 15,
"BS": 16,
"BH": 17,
"BD": 18,
"BB": 19,
"BY": 20,
"BZ": 22,
"BJ": 23,
... | id = {'Worldwide': 0, 'AF': 1, 'AL': 2, 'DZ': 3, 'AD': 5, 'AO': 6, 'AI': 7, 'AG': 9, 'AR': 10, 'AM': 11, 'AW': 12, 'AT': 14, 'AZ': 15, 'BS': 16, 'BH': 17, 'BD': 18, 'BB': 19, 'BY': 20, 'BZ': 22, 'BJ': 23, 'BM': 24, 'BO': 26, 'BA': 27, 'BW': 28, 'BV': 29, 'BR': 30, 'BN': 31, 'BG': 32, 'BF': 33, 'BI': 34, 'KH': 35, 'CM':... |
# In Search for the Lost Memory [Explorer Thief] (3526)
# To be replaced with GMS's exact dialogue.
# Following dialogue has been edited from DeepL on JMS's dialogue transcript (no KMS footage anywhere):
# https://kaengouraiu2.blog.fc2.com/blog-entry-46.html
recoveredMemory = 7081
darkLord = 1052001
sm.setSpeakerID(... | recovered_memory = 7081
dark_lord = 1052001
sm.setSpeakerID(darkLord)
sm.sendNext('The way you moved without a trace...you must have exceptional talent. Long time no see, #h #.')
sm.sendSay("Since when did you grow up to this point? You're no less inferior to any Dark Lord. You were just a greenhorn that couldn't even ... |
def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') | def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') |
def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
... | def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
VALID_HISTORY_FIELDS = [
'datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume',
'acc_net_value', 'discount_rate', 'unit_net_value',
'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement'
]
VALID_GET_PRICE_FI... | valid_history_fields = ['datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume', 'acc_net_value', 'discount_rate', 'unit_net_value', 'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement']
valid_get_price_fields = ['OpeningPx', 'ClosingPx', 'HighPx', 'LowPx', 'TotalTur... |
# unicode digit emojis
# digits from '0' to '9'
zero_digit_code = zd = 48
# excluded digits
excl_digits = [2, 4, 5, 7]
# unicode digit keycap
udkc = '\U0000fe0f\U000020e3'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10)
if i - zd not in excl_digits]
# number '10' emoji
hours_0_9.append('\U0001f51f')
# ... | zero_digit_code = zd = 48
excl_digits = [2, 4, 5, 7]
udkc = '️⃣'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10) if i - zd not in excl_digits]
hours_0_9.append('🔟')
hours_11_23 = [str(i) for i in range(11, 24)]
vote = ('PLUS', 'MINUS')
edit = '📝' |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix: return 0
m, n = len(matrix), len(matrix[0])
dp = [[0]*n for _ in range(m)]
res = 0
for i in range(m):
dp[i][0] = int(matrix[i][0])
for j in range(n):
dp[0][... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
(m, n) = (len(matrix), len(matrix[0]))
dp = [[0] * n for _ in range(m)]
res = 0
for i in range(m):
dp[i][0] = int(matrix[i][0])
for j in range(n)... |
class term(object):
# Dados de cadastro das usinas termeletrica (presentes no TERM.DAT)
Codigo = None
Nome = None
Potencia = None
FCMax = None
TEIF = None
IP = None
GTMin = None
# Dados Adicionais Especificados no arquivo de configuracao termica (CONFT)
Sist = None
Status = ... | class Term(object):
codigo = None
nome = None
potencia = None
fc_max = None
teif = None
ip = None
gt_min = None
sist = None
status = None
classe = None
custo = None
nome_classe = None
tipo_comb = None
def insere(self, custo, gmax):
self.custo = custo
... |
# This is a simple program to find the last three digits of 11 raised to any given number.
# The main algorithm that does the work is on line 10
def trim_num(num):
if len(str(num)) > 3: # no need to trim if the number is 3 or less digits long
return str(num)[(len(str(num)) - 3):] # trims the number
ret... | def trim_num(num):
if len(str(num)) > 3:
return str(num)[len(str(num)) - 3:]
return num
def main(exp):
init_val = str((exp - 1) * exp / 2 % 10 + exp % 100 / 10) + str(exp % 10) + '1'
return '{}'.format(trim_num(init_val)) |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = test_episodes # train, test, test_episodes, render
NUM_EPISODES_TO_TEST = 1000
MIN_FINAL_REWARD_FOR_SUCCESS = 1.0
LOAD_MODEL_FROM = models/gru_flat_babyai.pth
SAVE_MODELS_TO = None
# wo... | type_of_run = test_episodes
num_episodes_to_test = 1000
min_final_reward_for_success = 1.0
load_model_from = models / gru_flat_babyai.pth
save_models_to = None
env = BabyAI_Env
env_random_seed = 1
agent_random_seed = 1
reporting_interval = 1
total_steps = 1
anneal_lr = False
agent_net = GRU_Network
babyai_env_level = B... |
ezan = {
'name': 'ezan',
'age': 18,
'hair': 'brown',
'cool': True ,
}
print(ezan)
class Person(object): #use class to make object
def __init__(
self, name, age ,hair, color, hungry) : #initialize
#first object inside of a class is self
self.name = 'ezan'
self.age = 18
... | ezan = {'name': 'ezan', 'age': 18, 'hair': 'brown', 'cool': True}
print(ezan)
class Person(object):
def __init__(self, name, age, hair, color, hungry):
self.name = 'ezan'
self.age = 18
self.hair = 'brown'
self.cool = True
def eat(self, food):
print('EAT {f}'.format(f=f... |
# # Simple Tuple
# fruits = ('Apple', 'Orange', 'Mango')
# # Using Constructor
# fruits = tuple(('Apple', 'Orange', 'Mango'))
# # Getting a Single Value
# print(fruits[1])
# Trying to change based on position
# fruits[1] = 'Grape'
# Tuples with one value should have trailing comma
# fruits = ('Apple')
# fruits = ('... | fruits = {'Apple', 'Orange', 'Mango', 'Apple'}
print('Apple' in fruits)
fruits.add('Grape')
fruits.remove('Grape')
fruits.clear()
del fruits
print(fruits) |
description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
dct1 = device('nicos.devices.entangle.PowerSupply',
description = 'current in first channel of supply (flipper current)',
tangodevice = tango_base + 't... | description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(dct1=device('nicos.devices.entangle.PowerSupply', description='current in first channel of supply (flipper current)', tangodevice=tango_base + 'tti1/out1', timeout=1, precisi... |
class Stack:
def __init__(self):
self.stack = []
self.minMaxStack = []
# O(1) time | O(1) space
def peek(self):
if (len(self.stack)):
return self.stack[-1]
return None
# O(1) time | O(1) space
def pop(self):
if (len(self.stack)):
sel... | class Stack:
def __init__(self):
self.stack = []
self.minMaxStack = []
def peek(self):
if len(self.stack):
return self.stack[-1]
return None
def pop(self):
if len(self.stack):
self.minMaxStack.pop()
return self.stack.pop()
... |
BIG_CONSTANT = "YES"
def group_by(xs, grouper):
groups = {}
for x in xs:
group = grouper(x)
if group not in groups:
groups[group] = []
groups[group].append(x)
return groups
print(group_by([1, 2, 3, 4, 5, 6], lambda x: "even" if x % 2 == 0 else "odd"))
| big_constant = 'YES'
def group_by(xs, grouper):
groups = {}
for x in xs:
group = grouper(x)
if group not in groups:
groups[group] = []
groups[group].append(x)
return groups
print(group_by([1, 2, 3, 4, 5, 6], lambda x: 'even' if x % 2 == 0 else 'odd')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.