content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
"""A helper method to register a rule (and optionally a view function)
to the application. The endpoint is automatically prefixed with the
blueprint's name.
"""
if self.url_prefix is not None:
if rule:
rule ... | def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
"""A helper method to register a rule (and optionally a view function)
to the application. The endpoint is automatically prefixed with the
blueprint's name.
"""
if self.url_prefix is not None:
if rule:
rule ... |
class ModelSingleton(object):
# https://stackoverflow.com/a/6798042
_instances = {}
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
class_._instances[class_] = super(ModelSingleton, class_).__new__(class_, *args, **kwargs)
return class_._instances[class... | class Modelsingleton(object):
_instances = {}
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
class_._instances[class_] = super(ModelSingleton, class_).__new__(class_, *args, **kwargs)
return class_._instances[class_]
class Sharedmodel(ModelSingleton):
... |
tabuleiro_easy_1 = [
[4, 0, 1, 8, 3, 9, 5, 2, 0],
[3, 0, 9, 2, 7, 5, 1, 4, 6],
[5, 2, 7, 6, 0, 1, 9, 8, 0],
[0, 5, 8, 1, 0, 7, 3, 9, 4],
[0, 7, 3, 9, 8, 4, 2, 5, 0],
[9, 1, 4, 5, 2, 3, 6, 7, 8],
[7, 4, 0, 3, 0, 6, 8, 1, 2],
[8, 0, 6, 4, 1, 2, 7, 3, 5],
[1, 3, 2, 7, 5, 8, 4, 0, 9... | tabuleiro_easy_1 = [[4, 0, 1, 8, 3, 9, 5, 2, 0], [3, 0, 9, 2, 7, 5, 1, 4, 6], [5, 2, 7, 6, 0, 1, 9, 8, 0], [0, 5, 8, 1, 0, 7, 3, 9, 4], [0, 7, 3, 9, 8, 4, 2, 5, 0], [9, 1, 4, 5, 2, 3, 6, 7, 8], [7, 4, 0, 3, 0, 6, 8, 1, 2], [8, 0, 6, 4, 1, 2, 7, 3, 5], [1, 3, 2, 7, 5, 8, 4, 0, 9]]
tabuleiro_easy_2 = [[0, 6, 1, 8, 0, 0, ... |
class Config(object):
def __init__(self, vocab_size, max_length):
self.vocab_size = vocab_size
self.embedding_size = 300
self.hidden_size = 200
self.filters = [3, 4, 5]
self.num_filters = 256
self.num_classes = 10
self.max_length = max_length
self.num_... | class Config(object):
def __init__(self, vocab_size, max_length):
self.vocab_size = vocab_size
self.embedding_size = 300
self.hidden_size = 200
self.filters = [3, 4, 5]
self.num_filters = 256
self.num_classes = 10
self.max_length = max_length
self.num... |
#Mayor de edad
mayor=int(input("edad: "))
if(mayor >=18):
print("es mator de edad")
else:
print("es menor de edad")
| mayor = int(input('edad: '))
if mayor >= 18:
print('es mator de edad')
else:
print('es menor de edad') |
"""Top-level package for Python Boilerplate."""
__author__ = """Nate Solon"""
__email__ = 'nate.solon@gmail.com'
__version__ = '0.1.0'
| """Top-level package for Python Boilerplate."""
__author__ = 'Nate Solon'
__email__ = 'nate.solon@gmail.com'
__version__ = '0.1.0' |
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given a word W and a string S, find all starting indices in S which are anagrams of W.
For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4.
"""
def verify_string_combos(word, string):
"""
... | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given a word W and a string S, find all starting indices in S which are anagrams of W.
For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4.
"""
def verify_string_combos(word, string):
"""
... |
#!/usr/bin/env python3
# implicit None return
def say_hi():
print("hey there")
# implicit artument return "name"
def yell_name(name='Adrienne'):
"""
this is a doc string
also this function returns the arg by default
"""
print("YO {0} ".format(name.upper()))
# scoping
def add(num1=0, num2=0... | def say_hi():
print('hey there')
def yell_name(name='Adrienne'):
"""
this is a doc string
also this function returns the arg by default
"""
print('YO {0} '.format(name.upper()))
def add(num1=0, num2=0):
"""
adds the 2 numbers. doy
"""
num1 = num1 + num2
print(num1)
retu... |
""" Module for a sudoku Cell with row, column position """
class Cell:
""" A Sudoku cell """
def __init__(self, row: int, column: int):
"""
A Cell at the given row and column
:param row: The 1-indexed row of the cell
:param column: The 1-indexed column of the cell
"""
... | """ Module for a sudoku Cell with row, column position """
class Cell:
""" A Sudoku cell """
def __init__(self, row: int, column: int):
"""
A Cell at the given row and column
:param row: The 1-indexed row of the cell
:param column: The 1-indexed column of the cell
"""
... |
def getBASIC():
list = []
n = input()
while True:
line = n
if n.endswith('END'):
list.append(line)
return list
else:
list.append(line)
newN = input()
n = newN
| def get_basic():
list = []
n = input()
while True:
line = n
if n.endswith('END'):
list.append(line)
return list
else:
list.append(line)
new_n = input()
n = newN |
type_of_flowers = input()
count = int(input())
budget = int(input())
prices = {
"Roses": 5.00,
"Dahlias": 3.80,
"Tulips": 2.80,
"Narcissus": 3.00,
"Gladiolus": 2.50
}
price = count * prices[type_of_flowers]
if type_of_flowers == "Roses" and count > 80:
price -= 0.10 * price
elif type_of_flowe... | type_of_flowers = input()
count = int(input())
budget = int(input())
prices = {'Roses': 5.0, 'Dahlias': 3.8, 'Tulips': 2.8, 'Narcissus': 3.0, 'Gladiolus': 2.5}
price = count * prices[type_of_flowers]
if type_of_flowers == 'Roses' and count > 80:
price -= 0.1 * price
elif type_of_flowers == 'Dahlias' and count > 90:... |
#170
# Time: O(n)
# Space: O(n)
# Design and implement a TwoSum class. It should support the following operations: add and find.
#
# add - Add the number to an internal data structure.
# find - Find if there exists any pair of numbers which sum is equal to the value.
#
# For example,
# add(1); add(3); add(5);
# ... | class Twosumiii:
def __init__(self):
self.num_count = {}
def add(self, val):
if val in self.num_count:
self.num_count[val] += 1
else:
self.num_count[val] = 1
def find(self, target):
for num in self.num_count:
if target - num in self.num_... |
def flatten(d: dict, new_d, path=''):
for key, value in d.items():
if not isinstance(value, dict):
new_d[path + key] = value
else:
path += f'{key}.'
return flatten(d[key], new_d, path=path)
return new_d
if __name__ == "__main__":
d = {"foo": 42,
... | def flatten(d: dict, new_d, path=''):
for (key, value) in d.items():
if not isinstance(value, dict):
new_d[path + key] = value
else:
path += f'{key}.'
return flatten(d[key], new_d, path=path)
return new_d
if __name__ == '__main__':
d = {'foo': 42, 'bar': '... |
class BotovodException(Exception):
pass
class AgentException(BotovodException):
pass
class AgentNotExistException(BotovodException):
def __init__(self, name: str):
super().__init__(f"Botovod have not '{name}' agent")
self.name = name
class HandlerNotPassed(BotovodException):
def __... | class Botovodexception(Exception):
pass
class Agentexception(BotovodException):
pass
class Agentnotexistexception(BotovodException):
def __init__(self, name: str):
super().__init__(f"Botovod have not '{name}' agent")
self.name = name
class Handlernotpassed(BotovodException):
def __i... |
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
tripOccupancy = [0] * 1002
for trip in trips:
tripOccupancy[trip[1]] += trip[0]
tripOccupancy[trip[2]] -= trip[0]
occupancy = 0
for occupancyDelta in tripOccupancy:
... | class Solution:
def car_pooling(self, trips: List[List[int]], capacity: int) -> bool:
trip_occupancy = [0] * 1002
for trip in trips:
tripOccupancy[trip[1]] += trip[0]
tripOccupancy[trip[2]] -= trip[0]
occupancy = 0
for occupancy_delta in tripOccupancy:
... |
class Result:
def __init__(self, value=None, error=None):
self._value = value
self._error = error
def is_ok(self) -> bool:
return self._error is None
def is_error(self) -> bool:
return self._error is not None
@property
def value(self):
return self._value
... | class Result:
def __init__(self, value=None, error=None):
self._value = value
self._error = error
def is_ok(self) -> bool:
return self._error is None
def is_error(self) -> bool:
return self._error is not None
@property
def value(self):
return self._value
... |
cv_results = cross_validate(
model, X, y, cv=cv,
return_estimator=True, return_train_score=True,
n_jobs=-1,
)
cv_results = pd.DataFrame(cv_results)
| cv_results = cross_validate(model, X, y, cv=cv, return_estimator=True, return_train_score=True, n_jobs=-1)
cv_results = pd.DataFrame(cv_results) |
# """
# This is Master's API interface.
# You should not implement it, or speculate about its implementation
# """
#class Master:
# def guess(self, word):
# """
# :type word: str
# :rtype int
# """
class Solution:
def findSecretWord(self, wordlist, master):
n = 0
whil... | class Solution:
def find_secret_word(self, wordlist, master):
n = 0
while n < 6:
count = collections.Counter((w1 for (w1, w2) in itertools.permutations(wordlist, 2) if sum((i == j for (i, j) in zip(w1, w2))) == 0))
guess = min(wordlist, key=lambda w: count[w])
n ... |
class Usercredentials:
'''
class to generate new instances of usercredentials
'''
user_credential_list = [] #empty list for user creddential
def __init__(self,site_name,password):
'''
method to define properties of the object
'''
self.site_name = site_name
... | class Usercredentials:
"""
class to generate new instances of usercredentials
"""
user_credential_list = []
def __init__(self, site_name, password):
"""
method to define properties of the object
"""
self.site_name = site_name
self.password = password
def... |
"""Fixed and parsed data for testing"""
SERIES = {
"_links": { "nextepisode": { "href": "http://api.tvmaze.com/episodes/664353"},
"previousepisode": { "href": "http://api.tvmaze.com/episodes/631872"},
"self": { "href": "http://api.tvmaze.com/shows/60"}
},
"externals": { "im... | """Fixed and parsed data for testing"""
series = {'_links': {'nextepisode': {'href': 'http://api.tvmaze.com/episodes/664353'}, 'previousepisode': {'href': 'http://api.tvmaze.com/episodes/631872'}, 'self': {'href': 'http://api.tvmaze.com/shows/60'}}, 'externals': {'imdb': 'tt0364845', 'thetvdb': 72108, 'tvrage': 4628}, ... |
#!/usr/bin/env python
def clean_links(text):
"""Remove brackets around a wikilink, keeping the label instead of the page
if it exists.
"[[foobar]]" will become "foobar", but "[[foobar|code words]]" will return
"code words".
Args:
text (str): Full text of a Wikipedia article as a single st... | def clean_links(text):
"""Remove brackets around a wikilink, keeping the label instead of the page
if it exists.
"[[foobar]]" will become "foobar", but "[[foobar|code words]]" will return
"code words".
Args:
text (str): Full text of a Wikipedia article as a single string.
Returns:
... |
def GetParent(node, parent):
if node == parent[node]:
return node
parent[node] = GetParent(parent[node], parent)
return parent[node]
def union(u, v, parent, rank):
u = GetParent(u, parent)
v = GetParent(v, parent)
if rank[u] < rank[v]:
parent[u] = v
elif rank[u] > rank[... | def get_parent(node, parent):
if node == parent[node]:
return node
parent[node] = get_parent(parent[node], parent)
return parent[node]
def union(u, v, parent, rank):
u = get_parent(u, parent)
v = get_parent(v, parent)
if rank[u] < rank[v]:
parent[u] = v
elif rank[u] > rank[v... |
#!/usr/bin/env python3
n, *h = map(int, open(0).read().split())
dp = [0] * n
dp[0] = 0
a = abs
for i in range(1, n):
dp[i] = min(dp[i], dp[i-1] + a(h[i] - h[i-1]))
dp[i+1] = min(dp[i+1], dp[i-1] + a(h[i] - h[i-2]))
print(dp[n-1])
| (n, *h) = map(int, open(0).read().split())
dp = [0] * n
dp[0] = 0
a = abs
for i in range(1, n):
dp[i] = min(dp[i], dp[i - 1] + a(h[i] - h[i - 1]))
dp[i + 1] = min(dp[i + 1], dp[i - 1] + a(h[i] - h[i - 2]))
print(dp[n - 1]) |
"""
In this Bite you complete the divide_numbers function that takes a
numerator and a denominator (the number above and below the line
respectively when doing a division).
First you try to convert them to ints, if that raises a ValueError
you will re-raise it (using raise).
To keep things simple we can expect thi... | """
In this Bite you complete the divide_numbers function that takes a
numerator and a denominator (the number above and below the line
respectively when doing a division).
First you try to convert them to ints, if that raises a ValueError
you will re-raise it (using raise).
To keep things simple we can expect thi... |
"""
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't ha... | """
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't ha... |
"""This file defines the unified tensor framework interface required by DeepXDE.
The principles of this interface:
* There should be as few interfaces as possible.
* The interface is used by DeepXDE system so it is more important to have
clean definition rather than convenient usage.
* Default arguments should be av... | """This file defines the unified tensor framework interface required by DeepXDE.
The principles of this interface:
* There should be as few interfaces as possible.
* The interface is used by DeepXDE system so it is more important to have
clean definition rather than convenient usage.
* Default arguments should be av... |
# User input
minutes = float(input("Enter the time in minutes: "))
# Program operation
hours = minutes/60
# Computer output
print("The time in hours is: " + str(hours))
| minutes = float(input('Enter the time in minutes: '))
hours = minutes / 60
print('The time in hours is: ' + str(hours)) |
x = 12
y = 3
print(x > y) # True
x = "12"
y = "3"
print(x > y) # ! False / Why it's false ?
print(x < y) # ! True
# x = 12
# y = "3"
# print(x > y)
x2 = "45"
y2 = "321"
print(x2 > y2) # True
x2 = "45"
y2 = "621"
X2_Length = len(x2)
Y2_Length = len(y2)
print(X2_Length < Y2_Length) # True
print( ord('4') ) # 52... | x = 12
y = 3
print(x > y)
x = '12'
y = '3'
print(x > y)
print(x < y)
x2 = '45'
y2 = '321'
print(x2 > y2)
x2 = '45'
y2 = '621'
x2__length = len(x2)
y2__length = len(y2)
print(X2_Length < Y2_Length)
print(ord('4'))
print(ord('5'))
print(ord('6'))
print(ord('2'))
print(ord('1')) |
'''
For 35 points, answer the following questions.
Create a new folder named file_io and create a new Python file in the
folder. Run this 4 line program. Then look in the folder.
1) What did the program do?
'''
f = open('workfile.txt', 'w')
f.write('Bazarr 10 points\n')
f.write('Iko 3 points')
f.close()
'''Run this ... | """
For 35 points, answer the following questions.
Create a new folder named file_io and create a new Python file in the
folder. Run this 4 line program. Then look in the folder.
1) What did the program do?
"""
f = open('workfile.txt', 'w')
f.write('Bazarr 10 points\n')
f.write('Iko 3 points')
f.close()
'Run this shor... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
a = [int(input()) for _ in range(n)][::-1]
ans = 0
for i in range(n):
p, q = divmod(a[i], 2)
ans += p
if q == 1:
if (i + 1 <= n - 1) and (a[i + 1] >= 1):
ans += 1
a... | def main():
n = int(input())
a = [int(input()) for _ in range(n)][::-1]
ans = 0
for i in range(n):
(p, q) = divmod(a[i], 2)
ans += p
if q == 1:
if i + 1 <= n - 1 and a[i + 1] >= 1:
ans += 1
a[i + 1] -= 1
print(ans)
if __name__ == '_... |
'''
escreva num arquivo texto.txt o conteudo de uma lista de uma vez
'''
arquivo = open('texto.txt', 'a')
frases = list()
frases.append('TreinaWeb \n')
frases.append('Python \n')
frases.append('Arquivos \n')
frases.append('Django \n')
arquivo.writelines(frases) | """
escreva num arquivo texto.txt o conteudo de uma lista de uma vez
"""
arquivo = open('texto.txt', 'a')
frases = list()
frases.append('TreinaWeb \n')
frases.append('Python \n')
frases.append('Arquivos \n')
frases.append('Django \n')
arquivo.writelines(frases) |
'''Exceptions for my orm'''
class ObjectNotInitializedError(Exception):
pass
class ObjectNotFoundError(Exception):
pass
| """Exceptions for my orm"""
class Objectnotinitializederror(Exception):
pass
class Objectnotfounderror(Exception):
pass |
def download_file(my_socket):
print("[+] Downloading file")
filename = my_socket.receive_data()
my_socket.receive_file(filename)
| def download_file(my_socket):
print('[+] Downloading file')
filename = my_socket.receive_data()
my_socket.receive_file(filename) |
def return_for_conditions(obj, raise_ex=False, **kwargs):
"""
Get a function that returns/raises an object and is suitable as a
``side_effect`` for a mock object.
Args:
obj:
The object to return/raise.
raise_ex:
A boolean indicating if the object should be raised... | def return_for_conditions(obj, raise_ex=False, **kwargs):
"""
Get a function that returns/raises an object and is suitable as a
``side_effect`` for a mock object.
Args:
obj:
The object to return/raise.
raise_ex:
A boolean indicating if the object should be raised... |
#
# @lc app=leetcode id=223 lang=python3
#
# [223] Rectangle Area
#
# @lc code=start
class Solution:
def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)
total = (A - C) * (B - D) + (E... | class Solution:
def compute_area(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)
total = (A - C) * (B - D) + (E - G) * (F - H)
return total - overlap |
gameList = [
'Riverraid-v0',
'SpaceInvaders-v0',
'StarGunner-v0',
'Pitfall-v0',
'Centipede-v0'
]
| game_list = ['Riverraid-v0', 'SpaceInvaders-v0', 'StarGunner-v0', 'Pitfall-v0', 'Centipede-v0'] |
class Solution:
def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:
n = len(boxes)
# dp[i] := min trips to deliver boxes[0..i) and return to the storage
dp = [0] * (n + 1)
trips = 2
weight = 0
l = 0
for r in range(n):
weight += box... | class Solution:
def box_delivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:
n = len(boxes)
dp = [0] * (n + 1)
trips = 2
weight = 0
l = 0
for r in range(n):
weight += boxes[r][1]
if r > 0 and boxes[r... |
{{AUTO_GENERATED_NOTICE}}
CompilerInfo = provider(fields = ["platform", "bsc", "bsb_helper"])
def _rescript_compiler_impl(ctx):
return [CompilerInfo(
platform = ctx.attr.name,
bsc = ctx.file.bsc,
bsb_helper = ctx.file.bsb_helper,
)]
rescript_compiler = rule(
implementation = _resc... | {{AUTO_GENERATED_NOTICE}}
compiler_info = provider(fields=['platform', 'bsc', 'bsb_helper'])
def _rescript_compiler_impl(ctx):
return [compiler_info(platform=ctx.attr.name, bsc=ctx.file.bsc, bsb_helper=ctx.file.bsb_helper)]
rescript_compiler = rule(implementation=_rescript_compiler_impl, attrs={'bsc': attr.label(a... |
# https://leetcode.com/explore/featured/card/fun-with-arrays/521/introduction/3238/
class Solution:
def findMaxConsecutiveOnes(self, nums):
left = 0
prev = 0
while left < len(nums):
counter = 0
if nums[left] == 1:
right = left
while rig... | class Solution:
def find_max_consecutive_ones(self, nums):
left = 0
prev = 0
while left < len(nums):
counter = 0
if nums[left] == 1:
right = left
while right < len(nums):
if nums[right] == 1:
... |
class Solution(object):
def minTimeToVisitAllPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
current_pos, time = points[0], 0
for p in points:
if current_pos[0] != p[0] or current_pos[1] != p[1]:
delta_x = abs(p[0]-c... | class Solution(object):
def min_time_to_visit_all_points(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
(current_pos, time) = (points[0], 0)
for p in points:
if current_pos[0] != p[0] or current_pos[1] != p[1]:
delta_x = ... |
#
# PySNMP MIB module Nortel-Magellan-Passport-FrameRelayNniTraceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayNniTraceMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:17:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
RSS_PERF_NAME = "rss"
FLT_PERF_NAME = "flt"
CPU_CLOCK_PERF_NAME = "cpu_clock"
TSK_CLOCK_PERF_NAME = "task_clock"
SIZE_PERF_NAME = "file_size"
EXEC_OVER_HEAD_KEY = 'exec'
MEM_USE_OVER_HEAD_KEY = 'mem'
FILE_SIZE_OVER_HEAD_KEY = 'size'
| rss_perf_name = 'rss'
flt_perf_name = 'flt'
cpu_clock_perf_name = 'cpu_clock'
tsk_clock_perf_name = 'task_clock'
size_perf_name = 'file_size'
exec_over_head_key = 'exec'
mem_use_over_head_key = 'mem'
file_size_over_head_key = 'size' |
LINE_LEN = 25
while True:
try:
n = int(input())
if n == 0:
break
surface = []
max_len = 0
for i in range(n):
line = str(input())
line = line.strip()
l_space = line.find(' ')
if l_space == -1:
max_len = LINE_LEN
else:
r_space = line.rfind(' ')
... | line_len = 25
while True:
try:
n = int(input())
if n == 0:
break
surface = []
max_len = 0
for i in range(n):
line = str(input())
line = line.strip()
l_space = line.find(' ')
if l_space == -1:
max_len ... |
f = open('rosalind_motif.txt')
a = []
for line in f.readlines():
a.append(line.strip())
dna1, dna2 = a[0], a[1]
f.close()
def find_motif(dna1, dna2):
"""Given: Two DNA strings s and t (each of length at most 1 kbp).
Return: All locations of t as a substring of s."""
k = len(dna2)
indexes = []
for i in range(... | f = open('rosalind_motif.txt')
a = []
for line in f.readlines():
a.append(line.strip())
(dna1, dna2) = (a[0], a[1])
f.close()
def find_motif(dna1, dna2):
"""Given: Two DNA strings s and t (each of length at most 1 kbp).
Return: All locations of t as a substring of s."""
k = len(dna2)
indexes = []
... |
class Solution:
def findMin(self, nums: List[int]) -> int:
# solution 1
# return min(nums)
# solution 2
left = 0
right = len(nums)-1
while left < right:
mid = int((left + right)/2)
if nums[mid] < nums[right]:
right = mid
... | class Solution:
def find_min(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
while left < right:
mid = int((left + right) / 2)
if nums[mid] < nums[right]:
right = mid
elif nums[mid] == nums[right]:
right = rig... |
def cyclicQ(ll):
da_node = ll
sentient = ll
poop = ll
poop = poop.next.next
ll = ll.next
while poop != ll and poop is not None and poop.next is not None:
poop = poop.next.next
ll = ll.next
if poop is None or poop.next is None:
return None
node_in_cycle =... | def cyclic_q(ll):
da_node = ll
sentient = ll
poop = ll
poop = poop.next.next
ll = ll.next
while poop != ll and poop is not None and (poop.next is not None):
poop = poop.next.next
ll = ll.next
if poop is None or poop.next is None:
return None
node_in_cycle = ll
... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
class Trace:
'''An object that can cause a trace entry'''
def trace(self) -> str:
'''Return a representation of the entry for tracing
This is use... | class Trace:
"""An object that can cause a trace entry"""
def trace(self) -> str:
"""Return a representation of the entry for tracing
This is used by things like the standalone ISS with -v
"""
raise not_implemented_error()
class Tracepc(Trace):
def __init__(self, pc: int... |
WAGTAILSEARCH_BACKENDS = {
"default": {"BACKEND": "wagtail.contrib.postgres_search.backend"}
}
| wagtailsearch_backends = {'default': {'BACKEND': 'wagtail.contrib.postgres_search.backend'}} |
def key_in_dict_not_empty(key, dictionary):
"""
"""
if key in dictionary:
return is_not_empty(dictionary[key])
return False
def is_empty(value):
"""
"""
if value is None:
return True
return value in ['', [], {}]
def is_not_empty(value):
return not is_empty(value)
... | def key_in_dict_not_empty(key, dictionary):
"""
"""
if key in dictionary:
return is_not_empty(dictionary[key])
return False
def is_empty(value):
"""
"""
if value is None:
return True
return value in ['', [], {}]
def is_not_empty(value):
return not is_empty(value)
d... |
# https://www.codingame.com/training/easy/1d-spreadsheet
def add_dependency(cell, arg_cell, in_deps, out_deps):
if cell not in out_deps: out_deps[cell] = set()
out_deps[cell].add(arg_cell)
if arg_cell not in in_deps: in_deps[arg_cell] = set()
in_deps[arg_cell].add(cell)
def remove_dependency(cell, ... | def add_dependency(cell, arg_cell, in_deps, out_deps):
if cell not in out_deps:
out_deps[cell] = set()
out_deps[cell].add(arg_cell)
if arg_cell not in in_deps:
in_deps[arg_cell] = set()
in_deps[arg_cell].add(cell)
def remove_dependency(cell, in_deps, out_deps):
rc = []
if cell n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Word:
def __init__(self, id, name, image, category=None):
self.id = id
self.name = name
self.image = image
self.category = category
| class Word:
def __init__(self, id, name, image, category=None):
self.id = id
self.name = name
self.image = image
self.category = category |
def optimal_order(predecessors_map, weight_map):
vertices = frozenset(predecessors_map.keys())
# print(vertices)
memo_map = {frozenset(): (0, [])}
# print(memo_map)
return optimal_order_helper(predecessors_map, weight_map, vertices, memo_map)
def optimal_order_helper(predecessors_map, weight_map, ... | def optimal_order(predecessors_map, weight_map):
vertices = frozenset(predecessors_map.keys())
memo_map = {frozenset(): (0, [])}
return optimal_order_helper(predecessors_map, weight_map, vertices, memo_map)
def optimal_order_helper(predecessors_map, weight_map, vertices, memo_map):
if vertices in memo_... |
# Program to implement First Come First Served CPU scheduling algorithm
print("First Come First Served scheduling Algorithm")
print("============================================\n")
headers = ['Processes','Arrival Time','Burst Time','Waiting Time'
,'Turn-Around Time','Completion Time']
# Dictionary to st... | print('First Come First Served scheduling Algorithm')
print('============================================\n')
headers = ['Processes', 'Arrival Time', 'Burst Time', 'Waiting Time', 'Turn-Around Time', 'Completion Time']
out = dict()
n = int(input('Number of processes : '))
(a, b) = (0, 0)
for i in range(0, N):
k = f... |
# -*- coding: utf-8 -*-
__author__ = 'Sinval Vieira Mendes Neto'
__email__ = 'sinvalneto01@gmail.com'
__version__ = '0.1.0'
| __author__ = 'Sinval Vieira Mendes Neto'
__email__ = 'sinvalneto01@gmail.com'
__version__ = '0.1.0' |
# -*- coding: utf-8 -*-
#
# This file is part of the SKATestDevice project
#
#
#
# Distributed under the terms of the none license.
# See LICENSE.txt for more info.
"""Release information for Python Package"""
name = """tangods-skatestdevice"""
version = "1.0.0"
version_info = version.split(".")
description = """A ge... | """Release information for Python Package"""
name = 'tangods-skatestdevice'
version = '1.0.0'
version_info = version.split('.')
description = 'A generic Test device for testing SKA base class functionalites.'
author = 'cam'
author_email = 'cam at ska.ac.za'
license = 'BSD-3-Clause'
url = 'www.tango-controls.org'
copyri... |
#--coding:utf-8 --
"""
"""
class cDBSCAN:
"""
The major class of the cDBSCAN algorithm, belong to CAO Yaqiang, CHEN Xingwei.
"""
def __init__(self, mat, eps, minPts):
"""
@param mat: the raw or normalized [pointId,X,Y] data matrix
@type mat : np.array
@param eps: The... | """
"""
class Cdbscan:
"""
The major class of the cDBSCAN algorithm, belong to CAO Yaqiang, CHEN Xingwei.
"""
def __init__(self, mat, eps, minPts):
"""
@param mat: the raw or normalized [pointId,X,Y] data matrix
@type mat : np.array
@param eps: The clustering distance... |
# Tuples in python
def swap(m, n, k):
temp = m
m = n
n = k
k = temp
return m, n, k
def main():
a = (1, "iPhone 12 Pro Max", 1.8, 1)
print(a)
print(a[1])
print(a.index(1.8))
print(a.count(1))
b = a + (999, 888)
print(b)
m = 1
n = 2
k = 3
m, n, k = swap(... | def swap(m, n, k):
temp = m
m = n
n = k
k = temp
return (m, n, k)
def main():
a = (1, 'iPhone 12 Pro Max', 1.8, 1)
print(a)
print(a[1])
print(a.index(1.8))
print(a.count(1))
b = a + (999, 888)
print(b)
m = 1
n = 2
k = 3
(m, n, k) = swap(m, n, k)
print... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : August 2014
Copyright : (C) 2014-2016 Boundless, http://boundlessgeo.com
**********************************************************... | """
***************************************************************************
__init__.py
---------------------
Date : August 2014
Copyright : (C) 2014-2016 Boundless, http://boundlessgeo.com
***************************************************************************
* ... |
# O programa le um valor em metros e o exibe convertido em centimetros e milimetros
metros = float(input('Entre com a distancia em metros: '))
centimetros = metros * 100
milimetros = metros * 1000
kilometros = metros / 1000.0
print('{} metros e {:.0f} centimetros'.format(metros, centimetros))
print('{} metros e {} m... | metros = float(input('Entre com a distancia em metros: '))
centimetros = metros * 100
milimetros = metros * 1000
kilometros = metros / 1000.0
print('{} metros e {:.0f} centimetros'.format(metros, centimetros))
print('{} metros e {} milimetros'.format(metros, milimetros))
print('{} metros e {} kilometros'.format(metros,... |
train_datagen = ImageDataGenerator(rescale=1./255) # rescaling on the fly
# Updated to do image augmentation
train_datagen = ImageDataGenerator(
rescale = 1./255, # recaling
rotation_range = 40, # randomly rotate b/w 0 and 40 degrees
width_shift_range = 0.2, # shifting the images
height_shift_rang... | train_datagen = image_data_generator(rescale=1.0 / 255)
train_datagen = image_data_generator(rescale=1.0 / 255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') |
#!/usr/bin/env python
##
# Print a heading.
#
# @var string text
# @return string
##
def heading(text):
return '-----> ' + text;
##
# Print a single line.
#
# @var string text
# @return string
##
def line(text):
return ' ' + text;
##
# Print a single new line.
#
# @return string
##
def nl():
return... | def heading(text):
return '-----> ' + text
def line(text):
return ' ' + text
def nl():
return line('') |
load("@build_bazel_rules_nodejs//:providers.bzl", "run_node")
def _create_worker_module_impl(ctx):
output_file = ctx.actions.declare_file(ctx.attr.out_file)
if (len(ctx.files.worker_file) != 1):
fail("Expected a single file but got " + str(ctx.files.worker_file))
cjs = ["--cjs"] if ctx.attr.cjs el... | load('@build_bazel_rules_nodejs//:providers.bzl', 'run_node')
def _create_worker_module_impl(ctx):
output_file = ctx.actions.declare_file(ctx.attr.out_file)
if len(ctx.files.worker_file) != 1:
fail('Expected a single file but got ' + str(ctx.files.worker_file))
cjs = ['--cjs'] if ctx.attr.cjs else ... |
"""ANSI color codes for the command line output."""
RESET = u"\u001b[0m"
BLACK = u"\u001b[30m"
RED = u"\u001b[31m"
GREEN = u"\u001b[32m"
YELLOW = u"\u001b[33m"
BLUE = u"\u001b[34m"
MAGENTA = u"\u001b[35m"
CYAN = u"\u001b[36m"
WHITE = u"\u001b[37m"
BRIGHT_BLACK = u"\u001b[30;1m"
BRIGHT_RED = u"\u001b[31;1m"
BRIGHT_GREE... | """ANSI color codes for the command line output."""
reset = u'\x1b[0m'
black = u'\x1b[30m'
red = u'\x1b[31m'
green = u'\x1b[32m'
yellow = u'\x1b[33m'
blue = u'\x1b[34m'
magenta = u'\x1b[35m'
cyan = u'\x1b[36m'
white = u'\x1b[37m'
bright_black = u'\x1b[30;1m'
bright_red = u'\x1b[31;1m'
bright_green = u'\x1b[32;1m'
brigh... |
print('Laboratory work 1.1 measurements of the R-load.')
measurements = []
measurements_count = int(input('Enter number of measurements : '))
for cur_measurement_number in range(1, measurements_count+1):
print(f'Enter value for measurement {cur_measurement_number} -> ', end='')
measurement = float(input())
... | print('Laboratory work 1.1 measurements of the R-load.')
measurements = []
measurements_count = int(input('Enter number of measurements : '))
for cur_measurement_number in range(1, measurements_count + 1):
print(f'Enter value for measurement {cur_measurement_number} -> ', end='')
measurement = float(input())
... |
#tests: depend_extra
depend_extra=('pelle',)
def synthesis():
pass
| depend_extra = ('pelle',)
def synthesis():
pass |
def _capnp_toolchain_gen_impl(ctx):
ctx.template(
"toolchain/BUILD.bazel",
ctx.attr._build_tpl,
substitutions = {
"{capnp_tool}": str(ctx.attr.capnp_tool),
},
)
capnp_toolchain_gen = repository_rule(
implementation = _capnp_toolchain_gen_impl,
attrs = {
... | def _capnp_toolchain_gen_impl(ctx):
ctx.template('toolchain/BUILD.bazel', ctx.attr._build_tpl, substitutions={'{capnp_tool}': str(ctx.attr.capnp_tool)})
capnp_toolchain_gen = repository_rule(implementation=_capnp_toolchain_gen_impl, attrs={'capnp_tool': attr.label(allow_single_file=True, cfg='host', executable=True... |
expected_output = {
'steering_entries': {
'sgt': {
2057: {
'entry_last_refresh': '10:32:00',
'entry_state': 'COMPLETE',
'peer_name': 'Unknown-2057',
'peer_sgt': '2057-01',
'policy_rbacl_src_list': {
... | expected_output = {'steering_entries': {'sgt': {2057: {'entry_last_refresh': '10:32:00', 'entry_state': 'COMPLETE', 'peer_name': 'Unknown-2057', 'peer_sgt': '2057-01', 'policy_rbacl_src_list': {'entry_status': 'UNKNOWN', 'installed_elements': '0x00000C80', 'installed_peer_policy': {'peer_policy': '0x7F3ADDAFEA08', 'pol... |
__author__ = 'Stormpath, Inc.'
__copyright__ = 'Copyright 2012-2014 Stormpath, Inc.'
__version_info__ = ('1', '3', '1')
__version__ = '.'.join(__version_info__)
__short_version__ = '.'.join(__version_info__)
| __author__ = 'Stormpath, Inc.'
__copyright__ = 'Copyright 2012-2014 Stormpath, Inc.'
__version_info__ = ('1', '3', '1')
__version__ = '.'.join(__version_info__)
__short_version__ = '.'.join(__version_info__) |
J
# welcoming the user
name = input("What is your name? ")
print("Hello, " + name, "It is time to play hangman!")
print("Start guessing...")
# here we set the secret
word = "secret"
# creates a variable with an empty value
guesses = ''
# determine the number of turns
turns = 10
while turns > 0:
failed = 0
... | J
name = input('What is your name? ')
print('Hello, ' + name, 'It is time to play hangman!')
print('Start guessing...')
word = 'secret'
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char)
else:
print('_')
faile... |
conductores = {
'azambrano': ('Andres Zambrano', 5.6, ('Hyundai', 'Elantra')),
'jojeda': ('Juan Ojeda', 1.1, ('Hyundai', 'Accent')),
# ...
}
def agrega_conductor(conductores, nuevo_conductor):
username, nombre, puntaje, (marca, modelo) = nuevo_conductor
if username in conductores:
... | conductores = {'azambrano': ('Andres Zambrano', 5.6, ('Hyundai', 'Elantra')), 'jojeda': ('Juan Ojeda', 1.1, ('Hyundai', 'Accent'))}
def agrega_conductor(conductores, nuevo_conductor):
(username, nombre, puntaje, (marca, modelo)) = nuevo_conductor
if username in conductores:
return False
conductores... |
"""
Implement a class for a Least Recently Used (LRU) Cache. The cache should
support inserting key/value paris, retrieving a key's value and retrieving the
most recently active key.
Each of these methods should run in constant time. When a key/value pair is
inserted or a key's value is retrieved, the key in question... | """
Implement a class for a Least Recently Used (LRU) Cache. The cache should
support inserting key/value paris, retrieving a key's value and retrieving the
most recently active key.
Each of these methods should run in constant time. When a key/value pair is
inserted or a key's value is retrieved, the key in question... |
#calculator
def add(n1,n2):
return n1 +n2
def substract(n1,n2):
return n1-n2
def multiply(n1,n2):
return n1 * n2
def devide(n1,n2):
return n1/n2
operator = {
"+": add,
"-": substract,
"*": multiply,
"/": devide,
}
num1 = float(input("Enter number: "))
op_simbol = input("enter +... | def add(n1, n2):
return n1 + n2
def substract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def devide(n1, n2):
return n1 / n2
operator = {'+': add, '-': substract, '*': multiply, '/': devide}
num1 = float(input('Enter number: '))
op_simbol = input('enter + - * / ')
num2 = float(input(... |
# https://www.codechef.com/problems/SUMPOS
for T in range(int(input())):
l=sorted(list(map(int,input().split())))
print("NO") if(l[2]!=l[1]+l[0]) else print("YES") | for t in range(int(input())):
l = sorted(list(map(int, input().split())))
print('NO') if l[2] != l[1] + l[0] else print('YES') |
class LoggerTemplate():
def __init__(self, *args, **kwargs):
raise NotImplementedError
def update_loss(self, phase, value, step):
raise NotImplementedError
def update_metric(self, phase, metric, value, step):
raise NotImplementedError
| class Loggertemplate:
def __init__(self, *args, **kwargs):
raise NotImplementedError
def update_loss(self, phase, value, step):
raise NotImplementedError
def update_metric(self, phase, metric, value, step):
raise NotImplementedError |
var={"car":"volvo", "fruit":"apple"}
print(var["fruit"])
for f in var:
print("key: " + f + " value: " + var[f])
print()
print()
var1={"donut":["chocolate","glazed","sprinkled"]}
print(var1["donut"][0])
print("My favorite donut flavors are:", end= " ")
for f in var1["donut"]:
print(f, end=" ")
print()
print()
#Usin... | var = {'car': 'volvo', 'fruit': 'apple'}
print(var['fruit'])
for f in var:
print('key: ' + f + ' value: ' + var[f])
print()
print()
var1 = {'donut': ['chocolate', 'glazed', 'sprinkled']}
print(var1['donut'][0])
print('My favorite donut flavors are:', end=' ')
for f in var1['donut']:
print(f, end=' ')
print()
pr... |
#Challenge 4: Take a binary tree and reverse it
#I decided to create two classes. One to hold the node, and one to act as the Binary Tree.
#Node class
#Only contains the information for the node. Val is the value of the node, left is the left most value, and right is the right value
class Node:
def __init__(self, ... | class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class Binarytree:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def add(self, val):
if self.root is None:
self.root = node(v... |
DAOLIPROXY_VENDOR = "OpenStack Foundation"
DAOLIPROXY_PRODUCT = "DaoliProxy"
DAOLIPROXY_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo(object):
release = "1.el7.centos"
version = "2015.1.21"
def version_string(self):
return self.version
def release_string(... | daoliproxy_vendor = 'OpenStack Foundation'
daoliproxy_product = 'DaoliProxy'
daoliproxy_package = None
loaded = False
class Versioninfo(object):
release = '1.el7.centos'
version = '2015.1.21'
def version_string(self):
return self.version
def release_string(self):
return self.release
v... |
# Space: O(n)
# Time: O(n)
class Solution:
def findUnsortedSubarray(self, nums):
length = len(nums)
if length <= 1: return 0
stack = []
left, right = length - 1, 0
for i in range(length):
while stack and nums[stack[-1]] > nums[i]:
left = min(lef... | class Solution:
def find_unsorted_subarray(self, nums):
length = len(nums)
if length <= 1:
return 0
stack = []
(left, right) = (length - 1, 0)
for i in range(length):
while stack and nums[stack[-1]] > nums[i]:
left = min(left, stack.po... |
# encoding: utf-8
# module Autodesk.AutoCAD.DatabaseServices
# from D:\Python\ironpython-stubs\release\stubs\Autodesk\AutoCAD\DatabaseServices\__init__.py
# by generator 1.145
# no doc
# no imports
# no functions
# no classes
# variables with complex values
__path__ = [
'D:\\Python\\ironpython-stubs\\release\\stu... | __path__ = ['D:\\Python\\ironpython-stubs\\release\\stubs\\Autodesk\\AutoCAD\\DatabaseServices'] |
class InMemoryKVAdapter:
""" Dummy in-memory key-value store to be used as mock for KVAdapter"""
def __init__(self):
self._data = {}
def get_key(self, key):
root, key = self._navigate(key)
return root.get(key, None)
def get_keys(self, key):
root, key = self._navigate(k... | class Inmemorykvadapter:
""" Dummy in-memory key-value store to be used as mock for KVAdapter"""
def __init__(self):
self._data = {}
def get_key(self, key):
(root, key) = self._navigate(key)
return root.get(key, None)
def get_keys(self, key):
(root, key) = self._naviga... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 15:59:53 2020
@author: Pablo
"""
class Term:
string = ''
lang = ''
score=0
corpus=''
synonyms=[]
iateURL=''
translations = {}
def __init__(self, term, code):
self.strin... | """
Created on Tue Sep 29 15:59:53 2020
@author: Pablo
"""
class Term:
string = ''
lang = ''
score = 0
corpus = ''
synonyms = []
iate_url = ''
translations = {}
def __init__(self, term, code):
self.string = term
self.lang = code
def get_data(self):
print(s... |
# Basic - Print all integers from 0 to 150.
y = 0
while y <= 150:
print(y)
y = y + 1
# Multiples of Five - Print all the multiples of 5 from 5 to 1,000
x = 5
while x < 1001:
print(x)
x = x + 5
# Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible ... | y = 0
while y <= 150:
print(y)
y = y + 1
x = 5
while x < 1001:
print(x)
x = x + 5
j = 0
txt = 'Coding'
while j < 101:
if j % 10 == 0:
print(txt + 'Dojo')
elif j % 5 == 0:
print(txt)
else:
print(j)
j += 1
z = 0
sum = 0
while z < 500000:
if z % 2 != 0:
s... |
##write a function that takes a nested list as an argument
##and returns a normal list
##show that the result is equal to flattened_list
nested_list = ['a', [2, 3], [4, 'b', [0, -2, ['c', 'e', '0f']]]]
flattened_list = ['a', 2, 3, 4, 'b', 0, -2, 'c', 'e', '0f']
def flat_list(nest_list):
flat = list()
... | nested_list = ['a', [2, 3], [4, 'b', [0, -2, ['c', 'e', '0f']]]]
flattened_list = ['a', 2, 3, 4, 'b', 0, -2, 'c', 'e', '0f']
def flat_list(nest_list):
flat = list()
for elem in nest_list:
if type(elem) is list:
flat += flat_list(elem)
else:
flat.append(elem)
return f... |
''' Program to count each character's frequency
Example:
Input: banana
Output: a3b1n2
'''
def frequency(input1):
l = list(input1)
x= list(set(l))
x.sort()
result=""
for i in range(0,len(x)):
count=0
for j in range(0,len(l)):
if x[i]==l[j]:
count +=1
... | """ Program to count each character's frequency
Example:
Input: banana
Output: a3b1n2
"""
def frequency(input1):
l = list(input1)
x = list(set(l))
x.sort()
result = ''
for i in range(0, len(x)):
count = 0
for j in range(0, len(l)):
if x[i] == l[j]:
count ... |
class VarDecl:
def __init__(self, name: str, type: str):
self._name = name
self._type = type
def name(self) -> str:
return self._name
def type(self) -> str:
return self._type
| class Vardecl:
def __init__(self, name: str, type: str):
self._name = name
self._type = type
def name(self) -> str:
return self._name
def type(self) -> str:
return self._type |
# DROP TABLES
# The following CQL queries drop all the tables from sparkifydb.
song_in_session_table_drop = "DROP TABLE IF EXISTS song_in_session"
artist_in_session_table_drop = "DROP TABLE IF EXISTS artist_in_session"
user_and_song_table_drop = "DROP TABLE IF EXISTS user_and_song"
# CREATE TABLES
# The following CQL ... | song_in_session_table_drop = 'DROP TABLE IF EXISTS song_in_session'
artist_in_session_table_drop = 'DROP TABLE IF EXISTS artist_in_session'
user_and_song_table_drop = 'DROP TABLE IF EXISTS user_and_song'
song_in_session_table_create = '\n CREATE TABLE IF NOT EXISTS song_in_session (\n session_id int, ... |
class DataGridViewCell(DataGridViewElement,ICloneable,IDisposable):
""" Represents an individual cell in a System.Windows.Forms.DataGridView control. """
def AdjustCellBorderStyle(self,dataGridViewAdvancedBorderStyleInput,dataGridViewAdvancedBorderStylePlaceholder,singleVerticalBorderAdded,singleHorizontalBorderAdd... | class Datagridviewcell(DataGridViewElement, ICloneable, IDisposable):
""" Represents an individual cell in a System.Windows.Forms.DataGridView control. """
def adjust_cell_border_style(self, dataGridViewAdvancedBorderStyleInput, dataGridViewAdvancedBorderStylePlaceholder, singleVerticalBorderAdded, singleHoriz... |
# Exercise 01.2
# Author: Leonardo Ferreira Santos
arguments = input('Say something: ')
print('Number of characters: ', arguments.__sizeof__() - 25) # "-25" is necessary because this function always implements "25".
print('Reversed: ', arguments[::-1])
| arguments = input('Say something: ')
print('Number of characters: ', arguments.__sizeof__() - 25)
print('Reversed: ', arguments[::-1]) |
class Matrix:
def __init__(self, *rows):
self.matrix = [row for row in rows]
def __repr__(self):
matrix_repr = ""
for i, row in enumerate(self.matrix):
row_repr = " ".join(f"{n:6.2f}" for n in row[:-1])
row_repr = f"{i}: {row_repr} | {row[-1]:6.2f}"
... | class Matrix:
def __init__(self, *rows):
self.matrix = [row for row in rows]
def __repr__(self):
matrix_repr = ''
for (i, row) in enumerate(self.matrix):
row_repr = ' '.join((f'{n:6.2f}' for n in row[:-1]))
row_repr = f'{i}: {row_repr} | {row[-1]:6.2f}'
... |
# C++ | General
multiple_files = True
no_spaces = False
type_name = "Pixel"
# C++ | Names
name_camelCase = True
name_lower = False
# Other
out_filename = "Out.cpp" # Only works when multiple_files is on
multiple_files_extension = ".h" | multiple_files = True
no_spaces = False
type_name = 'Pixel'
name_camel_case = True
name_lower = False
out_filename = 'Out.cpp'
multiple_files_extension = '.h' |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "shopex")
| def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, 'shopex') |
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-DOMAIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-DOMAIN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:15:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
def test_e1():
a: list[i32]
a = [1, 2, 3]
b: list[str]
b = ['1', '2']
a = b
| def test_e1():
a: list[i32]
a = [1, 2, 3]
b: list[str]
b = ['1', '2']
a = b |
# TODO(kailys): Doc and create examples
class ConfigOption(object):
"A class representing options for ``Config``."
def __init__(self, name, value_map):
self.name = name
self.value_to_code_map = value_map
self.code_to_value_map = {v: k for k, v in value_map.iteritems()}
self.va... | class Configoption(object):
"""A class representing options for ``Config``."""
def __init__(self, name, value_map):
self.name = name
self.value_to_code_map = value_map
self.code_to_value_map = {v: k for (k, v) in value_map.iteritems()}
self.values = value_map.viewkeys()
... |
"""
Module: 'crypto' on GPy v1.11
"""
# MCU: (sysname='GPy', nodename='GPy', release='1.20.2.rc7', version='v1.11-6d01270 on 2020-05-04', machine='GPy with ESP32', pybytes='1.4.0')
# Stubber: 1.3.2
class AES:
''
MODE_CBC = 2
MODE_CFB = 3
MODE_CTR = 6
MODE_ECB = 1
SEGMENT_128 = 128
SEGMENT_8... | """
Module: 'crypto' on GPy v1.11
"""
class Aes:
""""""
mode_cbc = 2
mode_cfb = 3
mode_ctr = 6
mode_ecb = 1
segment_128 = 128
segment_8 = 8
def generate_rsa_signature():
pass
def getrandbits():
pass
def rsa_decrypt():
pass
def rsa_encrypt():
pass |
# -*- coding: utf-8 -*-
{
'name': "Product Minimum Order Quantity",
'summary': """
Specify the minimum order quantity of an item""",
'description': """
This module adds the functionality to control the minimum order quantity in a sales order line. The default number is set to 0. You can change this ... | {'name': 'Product Minimum Order Quantity', 'summary': '\n Specify the minimum order quantity of an item', 'description': '\nThis module adds the functionality to control the minimum order quantity in a sales order line. The default number is set to 0. You can change this value under the product form for individu... |
"""
goose : honk pig : 0.05 frog : -8 horse : 1 2 foo 3 duck : "quack quack"
"""
def pydict_to_mxdict(d):
res = []
for k,v in d.items():
res.append(k)
res.append(':')
if type(v) in [list, set, tuple]:
for i in v:
res.append(i)
else:
res.ap... | """
goose : honk pig : 0.05 frog : -8 horse : 1 2 foo 3 duck : "quack quack"
"""
def pydict_to_mxdict(d):
res = []
for (k, v) in d.items():
res.append(k)
res.append(':')
if type(v) in [list, set, tuple]:
for i in v:
res.append(i)
else:
re... |
def main():
myList = []
choice = 'a'
while choice != 'x':
if choice == 'a' or choice == 'A':
option1(myList)
elif choice == 'b' or choice == 'B':
option2(myList)
elif choice == 'c' or choice == 'C':
option3(myList)
elif choice == ... | def main():
my_list = []
choice = 'a'
while choice != 'x':
if choice == 'a' or choice == 'A':
option1(myList)
elif choice == 'b' or choice == 'B':
option2(myList)
elif choice == 'c' or choice == 'C':
option3(myList)
elif choice == 'd' or ch... |
reslist = [
-3251,
-1625,
0,
1625,
3251,
4876,
6502,
8127,
9752,
11378,
13003,
] # 1625/1626 increments
def fromcomp(val, bits):
if val >> (bits - 1) == 1:
return 0 - (val ^ (2 ** bits - 1)) - 1
else:
return val
filepath = "out.log"
with open(fil... | reslist = [-3251, -1625, 0, 1625, 3251, 4876, 6502, 8127, 9752, 11378, 13003]
def fromcomp(val, bits):
if val >> bits - 1 == 1:
return 0 - (val ^ 2 ** bits - 1) - 1
else:
return val
filepath = 'out.log'
with open(filepath) as fp:
line = fp.readline()
while line:
if line[32:34] =... |
# fun from StackOverflow :)
def toFixed(numObj, digits=0):
return f"{numObj:.{digits}f}"
# init
a = int(input("Enter a> "))
b = int(input("Enter b> "))
c = int(input("Enter c> "))
d = int(input("Enter d> "))
# calc
f = toFixed((a+b) / (c+d), 2)
# output
print("(a + b) / (c + d) = ", f)
| def to_fixed(numObj, digits=0):
return f'{numObj:.{digits}f}'
a = int(input('Enter a> '))
b = int(input('Enter b> '))
c = int(input('Enter c> '))
d = int(input('Enter d> '))
f = to_fixed((a + b) / (c + d), 2)
print('(a + b) / (c + d) = ', f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.