content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
This is the rank system based on the regression model we built
"""
def survival_score(timeSurvived, duration, winPlace):
"""
survival_score = 80% * survival time score + 20% * win place score
: type timeSurvived: int -- participant time survived
: type duration: int -- match duration time
: type winPlace: ... | """
This is the rank system based on the regression model we built
"""
def survival_score(timeSurvived, duration, winPlace):
"""
survival_score = 80% * survival time score + 20% * win place score
: type timeSurvived: int -- participant time survived
: type duration: int -- match duration time
: type winPlace... |
a=input().split(" ")
b=input().split(" ")
A=0
B=0
for i in range(len(a)):
num1=int(a[i])
num2=int(b[i])
if(num1>num2):
A+=1
elif(num1<num2):
B+=1
print(A, B)
| a = input().split(' ')
b = input().split(' ')
a = 0
b = 0
for i in range(len(a)):
num1 = int(a[i])
num2 = int(b[i])
if num1 > num2:
a += 1
elif num1 < num2:
b += 1
print(A, B) |
# app config
APP_CONFIG=dict(
SECRET_KEY="SECRET",
WTF_CSRF_SECRET_KEY="SECRET",
# Webservice config
WS_URL="http://localhost:5058", # ws del modello in locale
DATASET_REQ = "/dataset",
OPERATIVE_CENTERS_REQ = "/operative-centers",
OC_DATE_REQ = "/oc-date",
OC_DATA_REQ = "/oc-data",
PREDICT_REQ = "/p... | app_config = dict(SECRET_KEY='SECRET', WTF_CSRF_SECRET_KEY='SECRET', WS_URL='http://localhost:5058', DATASET_REQ='/dataset', OPERATIVE_CENTERS_REQ='/operative-centers', OC_DATE_REQ='/oc-date', OC_DATA_REQ='/oc-data', PREDICT_REQ='/predict', OPERATORS_RANK_REQ='/ops-rank/', SEND_REAL_Y_REQ='/store-real-y/', SEND_LOGIN_R... |
#encoding:utf-8
subreddit = 'mildlyvagina'
t_channel = '@r_mildlyvagina'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'mildlyvagina'
t_channel = '@r_mildlyvagina'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
num1, num2 = list(map(int, input().split()))
if num1 < num2:
print(num1, num2)
else:
print(num2, num1)
| (num1, num2) = list(map(int, input().split()))
if num1 < num2:
print(num1, num2)
else:
print(num2, num1) |
#!/usr/bin/env python3.4
# coding: utf-8
class MixinMeta(type):
"""
Abstract mixin metaclass.
"""
| class Mixinmeta(type):
"""
Abstract mixin metaclass.
""" |
def main():
print('Hola, mundo')
if __name__ =='__main__':
main()
| def main():
print('Hola, mundo')
if __name__ == '__main__':
main() |
env = None
pg = None
surface = None
width = None
height = None
# __pragma__ ('opov')
def init(environ):
global env, pg, surface, width, height
env = environ
pg = env['pg']
surface = env['surface']
width = env['width']
height = env['height']
tests = [test_transform_rotate,
te... | env = None
pg = None
surface = None
width = None
height = None
def init(environ):
global env, pg, surface, width, height
env = environ
pg = env['pg']
surface = env['surface']
width = env['width']
height = env['height']
tests = [test_transform_rotate, test_transform_rotozoom, test_transform_... |
__author__ = 'vcaen'
class Item(object):
def __init__(self, title, short_desc, desc, picture):
self.title = title
self.short_desc = short_desc
self.desc = desc
self.picture = picture
class Work(Item):
def __init__(self, title, short_desc, desc, date_begin, date_end, company... | __author__ = 'vcaen'
class Item(object):
def __init__(self, title, short_desc, desc, picture):
self.title = title
self.short_desc = short_desc
self.desc = desc
self.picture = picture
class Work(Item):
def __init__(self, title, short_desc, desc, date_begin, date_end, company, ... |
# https://leetcode.com/problems/counting-words-with-a-given-prefix/
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
res = 0
for each in words:
if len(each) >= len(pref):
if each[:len(pref)] == pref:
res += ... | class Solution:
def prefix_count(self, words: List[str], pref: str) -> int:
res = 0
for each in words:
if len(each) >= len(pref):
if each[:len(pref)] == pref:
res += 1
return res |
class RollingHash:
def __init__(self, text, pattern_size):
self.text = text
self.pattern_size = pattern_size
self.hash = RollingHash.hash_text(text, pattern_size)
self.start = 0
self.end = pattern_size
self.alphabet = 26
def move_window(self):
if self.end... | class Rollinghash:
def __init__(self, text, pattern_size):
self.text = text
self.pattern_size = pattern_size
self.hash = RollingHash.hash_text(text, pattern_size)
self.start = 0
self.end = pattern_size
self.alphabet = 26
def move_window(self):
if self.en... |
class ImageAdapter:
@staticmethod
def to_network_input(dataset):
return (dataset - 127.5) / 127.5
@staticmethod
def to_image(normalized_images):
images = normalized_images * 127.5 + 127.5
return images.astype(int)
| class Imageadapter:
@staticmethod
def to_network_input(dataset):
return (dataset - 127.5) / 127.5
@staticmethod
def to_image(normalized_images):
images = normalized_images * 127.5 + 127.5
return images.astype(int) |
BULBASAUR = 0x01
IVYSAUR = 0x02
VENUSAUR = 0x03
CHARMANDER = 0x04
CHARMELEON = 0x05
CHARIZARD = 0x06
SQUIRTLE = 0x07
WARTORTLE = 0x08
BLASTOISE = 0x09
CATERPIE = 0x0a
METAPOD = 0x0b
BUTTERFREE = 0x0c
WEEDLE = 0x0d
KAKUNA = 0x0e
BEEDRILL = 0x0f
PIDGEY = 0x10
PIDGEOTTO = 0x11
PIDGEOT = 0... | bulbasaur = 1
ivysaur = 2
venusaur = 3
charmander = 4
charmeleon = 5
charizard = 6
squirtle = 7
wartortle = 8
blastoise = 9
caterpie = 10
metapod = 11
butterfree = 12
weedle = 13
kakuna = 14
beedrill = 15
pidgey = 16
pidgeotto = 17
pidgeot = 18
rattata = 19
raticate = 20
spearow = 21
fearow = 22
ekans = 23
arbok = 24
p... |
class Solution:
"""
@param num: an integer
@return: the complement number
"""
def findComplement(self, num):
ans = 0
digit = 1
while num > 0:
ans += abs(num % 2 - 1) * digit
num //= 2
digit *= 2
return ans
| class Solution:
"""
@param num: an integer
@return: the complement number
"""
def find_complement(self, num):
ans = 0
digit = 1
while num > 0:
ans += abs(num % 2 - 1) * digit
num //= 2
digit *= 2
return ans |
# -*- coding: utf-8 -*-
class Exchange(object):
"""docstring for Exchange"""
def __init__(self):
self.trades = False
def getTrades(self):
return self.trades
# @abstractmethod
def calcTotal(self, controller):
pass
| class Exchange(object):
"""docstring for Exchange"""
def __init__(self):
self.trades = False
def get_trades(self):
return self.trades
def calc_total(self, controller):
pass |
# -*- coding: utf-8 -*-
# author: Minch Wu
"""RECUR.PY.
define some functions in recursive process
"""
def hanoi(n: int, L=None):
"""hanoi.
storage the move process
"""
if L is None:
L = []
def move(n, a='A', b='B', c='C'):
"""move.
move the pagoda
"""
i... | """RECUR.PY.
define some functions in recursive process
"""
def hanoi(n: int, L=None):
"""hanoi.
storage the move process
"""
if L is None:
l = []
def move(n, a='A', b='B', c='C'):
"""move.
move the pagoda
"""
if n == 1:
L.append(a + '->' + c)... |
input()
A = {int(param) for param in input().split()}
B = {int(param) for param in input().split()}
print(len(A-B))
for i in sorted(A-B):
print(i, end = ' ')
| input()
a = {int(param) for param in input().split()}
b = {int(param) for param in input().split()}
print(len(A - B))
for i in sorted(A - B):
print(i, end=' ') |
languages = ['Chamorro', 'Tagalog', 'English', 'russian']
print(languages)
languages.append('Spanish')
print(languages)
languages.insert(0, 'Finish')
print(languages)
del languages[0]
print(languages)
popped_language = languages.pop(0)
print(languages)
print(popped_language)
popped_language = languages.pop(0)
prin... | languages = ['Chamorro', 'Tagalog', 'English', 'russian']
print(languages)
languages.append('Spanish')
print(languages)
languages.insert(0, 'Finish')
print(languages)
del languages[0]
print(languages)
popped_language = languages.pop(0)
print(languages)
print(popped_language)
popped_language = languages.pop(0)
print(lan... |
'''
Created on Oct 5, 2011
@author: IslamM
'''
| """
Created on Oct 5, 2011
@author: IslamM
""" |
"""
Given a string and a set of characters, return the shortest substring containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
no_of_chars ... | """
Given a string and a set of characters, return the shortest substring containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
no_of_chars =... |
SOURCES = {
"activity.task.error.generic": "CommCareAndroid",
"app.handled.error.explanation": "CommCareAndroid",
"app.handled.error.title": "CommCareAndroid",
"app.key.request.deny": "CommCareAndroid",
"app.key.request.grant": "CommCareAndroid",
"app.key.request.message": "CommCareAndroid",
... | sources = {'activity.task.error.generic': 'CommCareAndroid', 'app.handled.error.explanation': 'CommCareAndroid', 'app.handled.error.title': 'CommCareAndroid', 'app.key.request.deny': 'CommCareAndroid', 'app.key.request.grant': 'CommCareAndroid', 'app.key.request.message': 'CommCareAndroid', 'app.menu.display.cond.bad.x... |
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
targetSum -= root.val
if targetSum == 0:
if (root.left is None) and (root.right is None):
return True
return self.has... | class Solution:
def has_path_sum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
target_sum -= root.val
if targetSum == 0:
if root.left is None and root.right is None:
return True
return self.hasPathSum(r... |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Date: 2018-06-27 23:59:30
# @Last Modified by: jpch89
# @Last Modified time: 2018-06-28 00:02:38
formatter = '{} {} {} {}'
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(Tru... | formatter = '{} {} {} {}'
print(formatter.format(1, 2, 3, 4))
print(formatter.format('one', 'two', 'three', 'four'))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format('Try your', 'Own text here', 'Maybe a peom', 'Or a song about ... |
'''2. Write a Python program to compute the similarity between two lists.
Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"]
Expected Output:
Color1-Color2: ['white', 'orange', 'red']
Color2-Color1: ['black', 'yellow'] '''
def find_similiarity(list1, list2):
list3 = lis... | """2. Write a Python program to compute the similarity between two lists.
Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"]
Expected Output:
Color1-Color2: ['white', 'orange', 'red']
Color2-Color1: ['black', 'yellow'] """
def find_similiarity(list1, list2):
list3 = lis... |
def get_client_ip(request):
client_ip = request.META.get('REMOTE_ADDR', '')
return client_ip
| def get_client_ip(request):
client_ip = request.META.get('REMOTE_ADDR', '')
return client_ip |
url = "https://customerportal.supermicro.com/Customer/ContentPages/CustOrders.aspx"
orderType = "//select[@id='ContentPlaceHolder1_ddlSearchType']"
fromDate = "//input[@id='ContentPlaceHolder1_txtFrom']"
customerId = "//select[@id='ContentPlaceHolder1_ddlCustomerID']"
searchIcon = "//a[@id='linkSearch']"
orderTable = "... | url = 'https://customerportal.supermicro.com/Customer/ContentPages/CustOrders.aspx'
order_type = "//select[@id='ContentPlaceHolder1_ddlSearchType']"
from_date = "//input[@id='ContentPlaceHolder1_txtFrom']"
customer_id = "//select[@id='ContentPlaceHolder1_ddlCustomerID']"
search_icon = "//a[@id='linkSearch']"
order_tabl... |
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
dp = [0]*n
for i,j,k in bookings:
dp[i-1]+=k
if j!=n:
dp[j]-=k
for i in range(1,n):
dp[i]+=dp[i-1]
return dp | class Solution:
def corp_flight_bookings(self, bookings: List[List[int]], n: int) -> List[int]:
dp = [0] * n
for (i, j, k) in bookings:
dp[i - 1] += k
if j != n:
dp[j] -= k
for i in range(1, n):
dp[i] += dp[i - 1]
return dp |
def buildFibonacciSequence(items):
actual = 0
next = 1
sequence = []
for index in range(items):
sequence.append(actual)
actual, next = next, actual+next
return sequence
| def build_fibonacci_sequence(items):
actual = 0
next = 1
sequence = []
for index in range(items):
sequence.append(actual)
(actual, next) = (next, actual + next)
return sequence |
"""
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero
or more conversions.
In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
Return true if and only if you can transform str1 into str2... | """
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero
or more conversions.
In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
Return true if and only if you can transform str1 into str2... |
class Animation:
def __init__(self, sprites, time_interval):
self.sprites = tuple(sprites)
self.time_interval = time_interval
self.index = 0
self.time = 0
def restart_at(self, index):
self.time = 0
self.index = index % len(self.sprites)
def update(self, dt)... | class Animation:
def __init__(self, sprites, time_interval):
self.sprites = tuple(sprites)
self.time_interval = time_interval
self.index = 0
self.time = 0
def restart_at(self, index):
self.time = 0
self.index = index % len(self.sprites)
def update(self, dt)... |
NoOfLines=int(input())
for Row in range(0,NoOfLines):
for Column in range(0,NoOfLines):
if(Row%2==0 and Column+1==NoOfLines)or(Row%2==1 and Column==0):
print("%2d"%(Row+2),end=" ")
else:
print("%2d"%(Row+1),end=" ")
else:
print(end="\n")
#second code
N... | no_of_lines = int(input())
for row in range(0, NoOfLines):
for column in range(0, NoOfLines):
if Row % 2 == 0 and Column + 1 == NoOfLines or (Row % 2 == 1 and Column == 0):
print('%2d' % (Row + 2), end=' ')
else:
print('%2d' % (Row + 1), end=' ')
else:
print(end='... |
# Module: FeatureEngineering
# Author: Adrian Antico <adrianantico@gmail.com>
# License: MIT
# Release: retrofit 0.1.7
# Last modified : 2021-09-21
class FeatureEngineering:
"""
Base class that the library specific classes inherit from.
"""
def __init__(self) -> None:
self.lag_args = {}
... | class Featureengineering:
"""
Base class that the library specific classes inherit from.
"""
def __init__(self) -> None:
self.lag_args = {}
self.roll_args = {}
self.diff_args = {}
self.calendar_args = {}
self.dummy_args = {}
self.model_data_prep_args = {}... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
def get_workspace_dependent_resource_location(location):
if location == "centraluseuap":
return "eastus"
return lo... | def get_workspace_dependent_resource_location(location):
if location == 'centraluseuap':
return 'eastus'
return location |
# 1.5 One Away
# There are three types of edits that can be performed on strings:
# insert a character, remove a character, or replace a character.
# Given two strings, write a function to check if they are one edit (or zero edits) away.
def one_away(string_1, string_2):
if string_1 == string_2:
return ... | def one_away(string_1, string_2):
if string_1 == string_2:
return True
if one_insert_away(string_1, string_2):
return True
if one_removal_away(string_1, string_2):
return True
if one_replacement_away(string_1, string_2):
return True
return False
def one_insert_away(s... |
def permune(orignal, chosen):
if not orignal:
print(chosen)
else:
for i in range(len(orignal)):
c=orignal[i]
chosen+=c
lt=list(orignal)
lt.pop(i)
orignal=''.join(lt)
permune(orignal,chosen)
orignal=orignal[:i]+c+orignal[i:]
chosen=chosen[:len(chosen)-1]
permune('lit','') | def permune(orignal, chosen):
if not orignal:
print(chosen)
else:
for i in range(len(orignal)):
c = orignal[i]
chosen += c
lt = list(orignal)
lt.pop(i)
orignal = ''.join(lt)
permune(orignal, chosen)
orignal = ori... |
entity_id = 'sensor.next_train_to_wim'
attributes = hass.states.get(entity_id).attributes
my_early_train_current_status = hass.states.get('sensor.my_early_train').state
scheduled = False # Check if train scheduled
for train in attributes['next_trains']:
if train['scheduled'] == '07:15':
scheduled = Tru... | entity_id = 'sensor.next_train_to_wim'
attributes = hass.states.get(entity_id).attributes
my_early_train_current_status = hass.states.get('sensor.my_early_train').state
scheduled = False
for train in attributes['next_trains']:
if train['scheduled'] == '07:15':
scheduled = True
if train['status'] != ... |
# ------------------------------
# 300. Longest Increasing Subsequence
#
# Description:
# Given an unsorted array of integers, find the length of longest increasing subsequence.
#
# Example:
# Input: [10,9,2,5,3,7,101,18]
# Output: 4
# Explanation: The longest increasing subsequence is [2,3,7,101], therefore the len... | class Solution:
def length_of_lis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [1]
max_len = 1
for i in range(1, len(nums)):
maxval = 0
for j in range(0, i):
if n... |
class Node:
def __init__(self,key=None,val=None,nxt=None,prev=None):
self.key = key
self.val = val
self.nxt = nxt
self.prev = prev
class DLL:
def __init__(self):
self.head = Node()
self.tail = Node()
self.head.nxt = self.tail
self.tail.prev = self... | class Node:
def __init__(self, key=None, val=None, nxt=None, prev=None):
self.key = key
self.val = val
self.nxt = nxt
self.prev = prev
class Dll:
def __init__(self):
self.head = node()
self.tail = node()
self.head.nxt = self.tail
self.tail.prev ... |
class Command(object):
def get_option(self, name):
pass
def run(self, ):
raise NotImplementedError
| class Command(object):
def get_option(self, name):
pass
def run(self):
raise NotImplementedError |
a, b, c, d = map(int, input().split())
if a+b > c+d:
print("Left")
elif a+b < c+d:
print("Right")
else:
print("Balanced")
| (a, b, c, d) = map(int, input().split())
if a + b > c + d:
print('Left')
elif a + b < c + d:
print('Right')
else:
print('Balanced') |
# pyre-ignore-all-errors
# TODO: Change `pyre-ignore-all-errors` to `pyre-strict` on line 1, so we get
# to see all type errors in this file.
# A (hypothetical) Python developer is having trouble with a typing-related
# issue. Here is what the code looks like:
class ConfigA:
pass
class ConfigB:
some_attri... | class Configa:
pass
class Configb:
some_attribute: int = 1
class Helperbase:
def __init__(self, config: ConfigA | ConfigB) -> None:
self.config = config
def common_fn(self) -> None:
pass
class Helpera(HelperBase):
def __init__(self, config: ConfigA) -> None:
super().__i... |
""" Euclid's algorithm """
def modinv(a0, n0):
""" Modular inverse algorithm """
(a, b) = (a0, n0)
(aa, ba) = (1, 0)
while True:
q = a // b
if a == (b * q):
if b != 1:
print("modinv({}, {}) = fail".format(a0, n0))
return -1
else:
... | """ Euclid's algorithm """
def modinv(a0, n0):
""" Modular inverse algorithm """
(a, b) = (a0, n0)
(aa, ba) = (1, 0)
while True:
q = a // b
if a == b * q:
if b != 1:
print('modinv({}, {}) = fail'.format(a0, n0))
return -1
else:
... |
#
# PySNMP MIB module CISCO-LWAPP-LOCAL-AUTH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-LOCAL-AUTH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:48:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class Human:
def method(self):
return print(f'Hello - {self}')
@classmethod
def classmethod(cls):
return print('it is a species of "Homo sapiens"')
@staticmethod
def staticmethod():
return print('Congratulations')
name_human = input('Enter your name: ')
Human.method(na... | class Human:
def method(self):
return print(f'Hello - {self}')
@classmethod
def classmethod(cls):
return print('it is a species of "Homo sapiens"')
@staticmethod
def staticmethod():
return print('Congratulations')
name_human = input('Enter your name: ')
Human.method(name_h... |
"""
Created on Oct 13, 2019
@author: majdukovic
"""
class UrlGenerator:
"""
This class builds urls
"""
def __init__(self):
self.urls_map = {
'POST_TOKEN': 'auth',
'GET_BOOKING': 'booking',
'POST_BOOKING': 'booking',
'PUT_BOOKING': 'booking',
... | """
Created on Oct 13, 2019
@author: majdukovic
"""
class Urlgenerator:
"""
This class builds urls
"""
def __init__(self):
self.urls_map = {'POST_TOKEN': 'auth', 'GET_BOOKING': 'booking', 'POST_BOOKING': 'booking', 'PUT_BOOKING': 'booking', 'PATCH_BOOKING': 'booking', 'DELETE_BOOKING': 'booki... |
"""
Views for the admin interface
"""
def includeme(config):
config.scan("admin.views")
| """
Views for the admin interface
"""
def includeme(config):
config.scan('admin.views') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
SUCCESS = "0"
NEED_SMS = "1"
SMS_FAIL = "2"
| success = '0'
need_sms = '1'
sms_fail = '2' |
#Vigenere cipher + b64 - substitution
'''
method = sys.argv[1]
key = sys.argv[2]
string = sys.argv[3]
'''
def encode(key, string) :
encoded_chars = []
for i in range(len(string)) :
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
encoded_chars.append(encoded... | """
method = sys.argv[1]
key = sys.argv[2]
string = sys.argv[3]
"""
def encode(key, string):
encoded_chars = []
for i in range(len(string)):
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
encoded_chars.append(encoded_c)
encoded_string = ''.join(encoded_... |
"""TCS module"""
#def hello(who):
# """function that greats"""
# return "hello " + who
def tcs(d):
"""TCS test function"""
return d
| """TCS module"""
def tcs(d):
"""TCS test function"""
return d |
def ForceDefaultLocale(get_response):
"""
Ignore Accept-Language HTTP headers
This will force the I18N machinery to always choose settings.LANGUAGE_CODE
as the default initial language, unless another one is set via sessions or cookies
Should be installed *before* any middleware that check... | def force_default_locale(get_response):
"""
Ignore Accept-Language HTTP headers
This will force the I18N machinery to always choose settings.LANGUAGE_CODE
as the default initial language, unless another one is set via sessions or cookies
Should be installed *before* any middleware that che... |
def mult_by_two(num):
return num * 2
def mult_by_five(num):
return num * 5
def square(num):
return num * num
def add_one(num):
return num + 1
def apply(num, func):
return func(num)
result = apply(10, mult_by_two)
print(result)
print(apply(10, mult_by_five))
print(apply(10, square))
print(... | def mult_by_two(num):
return num * 2
def mult_by_five(num):
return num * 5
def square(num):
return num * num
def add_one(num):
return num + 1
def apply(num, func):
return func(num)
result = apply(10, mult_by_two)
print(result)
print(apply(10, mult_by_five))
print(apply(10, square))
print(apply(1... |
class BisectionMap(object):
__slots__ = ('nodes')
#//-------------------------------------------------------//
def __init__(self, dict = {} ):
self.nodes = []
for key, value in dict.iteritems():
self[ key ] = value
#//----------------------------... | class Bisectionmap(object):
__slots__ = 'nodes'
def __init__(self, dict={}):
self.nodes = []
for (key, value) in dict.iteritems():
self[key] = value
def __find_position(self, key):
nodes = self.nodes
pos = 0
end = len(nodes)
while pos < end:
... |
# YASS, Yet Another Subdomainer Software
# Copyright 2015-2019 Francesco Marano (@mrnfrancesco) and individual contributors.
#
# 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.apa... | def without_duplicates(args):
"""
Removes duplicated items from an iterable.
:param args: the iterable to remove duplicates from
:type args: iterable
:return: the same iterable without duplicated items
:rtype: iterable
:raise TypeError: if *args* is not iterable
"""
if hasattr(args,... |
# Copyright 2017 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... | """Support functions used when processing resources in Apple bundles."""
load('@bazel_skylib//lib:paths.bzl', 'paths')
def _bundle_relative_path(f):
"""Returns the portion of `f`'s path relative to its containing `.bundle`.
This function fails if `f` does not have an ancestor directory named with the
`.bundle... |
# -*- coding: utf-8 -*-
test = 0
while True:
test += 1
deposits = int(input())
if deposits == 0:
break
delta = 0
print("Teste %d" % test)
for i in range(deposits):
values = input().split()
a = int(values[0])
b = int(values[1])
delta += a - b
... | test = 0
while True:
test += 1
deposits = int(input())
if deposits == 0:
break
delta = 0
print('Teste %d' % test)
for i in range(deposits):
values = input().split()
a = int(values[0])
b = int(values[1])
delta += a - b
print(delta)
print('') |
#LEETOCDE: 104. Maximum Depth of Binary Tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def maxDepth(root: TreeNode) -> int:
if not root: return 0
else: return max(1+maxDepth(root.left), 1+maxDepth(root.right))
#TODO: Implement iterativ... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def max_depth(root: TreeNode) -> int:
if not root:
return 0
else:
return max(1 + max_depth(root.left), 1 + max_depth(root.right))
def max_depth_ii(root: TreeNode) -> int:
pri... |
# Definition for a binary tree node.
# from typing import List
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def solve(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder:
r... | class Solution:
def solve(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder:
return None
root = tree_node(preorder[0])
if len(inorder) == 1:
return root
root_idx_inorder = inorder.index(preorder[0])
lchild = self.solve(preord... |
# sorting algorithms
# mergeSort
def merge_sort(a):
n = len(a)
if n < 2:
return a
q = int(n / 2)
left = a[:q]
right = a[q:]
# print("left : {%s} , right : {%s}, A : {%s}" % (left, right, a))
merge_sort(left)
merge_sort(right)
a = merge(a, left, right)
# print("Result ... | def merge_sort(a):
n = len(a)
if n < 2:
return a
q = int(n / 2)
left = a[:q]
right = a[q:]
merge_sort(left)
merge_sort(right)
a = merge(a, left, right)
return a
def merge(a, left, right):
l = len(left)
r = len(right)
(i, j, k) = (0, 0, 0)
while i < l and j < ... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"file_exists": "01_data.ipynb",
"ds_file_exists": "01_data.ipynb",
"filter_for_exists": "01_data.ipynb",
"drop_missing_files": "01_data.ipynb",
"add_ds": "01_data.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'file_exists': '01_data.ipynb', 'ds_file_exists': '01_data.ipynb', 'filter_for_exists': '01_data.ipynb', 'drop_missing_files': '01_data.ipynb', 'add_ds': '01_data.ipynb', 'merge_ds': '01_data.ipynb', 'remove_special_characters': '01_data.ipynb', 'ch... |
# Copyright 2021 Jason Rumney
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | domain = 'metlink'
attribution = 'Data provided by Greater Wellington Regional Council'
conf_stops = 'stops'
conf_stop_id = 'stop_id'
conf_dest = 'destination'
conf_route = 'route'
conf_num_departures = 'num_departures'
attr_accessible = 'wheelchair_accessible'
attr_aimed = 'aimed'
attr_arrival = 'arrival'
attr_closed ... |
def cria_matriz(linhas, colunas, valor):
matriz = []
for i in range(linhas):
lin = []
for j in range(colunas):
lin.append(valor)
matriz.append(lin)
return matriz
def le_matriz():
linhas = int(input("Digite a quantidade de linhas: "))
colunas = int(input("Digite a qu... | def cria_matriz(linhas, colunas, valor):
matriz = []
for i in range(linhas):
lin = []
for j in range(colunas):
lin.append(valor)
matriz.append(lin)
return matriz
def le_matriz():
linhas = int(input('Digite a quantidade de linhas: '))
colunas = int(input('Digite a... |
ELECTION_HOME="election@home"
ELECTION_VIEW="election@view"
ELECTION_META="election@meta"
ELECTION_EDIT="election@edit"
ELECTION_SCHEDULE="election@schedule"
ELECTION_EXTEND="election@extend"
ELECTION_ARCHIVE="election@archive"
ELECTION_COPY="election@copy"
ELECTION_BADGE="election@badge"
ELECTION_TRUSTEES_HOME="elect... | election_home = 'election@home'
election_view = 'election@view'
election_meta = 'election@meta'
election_edit = 'election@edit'
election_schedule = 'election@schedule'
election_extend = 'election@extend'
election_archive = 'election@archive'
election_copy = 'election@copy'
election_badge = 'election@badge'
election_tru... |
class IdentifierLabels:
ID = "CMPLNT_NUM"
class DateTimeEventLabels:
EVENT_START_TIMESTAMP = "CMPLNT_FR_DT"
EVENT_END_TIMESTAMP = "CMPLNT_TO_DT"
class DateTimeSubmissionLabels:
SUBMISSION_TO_POLICE_TIMESTAMP = "RPT_DT"
class LawBreakingLabels:
KEY_CODE = "KY_CD"
PD_CODE = "PD_CD"
LAW_B... | class Identifierlabels:
id = 'CMPLNT_NUM'
class Datetimeeventlabels:
event_start_timestamp = 'CMPLNT_FR_DT'
event_end_timestamp = 'CMPLNT_TO_DT'
class Datetimesubmissionlabels:
submission_to_police_timestamp = 'RPT_DT'
class Lawbreakinglabels:
key_code = 'KY_CD'
pd_code = 'PD_CD'
law_brea... |
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A) <= 2:
return len(A)
ans = 2
dp = collections.defaultdict(set)
for i, num in enumerate(A):
if num in dp:
for d, cnt in dp.pop(num):
dp[num + d].a... | class Solution:
def longest_arith_seq_length(self, A: List[int]) -> int:
if len(A) <= 2:
return len(A)
ans = 2
dp = collections.defaultdict(set)
for (i, num) in enumerate(A):
if num in dp:
for (d, cnt) in dp.pop(num):
dp[nu... |
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
for i1 in range(H):
for i2 in range(i1 + 1, H):
for j1 in range(W):
for j2 in range(j1 + 1, W):
if A[i1][j1] + A[i2][j2] > A[i2][j1] + A[i1][j2]:
print('No')
... | (h, w) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(H)]
for i1 in range(H):
for i2 in range(i1 + 1, H):
for j1 in range(W):
for j2 in range(j1 + 1, W):
if A[i1][j1] + A[i2][j2] > A[i2][j1] + A[i1][j2]:
print('No')
... |
# s.remove(0)
s = {1, 2, 3}
s.remove(0)
print(s)
# bug as it should return a KeyError exception !!!
| s = {1, 2, 3}
s.remove(0)
print(s) |
class Contacts:
def __init__(self, first_name=None, last_name=None, id=None, email_1=None, email_2=None, email_3=None,
home_phone=None, mobile_phone=None, work_phone=None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone
self... | class Contacts:
def __init__(self, first_name=None, last_name=None, id=None, email_1=None, email_2=None, email_3=None, home_phone=None, mobile_phone=None, work_phone=None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone
self.home_phone = hom... |
"""
CRUD system for Task
Create, Read, Update, Delete
"""
# Create Task
def create_task():
"""
Create a task into the database
""" | """
CRUD system for Task
Create, Read, Update, Delete
"""
def create_task():
"""
Create a task into the database
""" |
'''
The rows of levels in the .azr file are converted to list of strings. These
indices make it more convenient to access the desired parameter.
'''
J_INDEX = 0
PI_INDEX = 1
ENERGY_INDEX = 2
ENERGY_FIXED_INDEX = 3
CHANNEL_INDEX = 5
WIDTH_INDEX = 11
WIDTH_FIXED_INDEX = 10
SEPARATION_ENERGY_INDEX = 21
CHANNEL_RADIUS_INDE... | """
The rows of levels in the .azr file are converted to list of strings. These
indices make it more convenient to access the desired parameter.
"""
j_index = 0
pi_index = 1
energy_index = 2
energy_fixed_index = 3
channel_index = 5
width_index = 11
width_fixed_index = 10
separation_energy_index = 21
channel_radius_inde... |
class ModelMinxi:
def to_dict(self,*exclude):
attr_dict = {}
for field in self._meta.fields:
name = field.attname
if name not in exclude:
attr_dict[name] = getattr(self,name)
return attr_dict | class Modelminxi:
def to_dict(self, *exclude):
attr_dict = {}
for field in self._meta.fields:
name = field.attname
if name not in exclude:
attr_dict[name] = getattr(self, name)
return attr_dict |
"""
**********
LESSON 1A
**********
In the following code (lines 12-17), change x to 10, and then print out whether
or not x is 10.
"""
x = 5
if x == 5:
print("x is five!")
else:
print("x is not five...")
"""
Expected solution:
x = 10
if x == 10:
print("x is ten!")
else:
print("x is not ten..."... | """
**********
LESSON 1A
**********
In the following code (lines 12-17), change x to 10, and then print out whether
or not x is 10.
"""
x = 5
if x == 5:
print('x is five!')
else:
print('x is not five...')
'\n\nExpected solution:\n\nx = 10\n\nif x == 10:\n print("x is ten!")\nelse:\n print("x is not ten... |
"""248-Get current file name and path.
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Blog: stevepython.wordpress.com
requirements: None.
origin: Various.
"""
# To get the name and path of the current file in use:
print(__file__)
| """248-Get current file name and path.
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Blog: stevepython.wordpress.com
requirements: None.
origin: Various.
"""
print(__file__) |
numbers = []
for i in range(1,101) :
numbers.append(i)
prime_number = []
for number in numbers :
zero_mod = []
if number == 1 :
continue
else :
for divider in range(1,number+1) :
remain = number % divider
if remain == 0 :
zero_mod.append(divider)
... | numbers = []
for i in range(1, 101):
numbers.append(i)
prime_number = []
for number in numbers:
zero_mod = []
if number == 1:
continue
else:
for divider in range(1, number + 1):
remain = number % divider
if remain == 0:
zero_mod.append(divider)
... |
def get_data():
data = []
data_file = open("data.txt")
# data_file = open("test.txt")
for val in data_file:
data.append(val.strip())
data_file.close()
cubes = {}
for row in range(len(data)):
for col in range(len(data[row])):
if data[row][col] == '#':
... | def get_data():
data = []
data_file = open('data.txt')
for val in data_file:
data.append(val.strip())
data_file.close()
cubes = {}
for row in range(len(data)):
for col in range(len(data[row])):
if data[row][col] == '#':
cubes[f'{row}|{col}|0|0'] = 1
... |
# Write a python program to get a single string from two givan string, separated by a space
# and swap a first two char of each string
# Simple string = "abc", "xyz"
# Expected result = "xyc", "abz"
# st = "abc", "xyz"
# print(st[1][:2] + st[0][-1:])
# print(st[0][:2] + st[1][-1:])
def char_swap(a, b):
x = b[:2... | def char_swap(a, b):
x = b[:2] + a[2:]
y = a[:2] + b[2:]
return x + ' ' + y
if __name__ == '__main__':
print(char_swap('abc', 'xyz')) |
'''
Write a function that takes variable number of arguments and returns the sum , sum of squares, sum of
cubes, average, multiplication, multiplication of squares, multiplication of cubes of that numbers.
'''
def calc(*a):
sum = 0
mul = 1
sumSQR = 0
sumCubes = 0
mulSQR = 1
mulCubes... | """
Write a function that takes variable number of arguments and returns the sum , sum of squares, sum of
cubes, average, multiplication, multiplication of squares, multiplication of cubes of that numbers.
"""
def calc(*a):
sum = 0
mul = 1
sum_sqr = 0
sum_cubes = 0
mul_sqr = 1
mul_cubes = 1
... |
# URLs
MEXC_BASE_URL = "https://www.mexc.com"
MEXC_SYMBOL_URL = '/open/api/v2/market/symbols'
MEXC_TICKERS_URL = '/open/api/v2/market/ticker'
MEXC_DEPTH_URL = '/open/api/v2/market/depth?symbol={trading_pair}&depth=200'
MEXC_PRICE_URL = '/open/api/v2/market/ticker?symbol={trading_pair}'
MEXC_PING_URL = '/open/api/v2/... | mexc_base_url = 'https://www.mexc.com'
mexc_symbol_url = '/open/api/v2/market/symbols'
mexc_tickers_url = '/open/api/v2/market/ticker'
mexc_depth_url = '/open/api/v2/market/depth?symbol={trading_pair}&depth=200'
mexc_price_url = '/open/api/v2/market/ticker?symbol={trading_pair}'
mexc_ping_url = '/open/api/v2/common/pin... |
CONFUSION_MATRIX = "confusion_matrix"
AP = "ap"
DETECTION_AP = "detection_mAP"
DETECTION_APS = "detection_APs"
MOTA = "MOTA"
MOTP = "MOTP"
FALSE_POSITIVES = "false_positives"
FALSE_NEGATIVES = "false_negatives"
ID_SWITCHES = "id_switches"
AP_INTERPOLATED = "ap_interpolated"
ERRORS = "errors"
IOU = "iou"
BINARY_IOU = "b... | confusion_matrix = 'confusion_matrix'
ap = 'ap'
detection_ap = 'detection_mAP'
detection_aps = 'detection_APs'
mota = 'MOTA'
motp = 'MOTP'
false_positives = 'false_positives'
false_negatives = 'false_negatives'
id_switches = 'id_switches'
ap_interpolated = 'ap_interpolated'
errors = 'errors'
iou = 'iou'
binary_iou = 'b... |
class GitRequire(object):
def __init__(self, git_url=None, branch=None, submodule=False):
self.git_url = git_url
self.submodule = submodule
self.branch = branch
def clone_params(self):
clone_params = {"single_branch": True}
if self.branch is not None:
clone_p... | class Gitrequire(object):
def __init__(self, git_url=None, branch=None, submodule=False):
self.git_url = git_url
self.submodule = submodule
self.branch = branch
def clone_params(self):
clone_params = {'single_branch': True}
if self.branch is not None:
clone_... |
# Object in Python do not have a fixed layout.
class X:
def __init__(self, a):
self.a = a
x = X(1)
print(x.a) # 1
# For example, we can add new attributes to objects:
x.b = 5
print(x.b) # 5
# Or even new methods into a class:
X.foo = lambda self: 10
print(x.foo()) # 10
# Or even changing base classes d... | class X:
def __init__(self, a):
self.a = a
x = x(1)
print(x.a)
x.b = 5
print(x.b)
X.foo = lambda self: 10
print(x.foo())
class A:
def foo(self):
return 1
class B(A):
pass
class C:
def foo(self):
return 2
b = b()
print(b.foo(), B.__bases__)
B.__bases__ = (C,)
print(b.foo(), ... |
# encoding: utf-8
# module _locale
# from (built-in)
# by generator 1.145
""" Support for POSIX locales. """
# no imports
# Variables with simple values
ABDAY_1 = 131072
ABDAY_2 = 131073
ABDAY_3 = 131074
ABDAY_4 = 131075
ABDAY_5 = 131076
ABDAY_6 = 131077
ABDAY_7 = 131078
ABMON_1 = 131086
ABMON_10 = 131095
ABMON_11 =... | """ Support for POSIX locales. """
abday_1 = 131072
abday_2 = 131073
abday_3 = 131074
abday_4 = 131075
abday_5 = 131076
abday_6 = 131077
abday_7 = 131078
abmon_1 = 131086
abmon_10 = 131095
abmon_11 = 131096
abmon_12 = 131097
abmon_2 = 131087
abmon_3 = 131088
abmon_4 = 131089
abmon_5 = 131090
abmon_6 = 131091
abmon_7 = ... |
class Solution:
# @param A : list of strings
# @return a strings
def longestCommonPrefix(self, A):
common_substring = ""
if A:
common_substring = A[0]
for s in A[1:]:
i = 0
l = len(min(common_substring, s))
while i < l:
... | class Solution:
def longest_common_prefix(self, A):
common_substring = ''
if A:
common_substring = A[0]
for s in A[1:]:
i = 0
l = len(min(common_substring, s))
while i < l:
if s[i] != common_substring[i]:
... |
# Link to the problem: https://www.codechef.com/LTIME63B/problems/EID
def EID():
_ = input()
A = list(map(int, input().split()))
A.sort()
size = len(A)
diff = A[size - 1]
for i in range(size - 1):
tempDiff = A[i + 1] - A[i]
if tempDiff < diff:
diff = tempDiff
return diff
def main():
T = ... | def eid():
_ = input()
a = list(map(int, input().split()))
A.sort()
size = len(A)
diff = A[size - 1]
for i in range(size - 1):
temp_diff = A[i + 1] - A[i]
if tempDiff < diff:
diff = tempDiff
return diff
def main():
t = int(input())
while T:
t -= 1... |
monster = ['fairy', 'goblin', 'ogre', 'werewolf',
'vampire', 'gargoyle', 'pirate', 'undead']
weapon1 = ['dagger', 'stone', 'pistol', 'knife']
weapon2 = ['sword', 'war hammer', 'machine gun', 'battle axe', 'war scythe']
scene = ['grass and yellow wildflowers.',
'sand and sea shells',
... | monster = ['fairy', 'goblin', 'ogre', 'werewolf', 'vampire', 'gargoyle', 'pirate', 'undead']
weapon1 = ['dagger', 'stone', 'pistol', 'knife']
weapon2 = ['sword', 'war hammer', 'machine gun', 'battle axe', 'war scythe']
scene = ['grass and yellow wildflowers.', 'sand and sea shells', 'sand and cactus']
place = ['field',... |
# if-elif-else ladder
'''
if is a conditional statement that is used to perform different actions based on different conditions.
'''
if (5 < 6):
print('5 is less than 6')
print()
print()
a = 6
if (a == 5):
print('a is equal to 5')
else:
print('a is not equal to 5')
print()
print()
a = 6
b = 5
if ... | """
if is a conditional statement that is used to perform different actions based on different conditions.
"""
if 5 < 6:
print('5 is less than 6')
print()
print()
a = 6
if a == 5:
print('a is equal to 5')
else:
print('a is not equal to 5')
print()
print()
a = 6
b = 5
if a < b:
print('a is less than b')
... |
def conta_votos(lista_candidatos_numeros, lista_votos, numeros):
brancos = 0
nulos = 0
contagem_geral = []
for i in range(len(lista_candidatos_numeros)):
contagem_individual = [lista_candidatos_numeros[i][0], numeros[i], 0]
contagem_geral.append(contagem_individual)
for v in votos:
... | def conta_votos(lista_candidatos_numeros, lista_votos, numeros):
brancos = 0
nulos = 0
contagem_geral = []
for i in range(len(lista_candidatos_numeros)):
contagem_individual = [lista_candidatos_numeros[i][0], numeros[i], 0]
contagem_geral.append(contagem_individual)
for v in votos:
... |
global T_D,EPS,MU,ETA,dt
T_D = 12.0
L0 = 1.0
EPS = 0.05
# Osborne 2017 params
MU = -50.
ETA = 1.0
dt = 0.005 #hours
| global T_D, EPS, MU, ETA, dt
t_d = 12.0
l0 = 1.0
eps = 0.05
mu = -50.0
eta = 1.0
dt = 0.005 |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
if len(nums)<3:
return 0
output=[]
slices=[nums[0], nums[1]]
for num in nums[2:]:
if num-slices[-1]==slices[1]-slices[0]:
slices.append(num)
else:
... | class Solution:
def number_of_arithmetic_slices(self, nums: List[int]) -> int:
if len(nums) < 3:
return 0
output = []
slices = [nums[0], nums[1]]
for num in nums[2:]:
if num - slices[-1] == slices[1] - slices[0]:
slices.append(num)
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.isSymmetricHelper(root.left, root.r... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_symmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.isSymmetricHelper(root.left, root.right)
def is_symmetric_helper... |
# Copyright 2019 The TensorFlow 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 applica... | def preprocess_input(x, data_format=None, mode=None):
if mode == 'tf':
x /= 127.5
x -= 1.0
return x
elif mode == 'torch':
x /= 255.0
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
elif mode == 'caffe':
if data_format == 'channels_first':
... |
### Insertion Sort - Part 2 - Solution
def insertionSort2(nums):
for i in range(1, len(nums)):
comp, prev = nums[i], i-1
while (prev >= 0) and (nums[prev] > comp):
nums[prev+1] = nums[prev]
prev -= 1
nums[prev+1] = comp
print(*nums)
n = int(input())
nums = ... | def insertion_sort2(nums):
for i in range(1, len(nums)):
(comp, prev) = (nums[i], i - 1)
while prev >= 0 and nums[prev] > comp:
nums[prev + 1] = nums[prev]
prev -= 1
nums[prev + 1] = comp
print(*nums)
n = int(input())
nums = list(map(int, input().split()[:n]))... |
### CLASSES
class TrackPoint:
def __init__(self, time, coordinates, alt):
self.time = time
self.coordinates = coordinates
self.alt = alt
def __repr__(self):
return "%s %s %dm" % (self.time.strftime("%H:%m:%S"), self.coordinates, self.alt)
| class Trackpoint:
def __init__(self, time, coordinates, alt):
self.time = time
self.coordinates = coordinates
self.alt = alt
def __repr__(self):
return '%s %s %dm' % (self.time.strftime('%H:%m:%S'), self.coordinates, self.alt) |
VARS = [
{'name': 'script_name',
'required': True,
'example': 'fancy_script'},
{'name': 'description',
'example': 'Super fancy script'}
]
| vars = [{'name': 'script_name', 'required': True, 'example': 'fancy_script'}, {'name': 'description', 'example': 'Super fancy script'}] |
def test_api_docs(api_client):
rv = api_client.get("/apidocs", follow_redirects=True)
assert rv.status_code == 200
assert b"JournalsDB API Docs" in rv.data
| def test_api_docs(api_client):
rv = api_client.get('/apidocs', follow_redirects=True)
assert rv.status_code == 200
assert b'JournalsDB API Docs' in rv.data |
# Solution A
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
i = 0
name += "1"
for s in typed:
if s == name[i]:
i += 1
elif s != name[i - 1]:
return False
return i == len(name) - 1
# Solution B
clas... | class Solution:
def is_long_pressed_name(self, name: str, typed: str) -> bool:
i = 0
name += '1'
for s in typed:
if s == name[i]:
i += 1
elif s != name[i - 1]:
return False
return i == len(name) - 1
class Solution:
def is... |
#!/usr/bin/env python
# coding: utf-8
# # Re-implement some Python built-in functions
# In[1]:
def my_max(l1):
max_number = l1[0]
for number in l1:
if number > max_number:
max_number = number
return max_number
# In[2]:
def my_min(l1):
min_number = l1[0]
for number in l1:
... | def my_max(l1):
max_number = l1[0]
for number in l1:
if number > max_number:
max_number = number
return max_number
def my_min(l1):
min_number = l1[0]
for number in l1:
if number < min_number:
min_number = number
return min_number
def my_sum(l1):
tota... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.maxval=0
def countbst(self,root,minval,maxval):
if not root: return... | class Solution(object):
def __init__(self):
self.maxval = 0
def countbst(self, root, minval, maxval):
if not root:
return 0
if root.val < minval or root.val > maxval:
return -1
left = self.countbst(root.left, minval, root.val)
if left == -1:
... |
#!/usr/bin/python
""" Custom counting functions """
def ptcount(particledatalist, ptypelist, ptsums, ypoint=0.0, deltay=2.0):
""" Particle pT counter for mean pT calculation.
Input:
particledatalist -- List of ParticleData objects
ptypelist -- List of particle types for which to do the count
... | """ Custom counting functions """
def ptcount(particledatalist, ptypelist, ptsums, ypoint=0.0, deltay=2.0):
""" Particle pT counter for mean pT calculation.
Input:
particledatalist -- List of ParticleData objects
ptypelist -- List of particle types for which to do the count
ptsums ... |
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
register_npcx_project(
project_name="herobrine_npcx9",
zephyr_board="herobrine_npcx9",
dts_overlays=[
"gpio.dts",
"battery.dts... | register_npcx_project(project_name='herobrine_npcx9', zephyr_board='herobrine_npcx9', dts_overlays=['gpio.dts', 'battery.dts', 'i2c.dts', 'motionsense.dts', 'switchcap.dts', 'usbc.dts']) |
num1=num2=res=0
def cn():
global canal
canal="CFB Cursos"
cn()
print(canal) | num1 = num2 = res = 0
def cn():
global canal
canal = 'CFB Cursos'
cn()
print(canal) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.