content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Calculator app
# read input
# figure out order of operations
# consider edge cases
#divide by zero
#formula : string => "1 + 2 + 3"
def Calculator(formula):
"""Calculator handler executes calculation and returns float result"""
ans = 0
#read input into a list
... | def calculator(formula):
"""Calculator handler executes calculation and returns float result"""
ans = 0
tokens = formula.split()
print(tokens)
oop_list = oop_first_pass(tokens)
print(oopList)
if oopList is not None:
tokens2 = oopList.split()
print(tokens2)
ans = oop_s... |
class Form:
company: str
user: str
days: int
def __init__(self, company, user, days):
self.company = company
self.user = user
self.days = days
| class Form:
company: str
user: str
days: int
def __init__(self, company, user, days):
self.company = company
self.user = user
self.days = days |
def large(arr):
if (len(arr)) < 0:
return 0
max_sum = current = arr[0]
for num in arr[1:]:
current = max(current + num, num)
max_sum = max(current, max_sum)
return max_sum
if __name__ == "__main__":
print(large([1, -1, 3, -4, 5, -3, 6, -3, 2, -1])) | def large(arr):
if len(arr) < 0:
return 0
max_sum = current = arr[0]
for num in arr[1:]:
current = max(current + num, num)
max_sum = max(current, max_sum)
return max_sum
if __name__ == '__main__':
print(large([1, -1, 3, -4, 5, -3, 6, -3, 2, -1])) |
for i in range(int(input())):
n, k, s = list(map(int, input().split()))
total = k * s
count = 0
val = False
m = 0
for j in range(1, s + 1):
if (j % 7) != 0:
count += n
m += 1
else:
continue
if count >= total:
val = True
... | for i in range(int(input())):
(n, k, s) = list(map(int, input().split()))
total = k * s
count = 0
val = False
m = 0
for j in range(1, s + 1):
if j % 7 != 0:
count += n
m += 1
else:
continue
if count >= total:
val = True
... |
# Python program to display astrological sign
# or Zodiac sign for given date of birth
def zodiac_sign(day, month):
# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'
elif month == 'january'... | def zodiac_sign(day, month):
if month == 'december':
astro_sign = 'Sagittarius' if day < 22 else 'capricorn'
elif month == 'january':
astro_sign = 'Capricorn' if day < 20 else 'aquarius'
elif month == 'february':
astro_sign = 'Aquarius' if day < 19 else 'pisces'
elif month == 'ma... |
class Redirect(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
| class Redirect(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs |
audio = [
"aif",
"cda",
"mid",
"midi",
"mp3",
"mpa",
"ogg",
"wav",
"wma",
"wpl"
]
compressed = [
"arj",
"deb",
"gz",
"pkg",
"rar",
"rpm",
"tar",
"z",
"zip"
]
image = [
"ai",
"bmp",
"gif",
"ico",
"jpeg",
"jpg",
"png",... | audio = ['aif', 'cda', 'mid', 'midi', 'mp3', 'mpa', 'ogg', 'wav', 'wma', 'wpl']
compressed = ['arj', 'deb', 'gz', 'pkg', 'rar', 'rpm', 'tar', 'z', 'zip']
image = ['ai', 'bmp', 'gif', 'ico', 'jpeg', 'jpg', 'png', 'ps', 'psd', 'svg', 'tif', 'tiff', 'webp']
spreadsheet = ['ods', 'xlr', 'xls', 'xlsx']
text = ['doc', 'docx'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class UnknownSizeError(Exception):
def __init__(self, cls):
self.cls = cls
def __str__(self):
return f'The size of `{self.cls}` is unkown, the object could not be generated.'
class UnavalibleAttributeError(Exception):
def __init__(sel... | class Unknownsizeerror(Exception):
def __init__(self, cls):
self.cls = cls
def __str__(self):
return f'The size of `{self.cls}` is unkown, the object could not be generated.'
class Unavalibleattributeerror(Exception):
def __init__(self, cls, attr_name):
self.cls = cls
sel... |
# ------------------------------
# 166. Fraction to Recurring Decimal
#
# Description:
# Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
# If the fractional part is repeating, enclose the repeating part in parentheses.
# Example 1:
# Input: numerator =... | class Solution(object):
def fraction_to_decimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return '0'
res = []
res.append('-' if (numerator > 0) ^ (denominator > 0) els... |
# test short circuit expressions outside if conditionals
print(() or 1)
print((1,) or 1)
print(() and 1)
print((1,) and 1)
print("PASS") | print(() or 1)
print((1,) or 1)
print(() and 1)
print((1,) and 1)
print('PASS') |
TRAINING_DATA = [
(
"i went to amsterdem last year and the canals were beautiful",
{"entities": [(10, 19, "TOURIST_DESTINATION")]},
),
(
"You should visit Paris once in your life, but the Eiffel Tower is kinda boring",
{"entities": [(17, 22, "TOURIST_DESTINATION")]},
),
... | training_data = [('i went to amsterdem last year and the canals were beautiful', {'entities': [(10, 19, 'TOURIST_DESTINATION')]}), ('You should visit Paris once in your life, but the Eiffel Tower is kinda boring', {'entities': [(17, 22, 'TOURIST_DESTINATION')]}), ("There's also a Paris in Arkansas, lol", {'entities': [... |
class LoraCommands:
## Returns the firmware version and release date in format: "RN2903 X.Y.Z MMM DD YYYY HH:MM:SS"
GET_VERSION = 'sys get ver'
## Resets LoRa stack
RESET_STACK = 'mac reset'
## Sets the LoRA functionality to radio (needs to be done before anything else)
START_RADIO_O... | class Loracommands:
get_version = 'sys get ver'
reset_stack = 'mac reset'
start_radio_op = 'mac pause'
set_radio_power = 'radio set pwr {}'
get_radio_mode = 'radio get mod'
get_radio_frequency = 'radio get freq'
get_radio_spreading_factor = 'radio get sf'
set_continuous_radio_reception =... |
"""
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: (c++ int) or
(C++ long long int).
As we know, the result of
grows really fast with increasing
.
Let's do some calculations on very large integers.
Task
Read four numbers,
, , , and , and print the res... | """
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: (c++ int) or
(C++ long long int).
As we know, the result of
grows really fast with increasing
.
Let's do some calculations on very large integers.
Task
Read four numbers,
, , , and , and print the res... |
# DataBase Credentials
database="da665kfg2oc9og"
user = "aourrzrdjlrpjo"
password = "12359d0fa8d70aeea4d2ef3acd96eb794f178dee42887f7c350ad49a4d78e323"
host = "ec2-18-207-95-219.compute-1.amazonaws.com"
port = "5432" | database = 'da665kfg2oc9og'
user = 'aourrzrdjlrpjo'
password = '12359d0fa8d70aeea4d2ef3acd96eb794f178dee42887f7c350ad49a4d78e323'
host = 'ec2-18-207-95-219.compute-1.amazonaws.com'
port = '5432' |
# http://codeforces.com/contest/268/problem/C
n, m = map(int, input().split())
d = min(n, m)
print(d + 1)
for i in range(d + 1): print("{} {}".format(d-i, i)) | (n, m) = map(int, input().split())
d = min(n, m)
print(d + 1)
for i in range(d + 1):
print('{} {}'.format(d - i, i)) |
infile = "input_file.txt"
outfile = "output_file.txt"
delete_list = [
# Your words you want to fill to filter.
"Dog","Bird","Pig"
]
with open(infile) as fin, open(outfile, "w+") as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
| infile = 'input_file.txt'
outfile = 'output_file.txt'
delete_list = ['Dog', 'Bird', 'Pig']
with open(infile) as fin, open(outfile, 'w+') as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, '')
fout.write(line) |
answers =[
"Apple",
"Apricot",
"Avocado",
"Banana",
"Bilberry",
"Blackberry",
"Blackcurrant",
"Blueberry",
"Cherry",
"Coconut",
"Cranberry",
"Date",
"Dragonfruit",
"Durian",
"Grape",
"Grapefruit",
"Guava",
"Jackfruit",
"Jujube",
"Kiwifruit"... | answers = ['Apple', 'Apricot', 'Avocado', 'Banana', 'Bilberry', 'Blackberry', 'Blackcurrant', 'Blueberry', 'Cherry', 'Coconut', 'Cranberry', 'Date', 'Dragonfruit', 'Durian', 'Grape', 'Grapefruit', 'Guava', 'Jackfruit', 'Jujube', 'Kiwifruit', 'Kumquat', 'Lemon', 'Lime', 'Longan', 'Lychee', 'Mango', 'Mangosteen', 'Melon'... |
puzzle_input_list = []
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
line = line.strip()
puzzle_input_list.append(line)
open_brackets = {"{", "(", "[", "<"}
bracket_mapping = {"}": "{", ")": "(", "]": "[", ">": "<",
"{": "}", "(": ")", "[": "]", "<": ">"... | puzzle_input_list = []
with open('input.txt', 'r') as puzzle_input:
for line in puzzle_input:
line = line.strip()
puzzle_input_list.append(line)
open_brackets = {'{', '(', '[', '<'}
bracket_mapping = {'}': '{', ')': '(', ']': '[', '>': '<', '{': '}', '(': ')', '[': ']', '<': '>'}
bracket_to_points =... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Average Scores
#Problem level: 7 kyu
def average(array):
return round(sum(array)/len(array))
| def average(array):
return round(sum(array) / len(array)) |
# -*- coding: utf-8 -*-
{
'name': "Online Event Ticketing",
'category': 'Website/Website',
'summary': "Sell event tickets online",
'description': """
Sell event tickets through eCommerce app.
""",
'depends': ['website_event', 'event_sale', 'website_sale'],
'data': [
'data/event_data... | {'name': 'Online Event Ticketing', 'category': 'Website/Website', 'summary': 'Sell event tickets online', 'description': '\nSell event tickets through eCommerce app.\n ', 'depends': ['website_event', 'event_sale', 'website_sale'], 'data': ['data/event_data.xml', 'views/event_templates.xml', 'views/event_views.xml', ... |
class Allergies(object):
items = {
'eggs': 1,
'peanuts': 2,
'shellfish': 4,
'strawberries': 8,
'tomatoes': 16,
'chocolate': 32,
'pollen': 64,
'cats': 128,
}
def __init__(self, score):
self._score = score
def is_allergic_to(self, i... | class Allergies(object):
items = {'eggs': 1, 'peanuts': 2, 'shellfish': 4, 'strawberries': 8, 'tomatoes': 16, 'chocolate': 32, 'pollen': 64, 'cats': 128}
def __init__(self, score):
self._score = score
def is_allergic_to(self, item):
return bool(Allergies.items.get(item, 0) & self._score)
... |
def main():
# Let's create a dictionary with student keys and GPA values
student_gpa = {"john": 3.5,
"jane": 4.0,
"bob": 2.8,
"mary": 3.2}
# There are four student records in this dictionary
assert len(student_gpa) == 4
# Each student has a ... | def main():
student_gpa = {'john': 3.5, 'jane': 4.0, 'bob': 2.8, 'mary': 3.2}
assert len(student_gpa) == 4
assert len(student_gpa.keys()) == len(student_gpa.values())
for student in student_gpa.keys():
assert len(student) > 2
for gpa in student_gpa.values():
assert gpa > 2.0
asse... |
# DNA -> RNA Transcription
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
# rna dict
rna_dict = {'A': 'U', 'T': 'A',
'C': 'G', 'G': 'C'}
# seq to list
seq_list = list(seq)
# for each e... | def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
rna_dict = {'A': 'U', 'T': 'A', 'C': 'G', 'G': 'C'}
seq_list = list(seq)
for (i, s) in enumerate(seq_list):
seq_list[i] = rna_dict[s]
rna_seq = ''.join(se... |
class VserverPeerState(basestring):
"""
peered|pending|initializing|initiated|rejected|suspended|deleted
Possible values:
<ul>
<li> "peered" - Vserver peer relationship is
established and the respective applications can use peer
relationship,
<li> "pending" - Vserver peer re... | class Vserverpeerstate(basestring):
"""
peered|pending|initializing|initiated|rejected|suspended|deleted
Possible values:
<ul>
<li> "peered" - Vserver peer relationship is
established and the respective applications can use peer
relationship,
<li> "pending" - Vserver peer re... |
# The MIT License (MIT)
#
# Copyright (c) 2017-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, ... | def truncate(message, from_start, from_end=None):
"""
Truncate the string *message* until at max *from_start* characters and
insert an ellipsis (`...`) in place of the additional content. If *from_end*
is specified, the same will be applied to the end of the string.
"""
if len(message) <= from_start + (... |
# pylint: disable=missing-docstring
"""
# Stub file type annotations examples
## Links
[Stub files](https://mypy.readthedocs.io/en/latest/stubs.html)
"""
class MyValue:
pass
def func(_list, _my_value_cls=MyValue, **_kwargs):
pass
def func_any(_list, _my_value_cls=MyValue, **_kwargs):
pass
| """
# Stub file type annotations examples
## Links
[Stub files](https://mypy.readthedocs.io/en/latest/stubs.html)
"""
class Myvalue:
pass
def func(_list, _my_value_cls=MyValue, **_kwargs):
pass
def func_any(_list, _my_value_cls=MyValue, **_kwargs):
pass |
class Heap:
def __init__(self,comp):
self.hp = []
self.size = 0
self.comp = comp
def push(self,value):
self.hp.append(value)
self.size += 1
self._heapifyForInsertion()
def pop(self):
if self.size == 0:
return None
value = self.hp[0]... | class Heap:
def __init__(self, comp):
self.hp = []
self.size = 0
self.comp = comp
def push(self, value):
self.hp.append(value)
self.size += 1
self._heapifyForInsertion()
def pop(self):
if self.size == 0:
return None
value = self.... |
names = []
for i in range(10):
X =str(input(''))
names.append(X)
print(names[2])
print(names[6])
print(names[8]) | names = []
for i in range(10):
x = str(input(''))
names.append(X)
print(names[2])
print(names[6])
print(names[8]) |
def addBinary(a: str, b: str) -> str:
n_a = len(a)
n_b = len(b)
max_n = max(n_a, n_b)
a = a.rjust(max_n, "0")
b = b.rjust(max_n, "0")
jin_bit = 0
result = ""
for i in range(max_n - 1, -1, -1):
tmp_a = int(a[i])
tmp_b = int(b[i])
tmp = tmp_a + tmp_b + jin_bit
... | def add_binary(a: str, b: str) -> str:
n_a = len(a)
n_b = len(b)
max_n = max(n_a, n_b)
a = a.rjust(max_n, '0')
b = b.rjust(max_n, '0')
jin_bit = 0
result = ''
for i in range(max_n - 1, -1, -1):
tmp_a = int(a[i])
tmp_b = int(b[i])
tmp = tmp_a + tmp_b + jin_bit
... |
# Performance note: I benchmarked this code using a set instead of
# a list for the stopwords and was surprised to find that the list
# performed /better/ than the set - maybe because it's only a small
# list.
stopwords = '''
i
a
an
are
as
at
be
by
for
from
how
in
is
it
of
on
or
that
the
this
... | stopwords = '\ni\na\nan\nare\nas\nat\nbe\nby\nfor\nfrom\nhow\nin\nis\nit\nof\non\nor\nthat\nthe\nthis\nto\nwas\nwhat\nwhen\nwhere\n'.split()
def strip_stopwords(sentence):
"""Removes stopwords - also normalizes whitespace"""
words = sentence.split()
sentence = []
for word in words:
if word.lowe... |
class Credentials(object):
def __init__(self, username, password):
"""
Credentials.
:param username: Username
:param password: Password
"""
self.username = username #: Username
self.password = password #: Password
| class Credentials(object):
def __init__(self, username, password):
"""
Credentials.
:param username: Username
:param password: Password
"""
self.username = username
self.password = password |
# st2common
__all__ = ["MASKED_ATTRIBUTES_BLACKLIST", "MASKED_ATTRIBUTE_VALUE"]
# A blacklist of attributes which should be masked in the log messages by default.
# Note: If an attribute is an object or a dict, we try to recursively process it and mask the
# values.
MASKED_ATTRIBUTES_BLACKLIST = [
"password",
... | __all__ = ['MASKED_ATTRIBUTES_BLACKLIST', 'MASKED_ATTRIBUTE_VALUE']
masked_attributes_blacklist = ['password', 'auth_token', 'token', 'secret', 'credentials', 'st2_auth_token']
masked_attribute_value = '********' |
combination = [(True,True,True),(True,True,False),(True,False,True),(True,False,False),(False,True,True),(False,True,False),(False,False,True),(False,False,False)]
variable = {'p':0,'q':1,'r':2}
kb = ''
q = ''
priority = {'~':3,'v':1,'^':2}
def input_rules():
global kb,q
kb = (input("Enter rule : ... | combination = [(True, True, True), (True, True, False), (True, False, True), (True, False, False), (False, True, True), (False, True, False), (False, False, True), (False, False, False)]
variable = {'p': 0, 'q': 1, 'r': 2}
kb = ''
q = ''
priority = {'~': 3, 'v': 1, '^': 2}
def input_rules():
global kb, q
kb = ... |
# Numeric Pattern 7
"""
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"""
i = 0
nums = list(range(2, 52, 2))
for _ in range(5):
j = i + 5
row = " ".join(map(str, nums[i:j]))
print(row)
i = j
| """
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"""
i = 0
nums = list(range(2, 52, 2))
for _ in range(5):
j = i + 5
row = ' '.join(map(str, nums[i:j]))
print(row)
i = j |
{
'includes': [
'common.gypi',
],
'targets': [
{
'target_name': 'svg',
'type': 'static_library',
'include_dirs': [
'../include/config',
'../include/core',
'../include/xml',
'../include/utils',
'../include/svg',
],
'sources': [
'... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'svg', 'type': 'static_library', 'include_dirs': ['../include/config', '../include/core', '../include/xml', '../include/utils', '../include/svg'], 'sources': ['../include/svg/SkSVGAttribute.h', '../include/svg/SkSVGBase.h', '../include/svg/SkSVGPaintState.h', '.... |
def SetUpGame():
global WreckContainer, ShipContainer, PlanetContainer, ArchiveContainer, playerShip, gameData, SystemContainer
GameData = gameData()
GameData.tutorial = False
PlanetContainer = [Planet(0, -1050, 1000)]
GameData.homePlanet = PlanetContainer[0]
GameData.tasks = []
PlanetContai... | def set_up_game():
global WreckContainer, ShipContainer, PlanetContainer, ArchiveContainer, playerShip, gameData, SystemContainer
game_data = game_data()
GameData.tutorial = False
planet_container = [planet(0, -1050, 1000)]
GameData.homePlanet = PlanetContainer[0]
GameData.tasks = []
PlanetC... |
class SearchGoogleNewsError(Exception):
pass
class SearchGoogleNewsDataSourceNotFound(Exception):
pass
class SearchGoogleNewsParseError(Exception):
pass
| class Searchgooglenewserror(Exception):
pass
class Searchgooglenewsdatasourcenotfound(Exception):
pass
class Searchgooglenewsparseerror(Exception):
pass |
#!/usr/bin/env python3
# Character Picture Grid
grid = [
[".", ".", ".", ".", ".", "."],
[".", "O", "O", ".", ".", "."],
["O", "O", "O", "O", ".", "."],
["O", "O", "O", "O", "O", "."],
[".", "O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O", "."],
["O", "O", "O", "O", ".", "."],
[".", ... | grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']]
rows = len(grid)
columns... |
#
# PySNMP MIB module HH3C-VM-MAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VM-MAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
# 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... | """Helper methods for implementing the test bundles."""
load('@build_bazel_rules_apple//apple/bundling:binary_support.bzl', 'binary_support')
load('@build_bazel_rules_apple//apple/bundling:bundler.bzl', 'bundler')
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleBundleInfo')
_default_test_bundle_id = 'com.ba... |
class Solution:
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if len(rooms) == 1:
return True
if len(rooms[0]) == 0:
return False
curent = set()
visited = [0]
for key in rooms... | class Solution:
def can_visit_all_rooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if len(rooms) == 1:
return True
if len(rooms[0]) == 0:
return False
curent = set()
visited = [0]
for key in rooms[0... |
"""2. Fine-tuning SOTA video models on your own dataset
=======================================================
Fine-tuning is an important way to obtain good video models on your own data when you don't have large annotated dataset or don't have the
computing resources to train a model from scratch for your use case.... | """2. Fine-tuning SOTA video models on your own dataset
=======================================================
Fine-tuning is an important way to obtain good video models on your own data when you don't have large annotated dataset or don't have the
computing resources to train a model from scratch for your use case.... |
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
len_histogram = len(height)
ans = 0
height_list = sorter(height, reverse=True)
for now_h... | class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largest_rectangle_area(self, height):
len_histogram = len(height)
ans = 0
height_list = sorter(height, reverse=True)
for now_height in height_list:
... |
# 17. Take 10 integers from keyboard using loop and print their average value on the screen. (use array to store inputs).
numbers = list(map(int, input("Enter 10 numbers:").split()))
if len(numbers) >= 10:
numbers = numbers[0:10]
print("10 Numbers are", numbers)
print("Average=", sum(numbers)/len(numbers)... | numbers = list(map(int, input('Enter 10 numbers:').split()))
if len(numbers) >= 10:
numbers = numbers[0:10]
print('10 Numbers are', numbers)
print('Average=', sum(numbers) / len(numbers)) |
def parse_parts(line):
space_separated_parts = line.split()
bounds = space_separated_parts[0].split('-')
char = space_separated_parts[1].split(':')[0]
password = space_separated_parts[2]
return int(bounds[0]), int(bounds[1]), char, password
def is_valid_first(min_req, max_req, letter, password):
... | def parse_parts(line):
space_separated_parts = line.split()
bounds = space_separated_parts[0].split('-')
char = space_separated_parts[1].split(':')[0]
password = space_separated_parts[2]
return (int(bounds[0]), int(bounds[1]), char, password)
def is_valid_first(min_req, max_req, letter, password):
... |
# Given a collection of numbers, return all possible permutations.
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
# [1,2] have the following permutations:
# [1,2], [2,1]
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
... | class Solution:
def permute(self, nums):
ans = []
stack = [([], nums)]
while stack:
(ret, nums) = stack.pop(0)
if nums:
for i in range(len(nums)):
stack.append((ret + [nums[i]], nums[:i] + nums[i + 1:]))
else:
... |
# import pytest
class TestDatabase:
def test___call__(self): # synced
assert True
def test_default_schema(self): # synced
assert True
def test_schema_names(self): # synced
assert True
def test_table_names(self): # synced
assert True
def test_view_names(self)... | class Testdatabase:
def test___call__(self):
assert True
def test_default_schema(self):
assert True
def test_schema_names(self):
assert True
def test_table_names(self):
assert True
def test_view_names(self):
assert True
def test_create_table(self):
... |
class Vetor:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vetor (%r,%r)' % (self.x, self.y)
def __mul__(self, escalar):
x = self.x * escalar
y = self.y * escalar
return Vetor(x, y)
def __add__(self, outro):
x ... | class Vetor:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vetor (%r,%r)' % (self.x, self.y)
def __mul__(self, escalar):
x = self.x * escalar
y = self.y * escalar
return vetor(x, y)
def __add__(self, outro):
x ... |
# Databricks notebook source
# MAGIC %md # CCU002_03-D04-custom_tables
# MAGIC
# MAGIC **Description** This notebook creates custom tables, such as long format HES.
# MAGIC
# MAGIC **Author(s)** Venexia Walker
# COMMAND ----------
# MAGIC %md ## Define functions
# COMMAND ----------
# Define create table functio... | def create_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', select_sql_script: str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the t... |
SUBJ_REPORT = "Problem Report: ExCEED Labs"
ERROR_NO_EMAIL_TO_GET_AHOLD = "We need to know how to get ahold of you!"
ERROR_NO_REPORT = "Don't forget to add your problem report or request!"
ERROR_NOT_SUBMITTED = "There was a problem with your submission. Please try again!"
SUCCESS_REPORT_SUBMITTED = "Success! Your pro... | subj_report = 'Problem Report: ExCEED Labs'
error_no_email_to_get_ahold = 'We need to know how to get ahold of you!'
error_no_report = "Don't forget to add your problem report or request!"
error_not_submitted = 'There was a problem with your submission. Please try again!'
success_report_submitted = 'Success! Your probl... |
"""
URL: https://codeforces.com/problemset/problem/144/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
mil = list(map(int, input().split()))
count = 0
maxx_index = mil.index(max(mil))
while maxx_index - 1 >= 0:
mil[maxx_index - 1], mil[maxx_index] = mil[maxx_index], mil[maxx_index - 1]
... | """
URL: https://codeforces.com/problemset/problem/144/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
mil = list(map(int, input().split()))
count = 0
maxx_index = mil.index(max(mil))
while maxx_index - 1 >= 0:
(mil[maxx_index - 1], mil[maxx_index]) = (mil[maxx_index], mil[maxx_index - 1])
... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
""... | """
A list of valid values for the 'platform_id' identifier code in FT_CharMapRec
and FT_SfntName structures.
TT_PLATFORM_APPLE_UNICODE
Used by Apple to indicate a Unicode character map and/or name entry. See
TT_APPLE_ID_XXX for corresponding 'encoding_id' values. Note that name
entries in this format are code... |
# Sum square difference
# https://projecteuler.net/problem=6
def solve(n):
sn = (n*(n+1)//2) * (n*(n+1)//2)
sn2 = n*(n+1)*(2*n+1)//6 # sum of first n squared natural numbers
return abs(sn - sn2)
print(solve(100)) | def solve(n):
sn = n * (n + 1) // 2 * (n * (n + 1) // 2)
sn2 = n * (n + 1) * (2 * n + 1) // 6
return abs(sn - sn2)
print(solve(100)) |
_base_ = [
'../_base_/models/paa_distil_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
model = dict(
type='LAD',
# student
pretrained='torchvision://resnet50',
backbone=dict(depth=50),
bbox_head=dict(... | _base_ = ['../_base_/models/paa_distil_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
model = dict(type='LAD', pretrained='torchvision://resnet50', backbone=dict(depth=50), bbox_head=dict(type='PAA_LAD_Head'), teacher_pretrained='http://download.op... |
class Solution(object):
def solveNQueens(self, n):
def dfs(queens, xy_sub, xy_plus):
row = len(queens)
if row == n:
result.append(queens)
return None
for col in range(n):
if col not in queens and col + row not in xy_plus and... | class Solution(object):
def solve_n_queens(self, n):
def dfs(queens, xy_sub, xy_plus):
row = len(queens)
if row == n:
result.append(queens)
return None
for col in range(n):
if col not in queens and col + row not in xy_plus... |
def merge_sort_time(job_list):
'''
sorts the list by timestamp
:return:
array
'''
if len(job_list) > 1:
mid = len(job_list) // 2
lefthalf = job_list[:mid]
righthalf = job_list[mid:]
merge_sort_time(lefthalf)
merge_sort_time(righthalf)
i =... | def merge_sort_time(job_list):
"""
sorts the list by timestamp
:return:
array
"""
if len(job_list) > 1:
mid = len(job_list) // 2
lefthalf = job_list[:mid]
righthalf = job_list[mid:]
merge_sort_time(lefthalf)
merge_sort_time(righthalf)
i = 0... |
#
# PySNMP MIB module CHARACTER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/CHARACTER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:06:47 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
class Regularcombo():
"""docstring for ."""
def __init__(self, burger = ["big_mac"], snack = ["fries"], drink = ["coca"]):
try:
assert type(burger) == list
except AssertionError:
print('Please enter initial burger as list then custom')
else:
self.burge... | class Regularcombo:
"""docstring for ."""
def __init__(self, burger=['big_mac'], snack=['fries'], drink=['coca']):
try:
assert type(burger) == list
except AssertionError:
print('Please enter initial burger as list then custom')
else:
self.burger = bur... |
def write_results(results, save_path):
output = []
for k, v in results.items():
output.append("{}: {}".format(k, v))
output.append("\n")
output.append("If you need to access these results for the future "
"they are stored in: {}".format(save_path))
with open(save_pat... | def write_results(results, save_path):
output = []
for (k, v) in results.items():
output.append('{}: {}'.format(k, v))
output.append('\n')
output.append('If you need to access these results for the future they are stored in: {}'.format(save_path))
with open(save_path, 'w') as fp:
... |
houses = {"Harry": "Gryffindor", "Draco": "Slytherin"}
houses["Hermione"] = "Gryffindor"
print(houses["Harry"])
| houses = {'Harry': 'Gryffindor', 'Draco': 'Slytherin'}
houses['Hermione'] = 'Gryffindor'
print(houses['Harry']) |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head):
if not head:
return None
i = 0
tmp = head
first = True
prev = None
tmp_even_head = None
tail = None
... | class Solution:
def odd_even_list(self, head):
if not head:
return None
i = 0
tmp = head
first = True
prev = None
tmp_even_head = None
tail = None
while tmp:
if i % 2 != 0:
if first:
second_l... |
def lineup_students(string):
return sorted(string.split(), key=lambda x: (len(x), x), reverse=True)
# lineup_students = lambda s: sorted(s.split(), key=lambda x: (len(x), x), reverse=True)
| def lineup_students(string):
return sorted(string.split(), key=lambda x: (len(x), x), reverse=True) |
# Accept a positive integer and print the reverse of it.
n = int(input("Enter a positive integer: ")) # | n = 123
print()
rev = 0 # | rev = 0
while n > 0: # | 123 > 0 = True | 12 > 0 = True | 1 > 0 = True |
... | n = int(input('Enter a positive integer: '))
print()
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n = n // 10
print('The reverse of the number is:', rev) |
def parse_plotter_args(parser):
parser.add_option(
"--name_of_3dmodel",
type="string",
default="airplane/airplane_0630.ply",
help="name of 3D model to plot using the 'plot_subclouds' script",
)
parser.add_option(
"--save_plot_frames",
action="store_true",
... | def parse_plotter_args(parser):
parser.add_option('--name_of_3dmodel', type='string', default='airplane/airplane_0630.ply', help="name of 3D model to plot using the 'plot_subclouds' script")
parser.add_option('--save_plot_frames', action='store_true', default=False, help="whether to record the 3D model shown in... |
PART_NAMES = [
"nose", "leftEye", "rightEye", "leftEar", "rightEar", "leftShoulder",
"rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist",
"leftHip", "rightHip", "leftKnee", "rightKnee", "leftAnkle", "rightAnkle"
]
NUM_KEYPOINTS = len(PART_NAMES)
PART_IDS = {pn: pid for pid, pn in enumer... | part_names = ['nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder', 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist', 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle']
num_keypoints = len(PART_NAMES)
part_ids = {pn: pid for (pid, pn) in enumerate(PART_NAMES)... |
to_remove = input()
word = input()
while to_remove in word:
word = word.replace(to_remove, '')
print(word)
| to_remove = input()
word = input()
while to_remove in word:
word = word.replace(to_remove, '')
print(word) |
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
CHROME_WIN_UA = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
STORIES_URL = 'https://i.i... | base_url = 'https://www.instagram.com/'
login_url = BASE_URL + 'accounts/login/ajax/'
logout_url = BASE_URL + 'accounts/logout/'
media_url = BASE_URL + '{0}/media'
chrome_win_ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
stories_url = 'https://i.in... |
if __name__ == '__main__':
name = ' aleX'
print(name.strip())
# name = name.strip()
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
# name = name.replace('l', 'p')
print(name.split('l'))
print(type(name.split('e... | if __name__ == '__main__':
name = ' aleX'
print(name.strip())
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
print(name.split('l'))
print(type(name.split('e')))
print(name.upper())
print(name.lower())
print... |
'''
Created on 16.1.2017
@author: jm
'''
class GedcomLine(object):
'''
Gedcom line container, which can also carry the lower level gedcom lines.
Example
- level 2
- tag 'GIVN'
- value 'Johan' ...}
'''
# Current path elemements
# See https://docs.python.org/3/faq/... | """
Created on 16.1.2017
@author: jm
"""
class Gedcomline(object):
"""
Gedcom line container, which can also carry the lower level gedcom lines.
Example
- level 2
- tag 'GIVN'
- value 'Johan' ...}
"""
path_elem = []
def __init__(self, line, linenum=0):
"... |
'''input
1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
8
3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
23
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -... | """input
1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
8
3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
23
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1... |
filename = 'programming_poll.txt'
responses = []
while True:
response = input("\nWhy do you like programming? ")
responses.append(response)
continue_poll = input("Would you like to let someone else respond? (y/n) ")
if continue_poll != 'y':
break
with open(filename, 'a') as f:
for respons... | filename = 'programming_poll.txt'
responses = []
while True:
response = input('\nWhy do you like programming? ')
responses.append(response)
continue_poll = input('Would you like to let someone else respond? (y/n) ')
if continue_poll != 'y':
break
with open(filename, 'a') as f:
for response i... |
'''
Created on Oct 13, 2017
@author: LSX1KOR
'''
"""
In the multiple inheritance scenario, any specified attribute is searched first in the current class.
If not found, the search continues into parent classes in depth-first,
left-right fashion without searching same class twice.
"""
class Base1(object):
def foo(... | """
Created on Oct 13, 2017
@author: LSX1KOR
"""
'\nIn the multiple inheritance scenario, any specified attribute is searched first in the current class.\nIf not found, the search continues into parent classes in depth-first,\nleft-right fashion without searching same class twice.\n'
class Base1(object):
def foo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyright 2020-2021"
__license__ = "MIT"
__version__ = "2.3.7"
__status__ = "Prototype"
def iso86012datetime64(time):
r"""Convert ISO8601 time format to datetime64 in ns units.
Parameters... | __author__ = 'Louis Richard'
__email__ = 'louisr@irfu.se'
__copyright__ = 'Copyright 2020-2021'
__license__ = 'MIT'
__version__ = '2.3.7'
__status__ = 'Prototype'
def iso86012datetime64(time):
"""Convert ISO8601 time format to datetime64 in ns units.
Parameters
----------
time : ndarray
Time i... |
#
# @lc app=leetcode id=1806 lang=python3
#
# [1806] Minimum Number of Operations to Reinitialize a Permutation
#
# @lc code=start
class Solution:
def reinitializePermutation(self, n: int) -> int:
i, cnt = 1, 0
while not cnt or i > 1: # i != 1 doesn't work
i = i * 2 % (n - 1)
... | class Solution:
def reinitialize_permutation(self, n: int) -> int:
(i, cnt) = (1, 0)
while not cnt or i > 1:
i = i * 2 % (n - 1)
cnt += 1
return cnt |
class TestFunctionalTest(object):
counter = 0
@classmethod
def setup_class(cls):
cls.counter += 1
@classmethod
def teardown_class(cls):
cls.counter -= 1
def _run(self):
assert self.counter==1
def test1(self):
self._run()
def test2(self):
self._run(... | class Testfunctionaltest(object):
counter = 0
@classmethod
def setup_class(cls):
cls.counter += 1
@classmethod
def teardown_class(cls):
cls.counter -= 1
def _run(self):
assert self.counter == 1
def test1(self):
self._run()
def test2(self):
sel... |
class Parameter:
'''
Defines a sampled (or "free") parameter by spin, parity, channel,
rank, and whether it's an energy or width (kind).
kind : "energy" or "width"
"width" can be the partial width or ANC (depending on how it was
set up in AZURE2)
channel : channel pair... | class Parameter:
"""
Defines a sampled (or "free") parameter by spin, parity, channel,
rank, and whether it's an energy or width (kind).
kind : "energy" or "width"
"width" can be the partial width or ANC (depending on how it was
set up in AZURE2)
channel : channel pair... |
top_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
DESC
LIMIT 5
"""
worst_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
ASC
LIMIT 5
"""
top_vote = """SELECT *
FROM rm_episodes
INNE... | top_avg = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY averageRating\nDESC\nLIMIT 5\n'
worst_avg = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY averageRating\nASC\nLIMIT 5\n'
top_vote = 'SELECT *\nFROM rm_episodes\... |
config = {
# these values are related to the user's environment
'env': {
'databases': {
'postgres_host': '127.0.0.1',
'postgres_name': 'jesse_db',
'postgres_port': 5432,
'postgres_username': 'jesse_user',
'postgres_password': 'password',
... | config = {'env': {'databases': {'postgres_host': '127.0.0.1', 'postgres_name': 'jesse_db', 'postgres_port': 5432, 'postgres_username': 'jesse_user', 'postgres_password': 'password'}, 'caching': {'driver': 'pickle'}, 'logging': {'order_submission': True, 'order_cancellation': True, 'order_execution': True, 'position_ope... |
class CopyAsValuesParam(object):
def __init__(self, **kargs):
self.nodeId = kargs["nodeId"] if "nodeId" in kargs else None
self.asNewNode = kargs["asNewNode"] if "asNewNode" in kargs else False
| class Copyasvaluesparam(object):
def __init__(self, **kargs):
self.nodeId = kargs['nodeId'] if 'nodeId' in kargs else None
self.asNewNode = kargs['asNewNode'] if 'asNewNode' in kargs else False |
# a queue is a data structure in which the data element entered first is removed first
# basically you insert elements from one end and remove them from another end
# a very simple, and cliche example would be that of a plain old queue at McDonald's
# The person who joined the queue first will order first, and the one... | class Ourqueue:
def __init__(self):
self.front = -1
self.end = -1
self.elements = []
def queue(self, value):
self.front = self.front + 1
self.elements.insert(self.top, value)
def pop(self):
if self.top >= 0:
self.top = self.top - 1
else:... |
#!/usr/bin/env python3
def coverage_test_helper():
one = 10 + 3 - 12
print('This function should be called {one} time to achieve 100% coverage')
return one
| def coverage_test_helper():
one = 10 + 3 - 12
print('This function should be called {one} time to achieve 100% coverage')
return one |
class Checksum:
@staticmethod
def calc(data: str):
chksum = Checksum.__str_list2bin(data)
chksum = Checksum.__sum_bytes(chksum)
map(lambda x: bytearray(x + 1)[0], chksum)
return chksum
@staticmethod
def __str_list2bin(data: str) -> list:
map(lambda x: bytearray(x... | class Checksum:
@staticmethod
def calc(data: str):
chksum = Checksum.__str_list2bin(data)
chksum = Checksum.__sum_bytes(chksum)
map(lambda x: bytearray(x + 1)[0], chksum)
return chksum
@staticmethod
def __str_list2bin(data: str) -> list:
map(lambda x: bytearray(... |
async def m001_initial(db):
await db.execute(
"""
CREATE TABLE subdomains.domain (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,
domain TEXT NOT NULL,
webhook TEXT,
cf_token TEXT NOT NULL,
cf_zone_id TEXT NOT NULL,
des... | async def m001_initial(db):
await db.execute('\n CREATE TABLE subdomains.domain (\n id TEXT PRIMARY KEY,\n wallet TEXT NOT NULL,\n domain TEXT NOT NULL,\n webhook TEXT,\n cf_token TEXT NOT NULL,\n cf_zone_id TEXT NOT NULL,\n descrip... |
# --------------
##File path for the file
file_path
#Code starts here
#Function to read file
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence=file.rea... | file_path
def read_file(path):
file = open(path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
file_1 = open(file_path_1)
file_2 = open(file_path_2)
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_... |
# Adapted from: https://stackoverflow.com/questions/37935920/quantile-normalization-on-pandas-dataframe
# Citing: https://en.wikipedia.org/wiki/Quantile_normalization
class QNorm:
def __init__(self):
return
def fit(self,df):
return _QNormFit(self,df.stack().groupby(df.rank(method='first').stack(... | class Qnorm:
def __init__(self):
return
def fit(self, df):
return _q_norm_fit(self, df.stack().groupby(df.rank(method='first').stack().astype(int)).mean())
def fit_transform(self, df):
return self.fit(df).transform(df)
class _Qnormfit:
def __init__(self, parent, df):
... |
class PluginError(Exception):
pass
class OneLoginClientError(PluginError):
pass
class UserNotFound(PluginError):
pass
class FactorNotFound(PluginError):
pass
class TimeOutError(PluginError):
pass
class APIResponseError(PluginError):
pass | class Pluginerror(Exception):
pass
class Oneloginclienterror(PluginError):
pass
class Usernotfound(PluginError):
pass
class Factornotfound(PluginError):
pass
class Timeouterror(PluginError):
pass
class Apiresponseerror(PluginError):
pass |
YES = "LuckyChef"
NO = "UnluckyChef"
def solve():
for _ in range(int(input())):
x, y, k, n = map(int, input().split())
arr = []
for __ in range(n):
arr.append(list(map(int, input().split())))
remaining_pages = x - y
if remaining_pages <= 0:
print(YE... | yes = 'LuckyChef'
no = 'UnluckyChef'
def solve():
for _ in range(int(input())):
(x, y, k, n) = map(int, input().split())
arr = []
for __ in range(n):
arr.append(list(map(int, input().split())))
remaining_pages = x - y
if remaining_pages <= 0:
print(YE... |
class Board:
def __init__(self, lines):
self.data = []
self.has_won = False
for i, l in enumerate(lines):
self.data.append([int(x) for x in l.split()])
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self)
def final_score(sel... | class Board:
def __init__(self, lines):
self.data = []
self.has_won = False
for (i, l) in enumerate(lines):
self.data.append([int(x) for x in l.split()])
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self)
def final_score(... |
#!/usr/bin/env python3
NUMBER_OF_DIVS = 25
INCL_SPACES = True
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
if(INCL_SPACES):
divString = """
<div class="item{}">
<img class="rounded-img carousel-i... | number_of_divs = 25
incl_spaces = True
div_string = '\n<div class="item{}">\n <img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">\n</div>\n'
if INCL_SPACES:
div_string = '\n <div class="item{}">\n <img class="rounded-img carousel-img" id="carousel-img-{}... |
nome = input('Digite seu nome completo: ')
nomem = nome.upper()
nomemin = nome.lower()
fat = nome.split()
juntin = '-'.join(fat)
nomefatiado = nome.replace(" ", "")
print(len(nomefatiado))
print(nomemin)
print(nomem)
print(len(fat[0]))
print(fat)
print(juntin) | nome = input('Digite seu nome completo: ')
nomem = nome.upper()
nomemin = nome.lower()
fat = nome.split()
juntin = '-'.join(fat)
nomefatiado = nome.replace(' ', '')
print(len(nomefatiado))
print(nomemin)
print(nomem)
print(len(fat[0]))
print(fat)
print(juntin) |
def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with ope... | def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with ope... |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# Copy original array
new_arr = set(arr)
# Remove max values
new_arr.remove(max(new_arr))
# Print new max (2nd max)
print(max(new_arr))
| if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
new_arr = set(arr)
new_arr.remove(max(new_arr))
print(max(new_arr)) |
a, b, c = map(int, input().split())
if b - a == c - b:
print("YES")
else:
print("NO") | (a, b, c) = map(int, input().split())
if b - a == c - b:
print('YES')
else:
print('NO') |
# https://leetcode.com/problems/longest-valid-parentheses/
# Given a string containing just the characters '(' and ')', find the length of
# the longest valid (well-formed) parentheses substring.
################################################################################
# dp[i] = longest valid of s[i:n] starti... | class Solution:
def longest_valid_parentheses(self, s: str) -> int:
if len(s) <= 1:
return 0
n = len(s)
ans = 0
dp = [0] * n
for i in range(n - 2, -1, -1):
if s[i] == '(':
j = i + dp[i + 1] + 1
if j < n and s[j] == ')':... |
def fizz_buzz(n):
for fizz_buzz in range(n+1):
if fizz_buzz % 3 == 0 and fizz_buzz % 5 == 0:
print("fizzbuzz")
continue
elif fizz_buzz % 3 == 0:
print("fizz")
continue
elif fizz_buzz % 5 == 0:
print("buzz")
print(fizz_buzz)
... | def fizz_buzz(n):
for fizz_buzz in range(n + 1):
if fizz_buzz % 3 == 0 and fizz_buzz % 5 == 0:
print('fizzbuzz')
continue
elif fizz_buzz % 3 == 0:
print('fizz')
continue
elif fizz_buzz % 5 == 0:
print('buzz')
print(fizz_buzz... |
"""Unix shell commands toolchain support.
Defines a toolchain capturing common Unix shell commands as defined by IEEE
1003.1-2008 (POSIX), see `sh_posix_toolchain`, and `sh_posix_configure` to scan
the local environment for shell commands. The list of known commands is
available in `posix.commands`.
"""
load("@bazel... | """Unix shell commands toolchain support.
Defines a toolchain capturing common Unix shell commands as defined by IEEE
1003.1-2008 (POSIX), see `sh_posix_toolchain`, and `sh_posix_configure` to scan
the local environment for shell commands. The list of known commands is
available in `posix.commands`.
"""
load('@bazel_... |
#import GreenMindLib
msg_menu = '''
Use: sudo ./green -u http://businesscorp.com.br -o teste.txt \n\n
Green Recon
=============
Command Description
------- -----------
greenrecon Start recon OSINT
recon Suite recon OSINT
googl... | msg_menu = '\n\n Use: sudo ./green -u http://businesscorp.com.br -o teste.txt \n\n\nGreen Recon\n=============\n\n Command Description\n ------- -----------\n greenrecon Start recon OSINT\n recon Suite recon OSINT\n google_search ... |
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.9.5'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.9.5' |
_base_ = [
'../../_base_/default_runtime.py',
'../../_base_/schedules/schedule_sgd_1200e.py',
'../../_base_/det_models/dbnet_r18_fpnc.py',
'../../_base_/det_datasets/icdar2015.py',
'../../_base_/det_pipelines/dbnet_pipeline.py'
]
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list}}
... | _base_ = ['../../_base_/default_runtime.py', '../../_base_/schedules/schedule_sgd_1200e.py', '../../_base_/det_models/dbnet_r18_fpnc.py', '../../_base_/det_datasets/icdar2015.py', '../../_base_/det_pipelines/dbnet_pipeline.py']
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list}}
train_pipeline_r18 = {{_... |
class MoveNotFound(Exception):
pass
class CharacterNotFound(Exception):
pass
class OptionError(Exception):
pass
class LimitError(Exception):
pass
class CharacterMainError(Exception):
pass
class CharacterSubError(Exception):
pass
class CommandNotFound(Exception):
pass
class Comm... | class Movenotfound(Exception):
pass
class Characternotfound(Exception):
pass
class Optionerror(Exception):
pass
class Limiterror(Exception):
pass
class Charactermainerror(Exception):
pass
class Charactersuberror(Exception):
pass
class Commandnotfound(Exception):
pass
class Commandalre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.