content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
negative = False
if dividend < 0 and divisor < 0:
negative = False
elif dividend < 0 or divisor < 0:
negative = True
dividend, divisor = abs(dividend), abs(divisor)
... | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
negative = False
if dividend < 0 and divisor < 0:
negative = False
elif dividend < 0 or divisor < 0:
negative = True
(dividend, divisor) = (abs(dividend), abs(divisor))
result = 0
... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:java.bzl", "java_import_external")
def ts_repositories():
http_archive(
name = "io_bazel_rules_closure",
sha256 = "d66deed38a0bb20581c15664f0ab62270af5940786855c7adc3087b27168b529",
strip_... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:java.bzl', 'java_import_external')
def ts_repositories():
http_archive(name='io_bazel_rules_closure', sha256='d66deed38a0bb20581c15664f0ab62270af5940786855c7adc3087b27168b529', strip_prefix='rules_closure... |
# Input: String="aabccbb"
# Output: 3
# Explanation: The longest substring with distinct characters is "abc".
class DistinctCharMap(dict):
def __missing__(self, v):
return 0
def find_the_longest_substring_distinct(string, k=1):
distinct_char_map = DistinctCharMap()
temp_substring = ""
longest... | class Distinctcharmap(dict):
def __missing__(self, v):
return 0
def find_the_longest_substring_distinct(string, k=1):
distinct_char_map = distinct_char_map()
temp_substring = ''
longest_substring = ''
for i in range(len(string)):
char = string[i]
distinct_char_map[char] += ... |
n,m,k = map(int, input().split())
aa = list(map(int, input().split()))
a = []
for i in range(n):
a.append([aa[i], i+1])
a.sort()
if not(k%m):
t = int(k/m)
if t < 1:
print("impossible")
exit()
se =n - t
if n == 1:
if t == 1:
print(1)
exit()
else... | (n, m, k) = map(int, input().split())
aa = list(map(int, input().split()))
a = []
for i in range(n):
a.append([aa[i], i + 1])
a.sort()
if not k % m:
t = int(k / m)
if t < 1:
print('impossible')
exit()
se = n - t
if n == 1:
if t == 1:
print(1)
exit()
... |
# coding: utf-8
RESOURCE_MAPPING = {
'bookings': {
'resource': 'bookings/',
'docs': 'http://www.documentation.com/link/to/resource/documentation',
'methods': ['GET', 'POST']
},
}
| resource_mapping = {'bookings': {'resource': 'bookings/', 'docs': 'http://www.documentation.com/link/to/resource/documentation', 'methods': ['GET', 'POST']}} |
"""
Script that contains the story code
"""
class Color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
nerveGear = CYAN + "Nerve Ge... | """
Script that contains the story code
"""
class Color:
purple = '\x1b[95m'
cyan = '\x1b[96m'
darkcyan = '\x1b[36m'
blue = '\x1b[94m'
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
bold = '\x1b[1m'
underline = '\x1b[4m'
end = '\x1b[0m'
nerve_gear = CYAN + 'Nerve Ge... |
class Solution:
def minAddToMakeValid(self, S: str) -> int:
stack1=[]
stack2=[]
for i in range(len(S)):
if S[i] =="(":
stack1.append(S[i])
elif S[i]==")" and stack1:
stack1.pop()
else:
stack2.append(... | class Solution:
def min_add_to_make_valid(self, S: str) -> int:
stack1 = []
stack2 = []
for i in range(len(S)):
if S[i] == '(':
stack1.append(S[i])
elif S[i] == ')' and stack1:
stack1.pop()
else:
stack2.appe... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
TAG_XML = 'xml'
TAG_TESTSUITE = 'testsuite'
TAG_DETAILS = 'details'
TAG_TESTCASE = 'testcase'
TAG_VERSION = 'version'
TAG_SUMMARY = 'summary'
TAG_PRECONDITIONS = 'preconditions'
TAG_IMPORTANCE = 'importance'
TAG_ESTIMATED_EXEC_DURATION = 'estimated_exec_duration'
TAG_STAT... | tag_xml = 'xml'
tag_testsuite = 'testsuite'
tag_details = 'details'
tag_testcase = 'testcase'
tag_version = 'version'
tag_summary = 'summary'
tag_preconditions = 'preconditions'
tag_importance = 'importance'
tag_estimated_exec_duration = 'estimated_exec_duration'
tag_status = 'status'
tag_is_open = 'is_open'
tag_active... |
class credit_scrore_calculator_and_saver():
age = input("What's your age?\n")
gender = input("What's your gender?\n")
payment_history = input("How many loans you have you paid\n")
loans = input("How many loans do you have?\n")
loans_paid = input("How many loans you have paid\n")
credit_car... | class Credit_Scrore_Calculator_And_Saver:
age = input("What's your age?\n")
gender = input("What's your gender?\n")
payment_history = input('How many loans you have you paid\n')
loans = input('How many loans do you have?\n')
loans_paid = input('How many loans you have paid\n')
credit_card_utiliz... |
print('===========Digite a Placa e a Hora==========')
placa = input('Digite sua placa :')
hora =float(input('Digite a hora de entrada :'))
registro = placa
horas = hora * 3600
horaf = horas // 3600
placaSaida = input('Digite sua placa, para liberar, seu automovel! :')
horaSaida = int(input('Digite a hora de saida :'))... | print('===========Digite a Placa e a Hora==========')
placa = input('Digite sua placa :')
hora = float(input('Digite a hora de entrada :'))
registro = placa
horas = hora * 3600
horaf = horas // 3600
placa_saida = input('Digite sua placa, para liberar, seu automovel! :')
hora_saida = int(input('Digite a hora de saida :'... |
settings = {
'launch_path': '',
'auto_generate': False,
'auto_backup': False,
'JsonRpcUser': '',
'JsonRpcPassword': '',
'observer': '',
'num_addresses': 10,
'destination': '',
}
# Info about the settings are in ... | settings = {'launch_path': '', 'auto_generate': False, 'auto_backup': False, 'JsonRpcUser': '', 'JsonRpcPassword': '', 'observer': '', 'num_addresses': 10, 'destination': ''} |
x = 7
y = 11
print("x={}, y={}".format(x, y))
# swap: nonpythonic
# temp = x
# x = y
# y = temp
y, x = x, y
print("x={}, y={}".format(x, y))
| x = 7
y = 11
print('x={}, y={}'.format(x, y))
(y, x) = (x, y)
print('x={}, y={}'.format(x, y)) |
# -*- coding: utf-8 -*-
def make_urls(urlsource, *args, **kwargs):
if urlsource.kind == 'single':
return urlsource.url
raise NotImplementedError
| def make_urls(urlsource, *args, **kwargs):
if urlsource.kind == 'single':
return urlsource.url
raise NotImplementedError |
"""Jaden Smith, the son of Will Smith, is the star of films such as
The Karate Kid (2010) and After Earth (2013). Jaden is also known
or some of his philosophy that he delivers via Twitter.
When writing on Twitter, he is known for almost always capitalizing every word.
For simplicity, you'll have to capitalize each wor... | """Jaden Smith, the son of Will Smith, is the star of films such as
The Karate Kid (2010) and After Earth (2013). Jaden is also known
or some of his philosophy that he delivers via Twitter.
When writing on Twitter, he is known for almost always capitalizing every word.
For simplicity, you'll have to capitalize each wor... |
alarms = {
"0x00": {
"Category": "Public Alarm",
"Name": "Reset Alarm",
"SetCondition": " After the system reset, the reset alarm will be set automatically",
"ResetCondition": " Protocol instruction is cleared"
},
"0x01": {
"Category": "Public Alarm",
"Name": ... | alarms = {'0x00': {'Category': 'Public Alarm', 'Name': 'Reset Alarm', 'SetCondition': ' After the system reset, the reset alarm will be set automatically', 'ResetCondition': ' Protocol instruction is cleared'}, '0x01': {'Category': 'Public Alarm', 'Name': 'Undefined Instruction', 'SetCondition': 'Undifined instruction ... |
"""Base Class for Knowledge Base Query"""
class KBquery:
def __init__(self):
pass
def query(self, constrains):
return [] | """Base Class for Knowledge Base Query"""
class Kbquery:
def __init__(self):
pass
def query(self, constrains):
return [] |
class StandInLine:
def getWays(self, n, a, b):
if n <= 1:
return [0, 0]
a1, a2 = 1, 1
if n > 2:
for i in range(1, n + 1):
a1 *= i
a1 /= 2
a2 = a1 * 2 / n
return [a1, a2]
| class Standinline:
def get_ways(self, n, a, b):
if n <= 1:
return [0, 0]
(a1, a2) = (1, 1)
if n > 2:
for i in range(1, n + 1):
a1 *= i
a1 /= 2
a2 = a1 * 2 / n
return [a1, a2] |
class Solution:
def convert(self, s: str, numRows: int) -> str:
res = ['' for _ in range(numRows)]
curr_row = 0
for c in s:
res[curr_row] += c
if curr_row == 0: direction = 1
elif curr_row == numRows - 1: direction = -1
curr_row = (direction + ... | class Solution:
def convert(self, s: str, numRows: int) -> str:
res = ['' for _ in range(numRows)]
curr_row = 0
for c in s:
res[curr_row] += c
if curr_row == 0:
direction = 1
elif curr_row == numRows - 1:
direction = -1
... |
class Solution:
"""
@param nums:
@param k:
@return: return the length of subarray
"""
def smallestLengthII(self, nums, k):
n = len(nums)
prefixSum = [0 for _ in range(n + 1)]
for i in range(n):
prefixSum[i + 1] = prefixSum[i] + nums[i]
start = 1
... | class Solution:
"""
@param nums:
@param k:
@return: return the length of subarray
"""
def smallest_length_ii(self, nums, k):
n = len(nums)
prefix_sum = [0 for _ in range(n + 1)]
for i in range(n):
prefixSum[i + 1] = prefixSum[i] + nums[i]
start = 1
... |
isLoggedIn = False
credentials = {}
currentViewedRant = ""
feedItemId = 2
currentFeed = ""
rantToPost = ""
commentToPost = ""
notifs = []
notifInterval = 60 # interval in seconds
comments = []
commentLen = 0
commentInterval = 30 # interval in seconds
# threads
check_notifs = ""
check_comments = "" | is_logged_in = False
credentials = {}
current_viewed_rant = ''
feed_item_id = 2
current_feed = ''
rant_to_post = ''
comment_to_post = ''
notifs = []
notif_interval = 60
comments = []
comment_len = 0
comment_interval = 30
check_notifs = ''
check_comments = '' |
n = int(input())
coelhos = 0
ratos = 0
sapos = 0
for i in range(n):
quantia, tipo = input().split()
quantia = int(quantia)
if tipo == 'C':
coelhos += quantia
elif tipo == 'R':
ratos += quantia
else:
sapos += quantia
total = coelhos + ratos + sapos
print(f"Total: {total}... | n = int(input())
coelhos = 0
ratos = 0
sapos = 0
for i in range(n):
(quantia, tipo) = input().split()
quantia = int(quantia)
if tipo == 'C':
coelhos += quantia
elif tipo == 'R':
ratos += quantia
else:
sapos += quantia
total = coelhos + ratos + sapos
print(f'Total: {total} cob... |
class ScoreSaberException(Exception):
def __init__(self, status: int, url: str) -> None:
self.status = status
self.url = url
super().__init__(f"Score Saber returned {self.status} for {self.url}")
class NotFoundException(ScoreSaberException):
pass
class ServerException(ScoreSaberExce... | class Scoresaberexception(Exception):
def __init__(self, status: int, url: str) -> None:
self.status = status
self.url = url
super().__init__(f'Score Saber returned {self.status} for {self.url}')
class Notfoundexception(ScoreSaberException):
pass
class Serverexception(ScoreSaberExcept... |
#Finding the percentage
#https://www.hackerrank.com/challenges/finding-the-percentage/problem
if __name__ == '__main__':
n = int(raw_input())
student_marks = {}
for _ in range(n):
line = raw_input().split()
name, scores = line[0], line[1:]
scores = map(float, scores)
student... | if __name__ == '__main__':
n = int(raw_input())
student_marks = {}
for _ in range(n):
line = raw_input().split()
(name, scores) = (line[0], line[1:])
scores = map(float, scores)
student_marks[name] = scores
query_name = raw_input()
student_scores = student_marks[query... |
"""
default variables for cbstools
"""
TOPOLOGY_LUT_DIR = "/home/chris/Documents/code/python/cbstools-python/ToloplogyLUT/"
ATLAS_DIR = "/home/chris/mipav/plugins/atlases/brain-segmentation-prior3.0/"
DEFAULT_ATLAS = "brain-atlas-3.0.3.txt" | """
default variables for cbstools
"""
topology_lut_dir = '/home/chris/Documents/code/python/cbstools-python/ToloplogyLUT/'
atlas_dir = '/home/chris/mipav/plugins/atlases/brain-segmentation-prior3.0/'
default_atlas = 'brain-atlas-3.0.3.txt' |
"""
Common data structures used in the Bavard ecosystem, especially on the machine learning side of things. Includes data
structures related to chatbot conversations (in the :mod:`~bavard_ml_utils.types.conversations.conversation` module),
chatbot configuration and training data (in the :mod:`~bavard_ml_utils.types.age... | """
Common data structures used in the Bavard ecosystem, especially on the machine learning side of things. Includes data
structures related to chatbot conversations (in the :mod:`~bavard_ml_utils.types.conversations.conversation` module),
chatbot configuration and training data (in the :mod:`~bavard_ml_utils.types.age... |
grades = [80, 75, 90]
grades.append(100)
total = sum(grades)
length = len(grades)
average = total / length
grades_as_strings = [ str(grade) for grade in grades ]
grades_as_string = ', '.join(grades_as_strings)
print(f'Grades are: {grades_as_string}')
print(f'Average is {average}')
| grades = [80, 75, 90]
grades.append(100)
total = sum(grades)
length = len(grades)
average = total / length
grades_as_strings = [str(grade) for grade in grades]
grades_as_string = ', '.join(grades_as_strings)
print(f'Grades are: {grades_as_string}')
print(f'Average is {average}') |
'''
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4... | """
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4... |
PASSAGES = {} # type:ignore
START = None
INIT_STATE = None
| passages = {}
start = None
init_state = None |
class MonteCarloFrameSummary:
def __init__(self):
pass
@staticmethod
def closing_stockout_percentage(closing_stock: list, period_length: int):
""" Calculates the percentage of stock out that occurred during the period specified.
Args:
period_length (int): length of ... | class Montecarloframesummary:
def __init__(self):
pass
@staticmethod
def closing_stockout_percentage(closing_stock: list, period_length: int):
""" Calculates the percentage of stock out that occurred during the period specified.
Args:
period_length (int): length of... |
pass
| pass |
"""
112 / 112 test cases passed.
Runtime: 132 ms
Memory Usage: 19.9 MB
"""
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
rg = [[] for _ in range(n)]
in_deg = [0] * n
for sr, scs in enumerate(graph):
for sc in scs:
... | """
112 / 112 test cases passed.
Runtime: 132 ms
Memory Usage: 19.9 MB
"""
class Solution:
def eventual_safe_nodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
rg = [[] for _ in range(n)]
in_deg = [0] * n
for (sr, scs) in enumerate(graph):
for sc in scs:
... |
class PNMessageCountResult(object):
def __init__(self, result):
"""
Representation of message count server response
:param result: result of message count operation
"""
self._result = result
self.channels = result['channels']
def __str__(self):
return "M... | class Pnmessagecountresult(object):
def __init__(self, result):
"""
Representation of message count server response
:param result: result of message count operation
"""
self._result = result
self.channels = result['channels']
def __str__(self):
return '... |
# s: "The quick, superduperlong brown fox jumped over the lazy dog."
# limit: 10
# output: [
# "The quick,",
# "superduperlong",
# "brown fox",
# "jumped",
# "over the",
# "lazy dog.",
# ]
#
# s: ""
# output: [""]
# if single word exceeds limit, count it as its own entry in the output.
abc = "The qui... | abc = 'The quick, superduperlong brown fox jumped over the lazy dog.'
def text_chunker(text, limit):
output = []
text = text.split(' ')
curr_limit = ''
for word in text:
if len(word) + len(curr_limit) > limit - 1:
output.append(curr_limit)
curr_limit = word
elif ... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-pathway'
ES_DOC_TYPE = 'geneset'
API_PREFIX = 'geneset'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-pathway'
es_doc_type = 'geneset'
api_prefix = 'geneset'
api_version = '' |
CREATE_REPORTS = ('CREATE TABLE reports '
'(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'
'bug_id INTEGER NOT NULL,'
'current_resolution TEXT,'
'current_status TEXT,'
'opening INTEGER NOT NULL,'
'reporter INTEG... | create_reports = 'CREATE TABLE reports (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,bug_id INTEGER NOT NULL,current_resolution TEXT,current_status TEXT,opening INTEGER NOT NULL,reporter INTEGER NOT NULL)'
create_assigned_to = 'CREATE TABLE assigned_to(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,bug_id INTEGER NOT N... |
"""Authn/z-related exceptions raised by components in this module."""
class InvalidToken(ValueError):
"""Token in request is not valid."""
class MissingToken(ValueError):
"""No token found in request."""
class ConfigurationError(RuntimeError):
"""The application is not configured correctly."""
class... | """Authn/z-related exceptions raised by components in this module."""
class Invalidtoken(ValueError):
"""Token in request is not valid."""
class Missingtoken(ValueError):
"""No token found in request."""
class Configurationerror(RuntimeError):
"""The application is not configured correctly."""
class Ses... |
class Indent():
"""
indentation context
"""
def __init__(self, autoIndentStream):
self.s = autoIndentStream
self.original_indent = None
def __enter__(self):
s = self.s
self.original_indent = s.indent_str
s.indent_cnt += 1
s.indent_str = s.indent_str... | class Indent:
"""
indentation context
"""
def __init__(self, autoIndentStream):
self.s = autoIndentStream
self.original_indent = None
def __enter__(self):
s = self.s
self.original_indent = s.indent_str
s.indent_cnt += 1
s.indent_str = s.indent_str + ... |
"Generate a Kaggle submission file from VW predictions"
loc_preds = "data/shop.preds.txt"
loc_submission = "data/kaggle.submission.csv"
loc_test = "data/testHistory.csv"
def generate_submission(loc_preds, loc_test, loc_submission):
preds = {}
for e, line in enumerate( open(loc_preds) ):
row = line.strip().split("... | """Generate a Kaggle submission file from VW predictions"""
loc_preds = 'data/shop.preds.txt'
loc_submission = 'data/kaggle.submission.csv'
loc_test = 'data/testHistory.csv'
def generate_submission(loc_preds, loc_test, loc_submission):
preds = {}
for (e, line) in enumerate(open(loc_preds)):
row = line.... |
#############################################################################
# Copyright (c) 2017 Rajesh Kudaka
#
# Author: Rajesh Kudaka 4k.rajesh@gmail.com
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies th... | template = '\n<html>\n<body>\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">\n<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></scrip... |
'''
Author : Arnob Mahmud
Mail : arnob.tech.me @ gmail.com
'''
num = int(input("Enter starting number :"))
n = int(input("Enter ending number :"))
i = num
while i <= n:
print(i)
if i % 13 == 0:
break; # Breaks the loop if the upper condition been right
i = i + 1
| """
Author : Arnob Mahmud
Mail : arnob.tech.me @ gmail.com
"""
num = int(input('Enter starting number :'))
n = int(input('Enter ending number :'))
i = num
while i <= n:
print(i)
if i % 13 == 0:
break
i = i + 1 |
def make_node():
pass
def make_value_info():
pass
| def make_node():
pass
def make_value_info():
pass |
categorie="TELEPHONIE - GPS"
all_descr_clean_stem = " ".join(data[data.Categorie1==categorie].Description_cleaned.values)
wordcloud_word = WordCloud(background_color="black", collocations=False).generate_from_text(all_descr_clean_stem)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_word,cmap=plt.cm.Paired)
plt.axis(... | categorie = 'TELEPHONIE - GPS'
all_descr_clean_stem = ' '.join(data[data.Categorie1 == categorie].Description_cleaned.values)
wordcloud_word = word_cloud(background_color='black', collocations=False).generate_from_text(all_descr_clean_stem)
plt.figure(figsize=(10, 10))
plt.imshow(wordcloud_word, cmap=plt.cm.Paired)
plt... |
####################################################################################################################
# Functions - Lab Exercise 2
#
# Write a function called odds_or_evens that takes a boolean and a list of integers as parameters.
# If the boolean parameter is True, r... | def odds_or_evens(boolean, my_list):
if boolean:
for i in my_list:
if i % 2 != 0:
my_list.remove(i)
else:
for i in my_list:
if i % 2 == 0:
my_list.remove(i)
return my_list
def odds_or_evens(my_bool, nums):
"""Returns all of the odd... |
def minutes_to_hours(seconds, minutes=70):
hours = minutes / 60.0 + seconds / 3600
return hours
print(minutes_to_hours(300, 200))
# oppure si puo' scrivere:
# def minutes_to_hours(seconds, minutes=70):
# hours = minutes / 60.0 + seconds / 3600
# print(hours)
# (minutes_to_hours(300, 200))
# for ... | def minutes_to_hours(seconds, minutes=70):
hours = minutes / 60.0 + seconds / 3600
return hours
print(minutes_to_hours(300, 200))
def age_foo(age):
new_age = float(age) + 50
return new_age
age = input('Enter your age: ')
print(age_foo(age)) |
def count_values(dictionary):
"""
"""
seen_values = set()
for i in dictionary:
seen_values.add(dictionary[i])
return len(seen_values)
print(count_values({'red': 1, 'green': 1, 'blue': 2, 'yellow': 3, 'purp': 2}))
| def count_values(dictionary):
"""
"""
seen_values = set()
for i in dictionary:
seen_values.add(dictionary[i])
return len(seen_values)
print(count_values({'red': 1, 'green': 1, 'blue': 2, 'yellow': 3, 'purp': 2})) |
i = 1
for n in range(5):
globals()["w" + str(i)] = "adi"
i += 1
print(w2) | i = 1
for n in range(5):
globals()['w' + str(i)] = 'adi'
i += 1
print(w2) |
class Serialreader:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\r")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, sel... | class Serialreader:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b'\r')
if i >= 0:
r = self.buf[:i + 1]
self.buf = self.buf[i + 1:]
return r
while True:
i = max(1, min(2048... |
i = int(input("Enter a number: "))
if i%5 == 0:
print('Hello')
else:
print('Bye')
| i = int(input('Enter a number: '))
if i % 5 == 0:
print('Hello')
else:
print('Bye') |
class Helper:
"""
Container for helper functions
"""
@staticmethod
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i + n]
@staticmethod
def find_pattern(header, pattern):
... | class Helper:
"""
Container for helper functions
"""
@staticmethod
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
"""
for i in range(0, len(l), n):
yield l[i:i + n]
@staticmethod
def find_pattern(header, pattern):
"""
... |
class Users(THE_DATABASE.Model):
# this uses SqlAlchemy to create User classes when pulling data from the database
__tablename__ = 'Users'
username = THE_DATABASE.Column(THE_DATABASE.String(128),primary_key = True)
password = THE_DATABASE.Column(THE_DATABASE.String(64))
def __init__(self,input_user... | class Users(THE_DATABASE.Model):
__tablename__ = 'Users'
username = THE_DATABASE.Column(THE_DATABASE.String(128), primary_key=True)
password = THE_DATABASE.Column(THE_DATABASE.String(64))
def __init__(self, input_username, input_password):
self.password = input_password
self.username = ... |
t=int(input())
for i in range(t):
x1,x2,y1,y2,z1,z2=map(int,input().split())
if(x1<=x2 and y1<=y2 and z1>=z2):
print("yes")
else:
print("no")
| t = int(input())
for i in range(t):
(x1, x2, y1, y2, z1, z2) = map(int, input().split())
if x1 <= x2 and y1 <= y2 and (z1 >= z2):
print('yes')
else:
print('no') |
# time 30mins
# cost: 22 mins
# actually i was thinking of it in shower, so takes more time than recorded
class Solution:
"""
@param S: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, S):
# recursive
S.sort()
firs... | class Solution:
"""
@param S: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsets_with_dup(self, S):
S.sort()
(first, last) = self.subsets_recursion_helper(S)
return first + last
def subsets_recursion_helper(self, S):
if S is None:
... |
def new():
pass
| def new():
pass |
"""
Horizontal Split Panel: Left and Right layouts with a movable splitter.
/*
* Copyright 2008 Google Inc.
* Copyright 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the "License") you may not
* use this file except in compliance with the License. You m... | """
Horizontal Split Panel: Left and Right layouts with a movable splitter.
/*
* Copyright 2008 Google Inc.
* Copyright 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the "License") you may not
* use this file except in compliance with the License. You m... |
class LeadRecord:
def __init__(self):
self.attributes = {}
def __str__(self):
return "Lead (%s - %s)" % (self.id, self.email)
def __repr__(self):
return self.__str__()
def unwrap(xml):
lead = LeadRecord()
lead.id = xml.find('Id').text
lead.email = xml.find('Email')... | class Leadrecord:
def __init__(self):
self.attributes = {}
def __str__(self):
return 'Lead (%s - %s)' % (self.id, self.email)
def __repr__(self):
return self.__str__()
def unwrap(xml):
lead = lead_record()
lead.id = xml.find('Id').text
lead.email = xml.find('Email').t... |
# def pow2(x):
# return x**2
# for x in map(pow2, range(1,5)):
# print(x)
# for n in map(pow, range(1,10), range(4,0,-1)):
# print(n)
#==========practice=============
#1. 1**2 + 2**2 + 3**2........+9**2
print("pow2 total is: ",sum(map(lambda x: x**2, range(1,10))))
#2. 1**3 + 2**3 + 3**3........+9**3
to... | print('pow2 total is: ', sum(map(lambda x: x ** 2, range(1, 10))))
total = 0
pow3 = lambda n: n ** 3
for x in map(pow3, range(1, 10)):
total += x
print('pow3 total is: ', total)
total = 0
for x in map(pow, range(1, 10), range(9, 0, -1)):
total += x
print('pow total is: ', total) |
# a*x+b=y
def a_line (a,b):
# def arg_y (x):
# y = a*x+b
# return y
y = lambda x:a*x+b
return y
# a=3,b=5
# x=10,y=?
# x=20,y=?
line1 = a_line(3,5)
line2 = a_line(5,10)
print(line1(10))
print(line1(20))
print(line2(10))
print(line2(20)) | def a_line(a, b):
y = lambda x: a * x + b
return y
line1 = a_line(3, 5)
line2 = a_line(5, 10)
print(line1(10))
print(line1(20))
print(line2(10))
print(line2(20)) |
#!/usr/bin/env python
# coding=utf-8
# author: zengyuetian
if __name__ == '__main__':
pass | if __name__ == '__main__':
pass |
class Solution:
def longestAwesome(self, s: str) -> int:
ans = 0
prefix = 0 # binary prefix
prefixToIndex = [len(s)] * 1024
prefixToIndex[0] = -1
for i, c in enumerate(s):
prefix ^= 1 << ord(c) - ord('0')
ans = max(ans, i - prefixToIndex[prefix])
for j in range(10):
ans... | class Solution:
def longest_awesome(self, s: str) -> int:
ans = 0
prefix = 0
prefix_to_index = [len(s)] * 1024
prefixToIndex[0] = -1
for (i, c) in enumerate(s):
prefix ^= 1 << ord(c) - ord('0')
ans = max(ans, i - prefixToIndex[prefix])
for... |
__author__ = 'Tyler Rudie'
class article(object):
Date = ''
Publisher = ''
Title = ''
URL = ''
Term = ''
def __init__(self, Date, Publisher, Title, URL, Term):
self.Date = Date
self.Publisher = Publisher
se... | __author__ = 'Tyler Rudie'
class Article(object):
date = ''
publisher = ''
title = ''
url = ''
term = ''
def __init__(self, Date, Publisher, Title, URL, Term):
self.Date = Date
self.Publisher = Publisher
self.Title = Title
self.URL = URL
self.Term = Term... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class CakeError(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
| class Cakeerror(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name |
#
# PySNMP MIB module HH3C-EPON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-EPON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:13:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (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, single_value_constraint, constraints_intersection) ... |
#
# PySNMP MIB module COMMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMMON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
"""
Author: Resul Emre AYGAN
"""
"""
Project Description: Find The Parity Outlier
You are given an array (which will have a length of at least 3, but could be very large) containing integers.
The array is either entirely comprised of odd integers or entirely comprised of even integers except
for a single integer N.
W... | """
Author: Resul Emre AYGAN
"""
'\nProject Description: Find The Parity Outlier\n\nYou are given an array (which will have a length of at least 3, but could be very large) containing integers.\nThe array is either entirely comprised of odd integers or entirely comprised of even integers except\nfor a single integer N.... |
class singleton:
def __init__(self, undecoratedClass):
self.undecoratedClass = undecoratedClass
self.instance = None
def __call__(self, *args, **kwargs):
print(self.undecoratedClass.closed)
if self.undecoratedClass.closed is True:
self.instance = None
if se... | class Singleton:
def __init__(self, undecoratedClass):
self.undecoratedClass = undecoratedClass
self.instance = None
def __call__(self, *args, **kwargs):
print(self.undecoratedClass.closed)
if self.undecoratedClass.closed is True:
self.instance = None
if sel... |
# https://app.codesignal.com/interview-practice/task/dYCH8sdnxGf5aGkez/solutions
def decodeString(string):
final_output = []
for c in string:
if c != ']':
final_output.append(c)
else:
s = []
while(final_output[-1] != '['):
s.append(final_output... | def decode_string(string):
final_output = []
for c in string:
if c != ']':
final_output.append(c)
else:
s = []
while final_output[-1] != '[':
s.append(final_output.pop())
pop_bracket = final_output.pop()
number = []
... |
"Rules to verify and update pip-compile locked requirements.txt"
load("//python:defs.bzl", "py_binary", "py_test")
load("//python/pip_install:repositories.bzl", "requirement")
def compile_pip_requirements(
name,
extra_args = [],
visibility = ["//visibility:private"],
requirements_in = ... | """Rules to verify and update pip-compile locked requirements.txt"""
load('//python:defs.bzl', 'py_binary', 'py_test')
load('//python/pip_install:repositories.bzl', 'requirement')
def compile_pip_requirements(name, extra_args=[], visibility=['//visibility:private'], requirements_in=None, requirements_txt=None, **kwarg... |
def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
n = int(input())
matrix = []
for _ in range(n):
matrix.append([int(el) for el in input().split()])
all_directions = {
"up": (-1, 0),
"down": (1, 0),
"left": (0, -1),
"right": (0, 1),
"up_lef... | def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
n = int(input())
matrix = []
for _ in range(n):
matrix.append([int(el) for el in input().split()])
all_directions = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1), 'up_left': (-1, -1), 'up_right'... |
'''
Logging module for Sublime Text plugins. Tries to emulate normal Python logger.
by @blopker
'''
debug = False
class Logger(object):
def __init__(self, name):
self.name = name
def debug(self, *messages):
if not debug:
return
self._out('DEBUG', *messages)
def info(... | """
Logging module for Sublime Text plugins. Tries to emulate normal Python logger.
by @blopker
"""
debug = False
class Logger(object):
def __init__(self, name):
self.name = name
def debug(self, *messages):
if not debug:
return
self._out('DEBUG', *messages)
def info(s... |
# Recursers can create their personal access token at https://www.recurse.com/settings/apps
# To use the tool, create your personal access token and replace the fake access token below.
PERSONAL_ACCESS_TOKEN = "123456"
AUTH_HEADER = {"Authorization": "Bearer {}".format(PERSONAL_ACCESS_TOKEN)}
| personal_access_token = '123456'
auth_header = {'Authorization': 'Bearer {}'.format(PERSONAL_ACCESS_TOKEN)} |
def is_alphanumeric(word: str, valid_punctuation_marks: str = '-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are val... | def is_alphanumeric(word: str, valid_punctuation_marks: str='-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are valid... |
"""
embedeval
~~~~~~~~~
NLP Embedding Evaluation Tool
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
| """
embedeval
~~~~~~~~~
NLP Embedding Evaluation Tool
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
""" |
# Variables
center_x=50
center_y=50
diameter=10
ellipse(center_x,center_y,diameter,diameter)
# Variables allow us to make changes on them
# Let's make some changes on the variables
diameter=diameter+2
center_x=center_x+diameter
ellipse(center_x,center_y,diameter,diameter)
diameter=diameter+2
center_x=center_x+diamet... | center_x = 50
center_y = 50
diameter = 10
ellipse(center_x, center_y, diameter, diameter)
diameter = diameter + 2
center_x = center_x + diameter
ellipse(center_x, center_y, diameter, diameter)
diameter = diameter + 2
center_x = center_x + diameter
ellipse(center_x, center_y, diameter, diameter)
diameter = diameter + 2
... |
"""
[07/17/13] Challenge #130 [Intermediate] Foot-Traffic Generator
https://www.reddit.com/r/dailyprogrammer/comments/1ihm0q/071713_challenge_130_intermediate_foottraffic/
# [](#IntermediateIcon) *(Intermediate)*: Foot-Traffic Generator
This week's [Easy] challenge was [#133: Foot-Traffic
Analysis](http://www.reddit.... | """
[07/17/13] Challenge #130 [Intermediate] Foot-Traffic Generator
https://www.reddit.com/r/dailyprogrammer/comments/1ihm0q/071713_challenge_130_intermediate_foottraffic/
# [](#IntermediateIcon) *(Intermediate)*: Foot-Traffic Generator
This week's [Easy] challenge was [#133: Foot-Traffic
Analysis](http://www.reddit.... |
class Solution:
def solve(self, a, b, c):
dp = [[[0]*(len(c)+1) for j in range(len(b)+1)] for i in range(len(a)+1)]
ans = 0
for i in range(1,len(a)+1):
for j in range(1,len(b)+1):
for k in range(1,len(c)+1):
if a[i-1] == b[j-1] == c[k-1]:
... | class Solution:
def solve(self, a, b, c):
dp = [[[0] * (len(c) + 1) for j in range(len(b) + 1)] for i in range(len(a) + 1)]
ans = 0
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
for k in range(1, len(c) + 1):
if a[i - 1] == b[j... |
"""
Configuration file for the Python Atmospheric data Community Toolkit (ACT)
The values for a number of ACT parameters and the default metadata created
when reading files, correcting fields, etc. is controlled by this single
Python configuration file.
Examples:
---------
from act.config import DEFAULT_DATASTREAM_NAM... | """
Configuration file for the Python Atmospheric data Community Toolkit (ACT)
The values for a number of ACT parameters and the default metadata created
when reading files, correcting fields, etc. is controlled by this single
Python configuration file.
Examples:
---------
from act.config import DEFAULT_DATASTREAM_NAM... |
'''
Given the head of a singly linked list, reverse the list, and return the reversed list.
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
cur = head
p... | """
Given the head of a singly linked list, reverse the list, and return the reversed list.
"""
class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_list(self, head):
cur = head
prev = None
while cur:
... |
#Upon clicking, saves everything in hdf5 queue. Meant to be click after "Start" has already been pressed
def save(arr_in):
# HDF5
try:
hdf5.queue.put_nowait((frame_time, data_cube_corr))
num_cubes_stored += 1 # executed if above was successful
except:
pass
... | def save(arr_in):
try:
hdf5.queue.put_nowait((frame_time, data_cube_corr))
num_cubes_stored += 1
except:
pass
return () |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
N = len(A)
if N <= 1: return 0
start_list = []
end_list = []
for i, radius in enumerate(A):
left, right = i - radius, i + radius
start_list... | def solution(A):
n = len(A)
if N <= 1:
return 0
start_list = []
end_list = []
for (i, radius) in enumerate(A):
(left, right) = (i - radius, i + radius)
start_list.append(left)
end_list.append(right)
start_list.sort()
end_list.sort()
cur_started = 0
idx... |
n = int(input())
s = input()
def remove(s):
actC = 'a'
actI = -1
for i in range(len(s)):
if i > 0:
if ord(s[i])-ord(s[i-1]) == 1 and s[i] > actC:
actC = s[i]
actI = i
if i < len(s)-1:
if ord(s[i])-ord(s[i+1]) == 1 and s[i] > actC:
... | n = int(input())
s = input()
def remove(s):
act_c = 'a'
act_i = -1
for i in range(len(s)):
if i > 0:
if ord(s[i]) - ord(s[i - 1]) == 1 and s[i] > actC:
act_c = s[i]
act_i = i
if i < len(s) - 1:
if ord(s[i]) - ord(s[i + 1]) == 1 and s[i... |
class Sender:
def __init__(self):
self.subscribers = []
def __call__(self, *args, **kwargs):
for subscriber in self.subscribers:
subscriber(*args, **kwargs)
def __iadd__(self, handler):
self.subscribers.append(handler)
return self
def __isub__(self, handler... | class Sender:
def __init__(self):
self.subscribers = []
def __call__(self, *args, **kwargs):
for subscriber in self.subscribers:
subscriber(*args, **kwargs)
def __iadd__(self, handler):
self.subscribers.append(handler)
return self
def __isub__(self, handle... |
config = {
"palette": [255],
"loss": "bce_dice",
"gamma": 2.0, # focal loss gamma
"optimizer": "sgd",
"freeze": False,
"freeze_at": 24,
"dropout_rate": 0.1,
"momentum": 0.9,
"learning_rate": 0.1,
# (216, 320, 1) # (270, 400, 1) # (432, 640, 1)
"image_size": (216, 320, 1),
... | config = {'palette': [255], 'loss': 'bce_dice', 'gamma': 2.0, 'optimizer': 'sgd', 'freeze': False, 'freeze_at': 24, 'dropout_rate': 0.1, 'momentum': 0.9, 'learning_rate': 0.1, 'image_size': (216, 320, 1), 'batch_size': 16, 'epochs': 200} |
class InvestmentProperty:
REQUIRED_KW_ARGS = []
#####################################
# Required args for instantiation:
#####################################
# property (dict):
# list_price=float
# maintenance_costs_monthly:float
# other_costs_monthly:float
# propert... | class Investmentproperty:
required_kw_args = []
def __init__(self, **kwargs):
pass |
__author__ = 'Chetan'
class Actor(object):
def __init__(self):
self.isBusy = False
def occupied(self):
self.isBusy = True
print(type(self).__name__ , "is occupied with current movie")
def available(self):
self.isBusy = False
print(type(sel... | __author__ = 'Chetan'
class Actor(object):
def __init__(self):
self.isBusy = False
def occupied(self):
self.isBusy = True
print(type(self).__name__, 'is occupied with current movie')
def available(self):
self.isBusy = False
print(type(self).__name__, 'is free for ... |
class UserListSubclass(list):
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
def __setslice__(self, i, j, seq):
return self.__setitem__(slice(i, j), seq)
def __delslice__(self, i, j):
return self.__delitem__(slice(i, j))
# Subclass this class if you need to overw... | class Userlistsubclass(list):
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
def __setslice__(self, i, j, seq):
return self.__setitem__(slice(i, j), seq)
def __delslice__(self, i, j):
return self.__delitem__(slice(i, j)) |
li = [123, 456, 567, 789]
param = 456
if param in li:
print(li.index(param))
li = []
if not li:
print('[]')
else:
print('True') | li = [123, 456, 567, 789]
param = 456
if param in li:
print(li.index(param))
li = []
if not li:
print('[]')
else:
print('True') |
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# Runtime: 138 ms, faster than 47.61% of Python3 online submissions for Remove Duplicates from Sorted Array.
# Memory Usage: 15.6 MB, less than 21.60% of Python3 online submissions for Remove Duplicates from Sorted Array.
class Solution:
def re... | class Solution:
def remove_duplicates(self, nums: list[int]) -> int:
k = 0
for i in range(len(nums)):
if i < len(nums) - 1 and nums[i] == nums[i + 1]:
continue
nums[k] = nums[i]
k += 1
return k |
annual_salary = input("Enter your annual income: ")
if len(annual_salary) < 1 : annual_salary = 150000
annual_salary = float(annual_salary)
total_cost = 1000000.00
semi_annual_raise = 0.07
portion_down_payment = 0.25
r = 0.04
down_payment = total_cost * portion_down_payment
portion_saved = 0
portion_percent = 0.0
por... | annual_salary = input('Enter your annual income: ')
if len(annual_salary) < 1:
annual_salary = 150000
annual_salary = float(annual_salary)
total_cost = 1000000.0
semi_annual_raise = 0.07
portion_down_payment = 0.25
r = 0.04
down_payment = total_cost * portion_down_payment
portion_saved = 0
portion_percent = 0.0
por... |
class Timer:
def __init__(self, time, delegate):
self.delegate = delegate
self.time = time
self.elapsed = 0
self.active = True
self.payload = None
self.name = ""
def step(self, dt):
if not self.active:
return
self.elapsed += dt
... | class Timer:
def __init__(self, time, delegate):
self.delegate = delegate
self.time = time
self.elapsed = 0
self.active = True
self.payload = None
self.name = ''
def step(self, dt):
if not self.active:
return
self.elapsed += dt
... |
class GameState():
def __init__(self):
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
... | class Gamestate:
def __init__(self):
self.board = [['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'], ['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--',... |
# Complete the compareTriplets function below.
class Triplets:
def __init__(self):
self.result = [0,0]
def compareTriplets(self, a, b):
if self.problem_clarity(a, b) and self.originality(a, b):
return self.difficulty(a, b)
return None
def problem_clarity(self, a, b):
... | class Triplets:
def __init__(self):
self.result = [0, 0]
def compare_triplets(self, a, b):
if self.problem_clarity(a, b) and self.originality(a, b):
return self.difficulty(a, b)
return None
def problem_clarity(self, a, b):
if a[0] < b[0] and a[0] != b[0]:
... |
with open('task3.html', 'w') as f:
f.write('<html><body><table>\n')
for i in range(1, 11):
f.write('<tr>')
for j in range(1, 11):
f.write(f'<td><a href=http://{i*j}.ru>{i*j}</a></td>')
f.write('</tr>\n')
f.write('</table></body></html>')
s = 'Python'
ans = 0
for c in s:
... | with open('task3.html', 'w') as f:
f.write('<html><body><table>\n')
for i in range(1, 11):
f.write('<tr>')
for j in range(1, 11):
f.write(f'<td><a href=http://{i * j}.ru>{i * j}</a></td>')
f.write('</tr>\n')
f.write('</table></body></html>')
s = 'Python'
ans = 0
for c in ... |
h = set()
history = []
r3 = 65536
r4 = 16098955
while True:
r4 = (r4 + (r3 & 255)) & 16777215
r4 = (r4 * 65899) & 16777215
if r3 < 256:
if len(h) == 0:
print(r4)
if r4 in h:
print(history[-1])
break
h.add(r4)
history.append(r4)
r3 ... | h = set()
history = []
r3 = 65536
r4 = 16098955
while True:
r4 = r4 + (r3 & 255) & 16777215
r4 = r4 * 65899 & 16777215
if r3 < 256:
if len(h) == 0:
print(r4)
if r4 in h:
print(history[-1])
break
h.add(r4)
history.append(r4)
r3 = r4 ... |
"""
Tools to update the ISO registry.
"""
def iso_register(iso_code):
"""
Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from workalendar.core import Calendar
>>> @iso_register('MC-MR')
>>> class MyR... | """
Tools to update the ISO registry.
"""
def iso_register(iso_code):
"""
Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from workalendar.core import Calendar
>>> @iso_register('MC-MR')
>>> class MyRe... |
data = {
"AUG": 'Methionine',
"UUU": 'Phenylalanine',
"UUC": 'Phenylalanine',
"UUA": 'Leucine',
"UUG": 'Leucine',
"UCU": 'Serine',
"UCC": 'Serine',
"UCA": 'Serine',
"UCG": 'Serine',
"UAU": 'Tyrosine',
"UAC": 'Tyrosine',
"UGU": 'Cysteine',
"UGC": 'Cysteine',
"UGG": 'Tryptophan',
"UAA": 'STOP',
"UAG": 'ST... | data = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UCG': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan', 'UAA': 'STOP', 'UAG': 'STOP', 'UGA': 'STOP... |
class Tuple(tuple):
def __new__(cls, *args):
assert len(args) == 3
return super().__new__(cls, args)
# This doesn't work.
# def __init__(self, *args):
# assert len(args) == 3
# return tuple.__init__(self, args)
# or
# return tuple.__init__(self, *args)
| class Tuple(tuple):
def __new__(cls, *args):
assert len(args) == 3
return super().__new__(cls, args) |
numero = input()
horasTrabalhadas = float(input())
valorHora = float(input())
print(f'NUMBER = {numero}')
print(f'SALARY = U$ {horasTrabalhadas * valorHora:.2f}') | numero = input()
horas_trabalhadas = float(input())
valor_hora = float(input())
print(f'NUMBER = {numero}')
print(f'SALARY = U$ {horasTrabalhadas * valorHora:.2f}') |
def bin_hours_per_week(hpw):
"""
Bin the hours per week variable into 0-30, 31-40, 41-50, 50+ bins.
"""
if hpw <= 30:
return 0
elif hpw <= 40:
return 1
elif hpw <= 50:
return 2
return 3
| def bin_hours_per_week(hpw):
"""
Bin the hours per week variable into 0-30, 31-40, 41-50, 50+ bins.
"""
if hpw <= 30:
return 0
elif hpw <= 40:
return 1
elif hpw <= 50:
return 2
return 3 |
class IncorrectFileFormat(Exception):
pass
class NoConfigFileFound(Exception):
pass
| class Incorrectfileformat(Exception):
pass
class Noconfigfilefound(Exception):
pass |
#
# PySNMP MIB module A3COM-HUAWEI-DHCPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (huawei_mgmt, hw_dhcp) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'huaweiMgmt', 'hwDhcp')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_interse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.