content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
st=input()
k=list(st)
print(k)
def equal(s):
n=len(s)
sh=0
tr=0
for i in s:
if(i=='s'):
sh+=1
if(i=='t'):
tr+=1
if(sh==tr):
return 1
else:
return 0
def equal_s_t(st):
maxi=0
n=len(st)
for i in range(n):
for j in range(i,n):
if(equal(st[i:j+1]) and maxi<j-i+1):
maxi=j-i+1
return maxi
print(equal_s_t(st))
| st = input()
k = list(st)
print(k)
def equal(s):
n = len(s)
sh = 0
tr = 0
for i in s:
if i == 's':
sh += 1
if i == 't':
tr += 1
if sh == tr:
return 1
else:
return 0
def equal_s_t(st):
maxi = 0
n = len(st)
for i in range(n):
for j in range(i, n):
if equal(st[i:j + 1]) and maxi < j - i + 1:
maxi = j - i + 1
return maxi
print(equal_s_t(st)) |
def linha():
print()
print('=' * 80)
print()
linha()
num = 0
soma = 0
cont = 0
while not num == 999:
num = int(input('Valor: '))
if num != 999:
soma += num
cont += 1
print()
print(f'Valores digitados: {cont}')
print(f'Soma dos valores: {soma}')
linha()
| def linha():
print()
print('=' * 80)
print()
linha()
num = 0
soma = 0
cont = 0
while not num == 999:
num = int(input('Valor: '))
if num != 999:
soma += num
cont += 1
print()
print(f'Valores digitados: {cont}')
print(f'Soma dos valores: {soma}')
linha() |
CDNX_POS_PERMISSIONS = {
'operator': [
'list_subcategory',
'list_productfinal',
'list_productfinaloption',
],
}
| cdnx_pos_permissions = {'operator': ['list_subcategory', 'list_productfinal', 'list_productfinaloption']} |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#
# Author: Komal Thareja (kthare10@renci.org)
class ConfigurationMapping:
def __init__(self):
self.type = None
self.class_name = None
self.properties = None
self.module_name = None
def __getstate__(self):
state = self.__dict__.copy()
return state
def __setstate__(self, state):
self.__dict__.update(state)
def get_module_name(self) -> str:
return self.module_name
def get_class_name(self) -> str:
return self.class_name
def get_key(self) -> str:
return self.type
def get_properties(self) -> dict:
return self.properties
def set_class_name(self, *, class_name: str):
self.class_name = class_name
def set_module_name(self, *, module_name: str):
self.module_name = module_name
def set_key(self, *, key: str):
self.type = key
def set_properties(self, *, properties: dict):
self.properties = properties
def __str__(self):
return f"resource_type: {self.type} class_name: {self.class_name} module: {self.module_name} " \
f"properties: {self.properties}"
| class Configurationmapping:
def __init__(self):
self.type = None
self.class_name = None
self.properties = None
self.module_name = None
def __getstate__(self):
state = self.__dict__.copy()
return state
def __setstate__(self, state):
self.__dict__.update(state)
def get_module_name(self) -> str:
return self.module_name
def get_class_name(self) -> str:
return self.class_name
def get_key(self) -> str:
return self.type
def get_properties(self) -> dict:
return self.properties
def set_class_name(self, *, class_name: str):
self.class_name = class_name
def set_module_name(self, *, module_name: str):
self.module_name = module_name
def set_key(self, *, key: str):
self.type = key
def set_properties(self, *, properties: dict):
self.properties = properties
def __str__(self):
return f'resource_type: {self.type} class_name: {self.class_name} module: {self.module_name} properties: {self.properties}' |
#!/usr/bin/python3
def multiple_returns(sentence):
if len(sentence) == 0:
return (0, None)
return (len(sentence), sentence[0])
| def multiple_returns(sentence):
if len(sentence) == 0:
return (0, None)
return (len(sentence), sentence[0]) |
#Instructions
#Create an empty list named misspelled_words.
#Write a for loop that:
#iterates over tokenized_story,
#uses an if statement that returns True if the current token is not in tokenized_vocabulary and if so, appends the current token to misspelled_words.
#Print misspelled_words.
#In this code, we're going to explore how to build a basic spell checker. Spell checkers work by comparing each word in a passage of text to a set of correctly spelled words. In this mission, we will learn:
#how to work with plain text files to read in a vocabulary of correctly spelled words,
#more string methods for working with and processing text data,
#how to create functions to make the components of our spell checker more reusable.
#In this code, we're going to explore how to customize the functions we write to improve the spell checker we built from the previous mission. As our code becomes more modular and separated into functions, it can often become harder to debug. We'll explore how to debug our code in this mission using the errors the Python interpreter returns.
#Recall that our spell checker works by:
#reading in a file of correctly spelled words, tokenizing it into a list and assigning it to the variable vocabulary,
#reading in, cleaning, and tokenizing the piece of text we want spell checked,
#comparing each word (token) in the piece of text with each word in vocabulary and returning the ones that weren't found.
#The file dictionary.txt contains a sequence of correctly spelled words, which we'll use to seed the vocabulary. The file story.txt is a piece of text containing some misspelled words. In the following code cell, we added the spell checker we wrote so far from the previous mission.
def clean_text(text_string, special_characters):
cleaned_string = text_string
for string in special_characters:
cleaned_string = cleaned_string.replace(string, "")
cleaned_string = cleaned_string.lower()
return(cleaned_string)
def tokenize(text_string, special_characters):
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(" ")
return(story_tokens)
misspelled_words = []
clean_chars = [",", ".", "'", ";", "\n"]
tokenized_story = tokenize(story_string, clean_chars)
tokenized_vocabulary = tokenize(vocabulary, clean_chars)
for ts in tokenized_story:
if ts not in tokenized_vocabulary:
misspelled_words.append(ts)
print(misspelled_words)
#Instructions
#Modify the tokenize() function:
def tokenize(text_string, special_characters, clean=False):
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(" ")
return(story_tokens)
clean_chars = [",", ".", "'", ";", "\n"]
tokenized_story = []
tokenized_vocabulary = []
misspelled_words = []
#Use an if statement to check if clean is True. If so:
#Clean text_string using clean_text and assign the returned string to a variable.
#Tokenize this new string variable using the split() method and assign the returned list to a variable.
#Return this list.
# Answer code
def tokenize(text_string, special_characters, clean=False):
# If `clean` is `True`.
if clean:
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(" ")
return(story_tokens)
#Outside the if statement, write the code that's executed if clean is False:
#Tokenize text_string using the split() method and assign the returned list to a variable.
#Return this list.
# If `clean` not equal to `True`, no cleaning.
story_tokens = text_string.split(" ")
return(story_tokens)
#Outside the tokenize() function:
#Use the tokenize() function to clean and tokenize story_string and assign the result to tokenized_story.
#Use the tokenize() function to tokenize vocabulary and assign the result to tokenized_vocabulary.
clean_chars = [",", ".", "'", ";", "\n"]
tokenized_story = tokenize(story_string, clean_chars, True)
tokenized_vocabulary = tokenize(vocabulary, clean_chars)
#Finally, loop over in tokenized_story, check if each element is in tokenized_vocabulary, and add to misspelled_words if it isn't.
for ts in tokenized_story:
if ts not in tokenized_vocabulary:
misspelled_words.append(ts)
| def clean_text(text_string, special_characters):
cleaned_string = text_string
for string in special_characters:
cleaned_string = cleaned_string.replace(string, '')
cleaned_string = cleaned_string.lower()
return cleaned_string
def tokenize(text_string, special_characters):
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(' ')
return story_tokens
misspelled_words = []
clean_chars = [',', '.', "'", ';', '\n']
tokenized_story = tokenize(story_string, clean_chars)
tokenized_vocabulary = tokenize(vocabulary, clean_chars)
for ts in tokenized_story:
if ts not in tokenized_vocabulary:
misspelled_words.append(ts)
print(misspelled_words)
def tokenize(text_string, special_characters, clean=False):
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(' ')
return story_tokens
clean_chars = [',', '.', "'", ';', '\n']
tokenized_story = []
tokenized_vocabulary = []
misspelled_words = []
def tokenize(text_string, special_characters, clean=False):
if clean:
cleaned_story = clean_text(text_string, special_characters)
story_tokens = cleaned_story.split(' ')
return story_tokens
story_tokens = text_string.split(' ')
return story_tokens
clean_chars = [',', '.', "'", ';', '\n']
tokenized_story = tokenize(story_string, clean_chars, True)
tokenized_vocabulary = tokenize(vocabulary, clean_chars)
for ts in tokenized_story:
if ts not in tokenized_vocabulary:
misspelled_words.append(ts) |
def escreva(texto):
print('~' * (len(texto) + 4))
print(f' {texto}')
print('~' * (len(texto) + 4))
# Programa Principal
text = str(input('Digite: '))
escreva(text)
escreva('Gustavo Guanabara')
escreva('Curso de Python no Youtube')
escreva('CeV')
| def escreva(texto):
print('~' * (len(texto) + 4))
print(f' {texto}')
print('~' * (len(texto) + 4))
text = str(input('Digite: '))
escreva(text)
escreva('Gustavo Guanabara')
escreva('Curso de Python no Youtube')
escreva('CeV') |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include".split(';') if "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so".split(';') if "-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so" != "" else []
PROJECT_NAME = "kinect2_registration"
PROJECT_SPACE_DIR = "/home/shams3049/catkin_ws/install"
PROJECT_VERSION = "0.0.1"
| catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include'.split(';') if '/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include' != '' else []
project_catkin_depends = ''.replace(';', ' ')
pkg_config_libraries_with_prefix = '-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so'.split(';') if '-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so' != '' else []
project_name = 'kinect2_registration'
project_space_dir = '/home/shams3049/catkin_ws/install'
project_version = '0.0.1' |
'''
.remove(x)
This operation removes element from the set.
If element does not exist, it raises a KeyError.
The .remove(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0
.discard(x)
This operation also removes element from the set.
If element does not exist, it does not raise a KeyError.
The .discard(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.discard(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.discard(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.discard(0)
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
.pop()
This operation removes and return an arbitrary element from the set.
If there are no elements to remove, it raises a KeyError.
Example
>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set
Task
You have a non-empty set , and you have to execute commands given in lines.
The commands will be pop, remove and discard.
Input Format
The first line contains integer , the number of elements in the set .
The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer , the number of commands.
The next lines contains either pop, remove and/or discard commands followed by their associated value.
Constraints
Output Format
Print the sum of the elements of set on a single line.
Sample Input
9
1 2 3 4 5 6 7 8 9
10
pop
remove 9
discard 9
discard 8
remove 7
pop
discard 6
remove 5
pop
discard 5
Sample Output
4
Explanation
After completing these operations on the set, we get set. Hence, the sum is .
Note: Convert the elements of set s to integers while you are assigning them. To ensure the proper input of the set, we have added the first two lines of code to the editor.
'''
n = int(input())
s = set(map(int, input().split()))
N=int(input())
k=[]
for i in range(N):
k=input().split()
if k[0]=='pop':
s.pop()
if k[0]=='remove':
s.remove(int(k[1]))
if k[0]=='discard':
s.discard(int(k[1]))
print(sum(s))
| """
.remove(x)
This operation removes element from the set.
If element does not exist, it raises a KeyError.
The .remove(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0
.discard(x)
This operation also removes element from the set.
If element does not exist, it does not raise a KeyError.
The .discard(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.discard(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.discard(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.discard(0)
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
.pop()
This operation removes and return an arbitrary element from the set.
If there are no elements to remove, it raises a KeyError.
Example
>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set
Task
You have a non-empty set , and you have to execute commands given in lines.
The commands will be pop, remove and discard.
Input Format
The first line contains integer , the number of elements in the set .
The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer , the number of commands.
The next lines contains either pop, remove and/or discard commands followed by their associated value.
Constraints
Output Format
Print the sum of the elements of set on a single line.
Sample Input
9
1 2 3 4 5 6 7 8 9
10
pop
remove 9
discard 9
discard 8
remove 7
pop
discard 6
remove 5
pop
discard 5
Sample Output
4
Explanation
After completing these operations on the set, we get set. Hence, the sum is .
Note: Convert the elements of set s to integers while you are assigning them. To ensure the proper input of the set, we have added the first two lines of code to the editor.
"""
n = int(input())
s = set(map(int, input().split()))
n = int(input())
k = []
for i in range(N):
k = input().split()
if k[0] == 'pop':
s.pop()
if k[0] == 'remove':
s.remove(int(k[1]))
if k[0] == 'discard':
s.discard(int(k[1]))
print(sum(s)) |
ERR_SUCCESSFUL = 0
ERR_AUTHENTICATION_FAILED = 1
ERR_DUPLICATE_MODEL = 2
ERR_DOT_NOT_EXIST = 3
ERR_PERMISSION_DENIED = 4
ERR_INVALID_CREDENTIALS = 5
ERR_AUTHENTICATION_FAILED = 6
ERR_USER_IS_INACTIVE = 7
ERR_NOT_AUTHENTICATED = 8
ERR_INPUT_VALIDATION = 9
ERR_PARSE = 10
ERR_UNSUPPORTED_MEDIA = 11
ERR_METHOD_NOT_ALLOWED = 12
ERR_NOT_ACCEPTABLE = 13
ERR_CONFLICT = 14
ERR_INTERNAL = 15
| err_successful = 0
err_authentication_failed = 1
err_duplicate_model = 2
err_dot_not_exist = 3
err_permission_denied = 4
err_invalid_credentials = 5
err_authentication_failed = 6
err_user_is_inactive = 7
err_not_authenticated = 8
err_input_validation = 9
err_parse = 10
err_unsupported_media = 11
err_method_not_allowed = 12
err_not_acceptable = 13
err_conflict = 14
err_internal = 15 |
# Bottom-Up Dynamic Programming (Tabulation)
class Solution:
def minCostClimbingStairs(self, cost: list[int]) -> int:
# The array's length should be 1 longer than the length of cost
# This is because we can treat the "top floor" as a step to reach
minimum_cost = [0] * (len(cost) + 1)
# Start iteration from step 2, since the minimum cost of reaching
# step 0 and step 1 is 0
for i in range(2, len(cost) + 1):
take_one_step = minimum_cost[i - 1] + cost[i - 1]
take_two_steps = minimum_cost[i - 2] + cost[i - 2]
minimum_cost[i] = min(take_one_step, take_two_steps)
# The final element in minimum_cost refers to the top floor
return minimum_cost[-1]
# Top-Down Dynamic Programming (Recursion + Memoization)
class Solution:
def minCostClimbingStairs(self, cost: list[int]) -> int:
def minimum_cost(i):
# Base case, we are allowed to start at either step 0 or step 1
if i <= 1:
return 0
# Check if we have already calculated minimum_cost(i)
if i in memo:
return memo[i]
# If not, cache the result in our hash map and return it
down_one = cost[i - 1] + minimum_cost(i - 1)
down_two = cost[i - 2] + minimum_cost(i - 2)
memo[i] = min(down_one, down_two)
return memo[i]
memo = {}
return minimum_cost(len(cost))
# Bottom-Up, Constant Space
class Solution:
def minCostClimbingStairs(self, cost: list[int]) -> int:
down_one = down_two = 0
for i in range(2, len(cost) + 1):
temp = down_one
down_one = min(down_one + cost[i - 1], down_two + cost[i - 2])
down_two = temp
return down_one
| class Solution:
def min_cost_climbing_stairs(self, cost: list[int]) -> int:
minimum_cost = [0] * (len(cost) + 1)
for i in range(2, len(cost) + 1):
take_one_step = minimum_cost[i - 1] + cost[i - 1]
take_two_steps = minimum_cost[i - 2] + cost[i - 2]
minimum_cost[i] = min(take_one_step, take_two_steps)
return minimum_cost[-1]
class Solution:
def min_cost_climbing_stairs(self, cost: list[int]) -> int:
def minimum_cost(i):
if i <= 1:
return 0
if i in memo:
return memo[i]
down_one = cost[i - 1] + minimum_cost(i - 1)
down_two = cost[i - 2] + minimum_cost(i - 2)
memo[i] = min(down_one, down_two)
return memo[i]
memo = {}
return minimum_cost(len(cost))
class Solution:
def min_cost_climbing_stairs(self, cost: list[int]) -> int:
down_one = down_two = 0
for i in range(2, len(cost) + 1):
temp = down_one
down_one = min(down_one + cost[i - 1], down_two + cost[i - 2])
down_two = temp
return down_one |
nterms = int(input())
n1=0
n2=1
count=0
if nterms <= 0:
print("please enter a positive integer")
elif nterms==1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count+=1
| nterms = int(input())
n1 = 0
n2 = 1
count = 0
if nterms <= 0:
print('please enter a positive integer')
elif nterms == 1:
print('Fibonacci sequence upto', nterms, ':')
print(n1)
else:
print('Fibonacci sequence:')
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1 |
def load(h):
return ({'abbr': 0,
'code': 0,
'title': 'Parcel lifted index (to 500 hPa)',
'units': 'K'},
{'abbr': 1,
'code': 1,
'title': 'Best lifted index (to 500 hPa)',
'units': 'K'},
{'abbr': 2, 'code': 2, 'title': 'K index', 'units': 'K'},
{'abbr': 3, 'code': 3, 'title': 'KO index', 'units': 'K'},
{'abbr': 4, 'code': 4, 'title': 'Total totals index', 'units': 'K'},
{'abbr': 5, 'code': 5, 'title': 'Sweat index', 'units': 'Numeric'},
{'abbr': 6,
'code': 6,
'title': 'Convective available potential energy',
'units': 'J kg-1'},
{'abbr': 7, 'code': 7, 'title': 'Convective inhibition', 'units': 'J kg-1'},
{'abbr': 8, 'code': 8, 'title': 'Storm relative helicity', 'units': 'J kg-1'},
{'abbr': 9, 'code': 9, 'title': 'Energy helicity index', 'units': 'Numeric'},
{'abbr': 10, 'code': 10, 'title': 'Surface lifted index', 'units': 'K'},
{'abbr': 11, 'code': 11, 'title': 'Best (4-layer) lifted index', 'units': 'K'},
{'abbr': 12, 'code': 12, 'title': 'Richardson number', 'units': 'Numeric'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
| def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Parcel lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 1, 'code': 1, 'title': 'Best lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 2, 'code': 2, 'title': 'K index', 'units': 'K'}, {'abbr': 3, 'code': 3, 'title': 'KO index', 'units': 'K'}, {'abbr': 4, 'code': 4, 'title': 'Total totals index', 'units': 'K'}, {'abbr': 5, 'code': 5, 'title': 'Sweat index', 'units': 'Numeric'}, {'abbr': 6, 'code': 6, 'title': 'Convective available potential energy', 'units': 'J kg-1'}, {'abbr': 7, 'code': 7, 'title': 'Convective inhibition', 'units': 'J kg-1'}, {'abbr': 8, 'code': 8, 'title': 'Storm relative helicity', 'units': 'J kg-1'}, {'abbr': 9, 'code': 9, 'title': 'Energy helicity index', 'units': 'Numeric'}, {'abbr': 10, 'code': 10, 'title': 'Surface lifted index', 'units': 'K'}, {'abbr': 11, 'code': 11, 'title': 'Best (4-layer) lifted index', 'units': 'K'}, {'abbr': 12, 'code': 12, 'title': 'Richardson number', 'units': 'Numeric'}, {'abbr': None, 'code': 255, 'title': 'Missing'}) |
# channel.py
# ~~~~~~~~~
# This module implements the Channel class.
# :authors: Justin Karneges, Konstantin Bokarius.
# :copyright: (c) 2015 by Fanout, Inc.
# :license: MIT, see LICENSE for more details.
# The Channel class is used to represent a channel in a GRIP proxy and
# tracks the previous ID of the last message.
class Channel(object):
# Initialize with the channel name and an optional previous ID.
def __init__(self, name, prev_id=None):
self.name = name
self.prev_id = prev_id
self.filters = []
| class Channel(object):
def __init__(self, name, prev_id=None):
self.name = name
self.prev_id = prev_id
self.filters = [] |
def main():
st = input("")
print(min(st))
main()
| def main():
st = input('')
print(min(st))
main() |
def sum_of_digits(digits) -> str:
if not str(digits).isdecimal():
return ''
else:
return f'{" + ".join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}'
| def sum_of_digits(digits) -> str:
if not str(digits).isdecimal():
return ''
else:
return f"{' + '.join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}" |
str = 'Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string | str = 'Hello World!'
print(str)
print(str[0])
print(str[2:5])
print(str[2:])
print(str * 2)
print(str + 'TEST') |
#D&D D12 die with 12 pentagonal faces
af = 7
textH = 2
textD = 0.3
faces = {"1":(0,0), "2":(60,72), "3":(60,72*2), "4":(60,72*3), "5":(60,72*4), "6":(60,0),
"C":(180,0),"B":(120,72*3+36),"A":(120,72*4+36),"9":(120,36),"8":(120,72+36),"7":(120,72*2+36)}
a = cq.Workplane("XY").sphere(5)
for k in faces.keys():
abtY , abtZ = faces[k]
a = a.cut(cq.Workplane("XY").transformed(rotate=cq.Vector(abtY,0,0))
.workplane(offset=af/2).rect(10,10).extrude(10).rotate((0,0,0),(0,0,1),abtZ))
a = a.fillet(.5)
for k in faces.keys():
abtY , abtZ = faces[k]
a = a.cut(cq.Workplane("XY").transformed(rotate=cq.Vector(abtY,0,0))
.workplane(offset=af/2-textD).text(k,textH,textD).rotate((0,0,0),(0,0,1),abtZ))
| af = 7
text_h = 2
text_d = 0.3
faces = {'1': (0, 0), '2': (60, 72), '3': (60, 72 * 2), '4': (60, 72 * 3), '5': (60, 72 * 4), '6': (60, 0), 'C': (180, 0), 'B': (120, 72 * 3 + 36), 'A': (120, 72 * 4 + 36), '9': (120, 36), '8': (120, 72 + 36), '7': (120, 72 * 2 + 36)}
a = cq.Workplane('XY').sphere(5)
for k in faces.keys():
(abt_y, abt_z) = faces[k]
a = a.cut(cq.Workplane('XY').transformed(rotate=cq.Vector(abtY, 0, 0)).workplane(offset=af / 2).rect(10, 10).extrude(10).rotate((0, 0, 0), (0, 0, 1), abtZ))
a = a.fillet(0.5)
for k in faces.keys():
(abt_y, abt_z) = faces[k]
a = a.cut(cq.Workplane('XY').transformed(rotate=cq.Vector(abtY, 0, 0)).workplane(offset=af / 2 - textD).text(k, textH, textD).rotate((0, 0, 0), (0, 0, 1), abtZ)) |
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ! Please change the following two path strings to you own one !
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ELINA_PYTHON_INTERFACE_PATH = '/home/xxxxx/pkgs/ELINA/python_interface'
DEEPG_CODE_PATH = '/home/xxxxx/pkgs/deepg/code'
NORM_TYPES = ['0', '1', '2', 'inf']
DATASETS = ["imagenet", "cifar10", "mnist"]
METHOD_LIST = ['Clean',
'PGD',
'CW',
'MILP',
'FastMILP',
'PercySDP',
'FazlybSDP',
'AI2',
'RefineZono',
'LPAll',
'kReLU',
'DeepPoly',
'ZicoDualLP',
'CROWN',
'CROWN_IBP',
'CNNCert',
'FastLin_IBP',
'FastLin',
'FastLinSparse',
'FastLip',
'RecurJac',
'Spectral',
'IBP',
'IBPVer2']
| elina_python_interface_path = '/home/xxxxx/pkgs/ELINA/python_interface'
deepg_code_path = '/home/xxxxx/pkgs/deepg/code'
norm_types = ['0', '1', '2', 'inf']
datasets = ['imagenet', 'cifar10', 'mnist']
method_list = ['Clean', 'PGD', 'CW', 'MILP', 'FastMILP', 'PercySDP', 'FazlybSDP', 'AI2', 'RefineZono', 'LPAll', 'kReLU', 'DeepPoly', 'ZicoDualLP', 'CROWN', 'CROWN_IBP', 'CNNCert', 'FastLin_IBP', 'FastLin', 'FastLinSparse', 'FastLip', 'RecurJac', 'Spectral', 'IBP', 'IBPVer2'] |
def FlagsForFile( filename ):
return { 'flags': [
'-Wall',
'-Wextra',
'-Werror',
'-std=c++11',
'-x', 'c++',
'-isystem', '/usr/include/c++/10',
'-isystem', '/usr/include/c++/10/backward',
'-isystem', '/usr/local/include',
'-isystem', '/usr/include',
] }
| def flags_for_file(filename):
return {'flags': ['-Wall', '-Wextra', '-Werror', '-std=c++11', '-x', 'c++', '-isystem', '/usr/include/c++/10', '-isystem', '/usr/include/c++/10/backward', '-isystem', '/usr/local/include', '-isystem', '/usr/include']} |
def increaseNumberRoundness(n):
gotToSignificant = False
while n > 0:
if n % 10 == 0 and gotToSignificant:
return True
elif n % 10 != 0:
gotToSignificant = True
n /= 10
return False
| def increase_number_roundness(n):
got_to_significant = False
while n > 0:
if n % 10 == 0 and gotToSignificant:
return True
elif n % 10 != 0:
got_to_significant = True
n /= 10
return False |
fname = input('please enter a file name: ')
fhand = open('romeo.txt')
new_list = list()
for line in fhand:
word = line.split()
for element in word:
if element not in new_list:
new_list.append(element)
new_list.sort()
print(new_list)
| fname = input('please enter a file name: ')
fhand = open('romeo.txt')
new_list = list()
for line in fhand:
word = line.split()
for element in word:
if element not in new_list:
new_list.append(element)
new_list.sort()
print(new_list) |
# Copyright 2015-2018 Camptocamp SA, Damien Crier
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Colorize field in tree views",
"summary": "Allows you to dynamically color fields on tree views",
"category": "Hidden/Dependency",
"version": "14.0.1.0.0",
"depends": ["web"],
"author": "Camptocamp, Therp BV, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/web",
"demo": ["demo/res_users.xml"],
"data": ["views/web_tree_dynamic_colored_field.xml"],
"installable": True,
}
| {'name': 'Colorize field in tree views', 'summary': 'Allows you to dynamically color fields on tree views', 'category': 'Hidden/Dependency', 'version': '14.0.1.0.0', 'depends': ['web'], 'author': 'Camptocamp, Therp BV, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'website': 'https://github.com/OCA/web', 'demo': ['demo/res_users.xml'], 'data': ['views/web_tree_dynamic_colored_field.xml'], 'installable': True} |
# EDA: Target - Q1
print("Number of unique cities in the data set:\n", df_tar['Target City'].nunique())
print("---------------------------------------")
most_frequent_cities = df_tar['Target City'].value_counts().sort_values(ascending=False)[:15]
print("Most frequent cities:\n", most_frequent_cities)
print("---------------------------------------") | print('Number of unique cities in the data set:\n', df_tar['Target City'].nunique())
print('---------------------------------------')
most_frequent_cities = df_tar['Target City'].value_counts().sort_values(ascending=False)[:15]
print('Most frequent cities:\n', most_frequent_cities)
print('---------------------------------------') |
class ScreenIdError(ValueError):
pass
class UssdNamespaceError(RuntimeError):
pass | class Screeniderror(ValueError):
pass
class Ussdnamespaceerror(RuntimeError):
pass |
def matchParenthesis(string):
parenthesis = 0
brackets = 0
curlyBrackets = 0
for i in range(len(string)):
l = string[i]
if l == '(':
if i > 0:
if not string[i-1] == ':' and not string[i-1] == ';':
parenthesis += 1
else:
parenthesis += 1
elif l == '[':
brackets += 1
elif l == '{':
curlyBrackets += 1
elif l == ')':
if i > 0:
if not (string[i-1] == ':' or string[i-1] == ';'):
if i > 1:
if not string[i-2] == '-':
parenthesis -= 1
elif l == ']':
brackets -= 1
elif l == '}':
curlyBrackets -= 1
fix = ""
if parenthesis > 0:
for i in range(parenthesis):
fix += ")"
else:
for i in range(parenthesis * -1):
fix += "("
if brackets > 0:
for i in range(brackets):
fix += "]"
else:
for i in range(brackets * -1):
fix += "["
if curlyBrackets > 0:
for i in range(curlyBrackets):
fix += "}"
else:
for i in range(curlyBrackets * -1):
fix += "{"
return fix
| def match_parenthesis(string):
parenthesis = 0
brackets = 0
curly_brackets = 0
for i in range(len(string)):
l = string[i]
if l == '(':
if i > 0:
if not string[i - 1] == ':' and (not string[i - 1] == ';'):
parenthesis += 1
else:
parenthesis += 1
elif l == '[':
brackets += 1
elif l == '{':
curly_brackets += 1
elif l == ')':
if i > 0:
if not (string[i - 1] == ':' or string[i - 1] == ';'):
if i > 1:
if not string[i - 2] == '-':
parenthesis -= 1
elif l == ']':
brackets -= 1
elif l == '}':
curly_brackets -= 1
fix = ''
if parenthesis > 0:
for i in range(parenthesis):
fix += ')'
else:
for i in range(parenthesis * -1):
fix += '('
if brackets > 0:
for i in range(brackets):
fix += ']'
else:
for i in range(brackets * -1):
fix += '['
if curlyBrackets > 0:
for i in range(curlyBrackets):
fix += '}'
else:
for i in range(curlyBrackets * -1):
fix += '{'
return fix |
_base_ = [
'../_base_/datasets/imagenet_bs128.py',
'../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py'
]
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResArch',
arch='IRNet-18',
num_stages=4,
out_indices=(1,2,3),
style='pytorch'),
neck=dict(
type='MultiLevelFuse',
in_channels=[128, 256, 512],
out_channels=256,
conv_type='XNOR'),
head=dict(
type='IRClsHead',
num_classes=1000,
in_channels=256,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
find_unused_parameters=True
seed = 166
| _base_ = ['../_base_/datasets/imagenet_bs128.py', '../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py']
model = dict(type='ImageClassifier', backbone=dict(type='ResArch', arch='IRNet-18', num_stages=4, out_indices=(1, 2, 3), style='pytorch'), neck=dict(type='MultiLevelFuse', in_channels=[128, 256, 512], out_channels=256, conv_type='XNOR'), head=dict(type='IRClsHead', num_classes=1000, in_channels=256, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1, 5)))
find_unused_parameters = True
seed = 166 |
a = 2
b = 0
try:
print(a/b)
except ZeroDivisionError:
print('Division by zero is not allowed') | a = 2
b = 0
try:
print(a / b)
except ZeroDivisionError:
print('Division by zero is not allowed') |
# Problem Set 2, Question 3
# These hold the values of the balance.
balance = 320000
origBalance = balance
# These hold the values of the annual and monthly interest rates.
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12
lowerBound = balance / 12
upperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12.0
# This goes through all the possibilites.
while (abs(balance) > 0.01):
# Reset the value of balance to its original value
balance = origBalance
# Calculate a new monthly payment value from the bounds
payment = (upperBound - lowerBound) / 2 + lowerBound
# Test if this payment value is sufficient to pay off the entire balance in 12 months
for month in range(12):
balance -= payment
balance *= 1 + monthlyInterestRate
# Reset bounds based on the final value of balance
if balance > 0:
# If the balance is too big, need higher payment so we increase the lower bound
lowerBound = payment
else:
# If the balance is too small, we need a lower payment, so we decrease the upper bound
upperBound = payment
print ("Lowest Payment: " + str(round(payment, 2))) | balance = 320000
orig_balance = balance
annual_interest_rate = 0.2
monthly_interest_rate = annualInterestRate / 12
lower_bound = balance / 12
upper_bound = balance * (1 + monthlyInterestRate) ** 12 / 12.0
while abs(balance) > 0.01:
balance = origBalance
payment = (upperBound - lowerBound) / 2 + lowerBound
for month in range(12):
balance -= payment
balance *= 1 + monthlyInterestRate
if balance > 0:
lower_bound = payment
else:
upper_bound = payment
print('Lowest Payment: ' + str(round(payment, 2))) |
# Advent of code 2018
# Antti "Waitee" Auranen
# Day 4
# Example of the datetime part of the logs:
# [1518-10-12 00:15]
#
# Examples of the message part of the logs:
# Guard #1747 begins shift
# falls asleep
# wakes up
def main():
inputs = []
guards = []
while(True):
s = input("> ")
#split the lines into tuples for easier sorting
if len(s) > 0:
line = (s[1:17], s[19:])
inputs.append(line)
else:
break
inputs = quickSort(inputs)
for a in inputs:
# print(a)
if a[1][:5] == "Guard":
guard = a[1][s.find("#")+1 : s.find("begins") -1]
guards.append([guard, 0])
for a in guards:
print(a)
return 0
def quickSort(xs):
before = []
after = []
now = []
if len(xs) > 1:
pivot = xs[0][0]
for a in xs:
if a[0] < pivot:
before.append(a)
if a[0] == pivot:
now.append(a)
if a[0] > pivot:
after.append(a)
return quickSort(before) + now + quickSort(after)
else:
return xs
main() | def main():
inputs = []
guards = []
while True:
s = input('> ')
if len(s) > 0:
line = (s[1:17], s[19:])
inputs.append(line)
else:
break
inputs = quick_sort(inputs)
for a in inputs:
if a[1][:5] == 'Guard':
guard = a[1][s.find('#') + 1:s.find('begins') - 1]
guards.append([guard, 0])
for a in guards:
print(a)
return 0
def quick_sort(xs):
before = []
after = []
now = []
if len(xs) > 1:
pivot = xs[0][0]
for a in xs:
if a[0] < pivot:
before.append(a)
if a[0] == pivot:
now.append(a)
if a[0] > pivot:
after.append(a)
return quick_sort(before) + now + quick_sort(after)
else:
return xs
main() |
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
steps = 0
# Walk upwards, counting steps until first slope down
while steps + 1 < len(arr) and arr[steps] < arr[steps + 1]:
steps += 1
# Check if there was no incline or it ends in a cliff
if steps == 0 or steps == len(arr) -1:
return False
#Walk downwards the slope counting to make sure there are no inclines again
while steps + 1 < len(arr) and arr[steps] > arr[steps + 1]:
steps += 1
#compare if length equals to step down
return steps == len(arr) - 1 | class Solution:
def valid_mountain_array(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
steps = 0
while steps + 1 < len(arr) and arr[steps] < arr[steps + 1]:
steps += 1
if steps == 0 or steps == len(arr) - 1:
return False
while steps + 1 < len(arr) and arr[steps] > arr[steps + 1]:
steps += 1
return steps == len(arr) - 1 |
def run(proj_path, target_name, params):
return {
"project_name": "Sample",
"build_types": ["Debug", "Release"],
"archs": [
{
"arch": "x86_64",
"conan_arch": "x86_64",
"conan_profile": "ezored_windows_app_profile",
}
],
}
| def run(proj_path, target_name, params):
return {'project_name': 'Sample', 'build_types': ['Debug', 'Release'], 'archs': [{'arch': 'x86_64', 'conan_arch': 'x86_64', 'conan_profile': 'ezored_windows_app_profile'}]} |
def feature_extraction(cfg,Z,N) : #function Descriptors=feature_extraction(Z,N)
#
#% The features are the magnitude of the Zernike moments.
#% Collect the moments into (2*l+1)-dimensional vectors
#% and define the rotationally invariant 3D Zernike descriptors
#% Fnl as norms of vectors Znl.
#
F=cfg.zeros(N+1,N+1)+cfg.NaN #F=zeros(N+1,N+1)+NaN;
#% Calcuate the magnitude
for n in cfg.rng(0,N) : #for n=0:N
for l in cfg.rng(0,n) : # for l=0:n
if cfg.mod(n-l,2)==0 : # if mod(n-l,2)==0
aux_1=Z[n,l,0:(l+1)] #! # aux_1=Z(n+1,l+1,1:l+1);
#! matlab col-major; no need to transpose # aux_1=aux_1(:)';
if l > 0 : # if l>0
# % Taking the values for m<0
aux_2=cfg.conj(aux_1[1:(l+1)]) #! # aux_2=conj(aux_1(2:(l+1)));
for m in cfg.rng(1,l) : # for m=1:l
aux_2[m-1]=aux_2[m-1]*cfg.power(-1,m) #! # aux_2(m)=aux_2(m)*power(-1,m);
# end
# % Sorting the vector
aux_2=cfg.rot90(aux_2,2) # aux_2=rot90(aux_2,2);
aux_1=cfg.cat(0,aux_2,aux_1) #! axis # aux_1=cat(2,aux_2,aux_1);
# end
F[n,l] = cfg.norm(aux_1,2) #! # F(n+1,l+1)=norm(aux_1,2);
# end
# end
#end
#% Generate vector of Zernike descriptors
#% Column vector that store the magnitude
#% of the Zernike moments for n,l.
F = F.transpose() #! matlab indexin is col-wise. tranpose does not affect the values, just their ordering
idx=cfg.find(F>=0) #idx=find(F>=0);
Descriptors = F[idx] #Descriptors=F(idx);
return Descriptors
| def feature_extraction(cfg, Z, N):
f = cfg.zeros(N + 1, N + 1) + cfg.NaN
for n in cfg.rng(0, N):
for l in cfg.rng(0, n):
if cfg.mod(n - l, 2) == 0:
aux_1 = Z[n, l, 0:l + 1]
if l > 0:
aux_2 = cfg.conj(aux_1[1:l + 1])
for m in cfg.rng(1, l):
aux_2[m - 1] = aux_2[m - 1] * cfg.power(-1, m)
aux_2 = cfg.rot90(aux_2, 2)
aux_1 = cfg.cat(0, aux_2, aux_1)
F[n, l] = cfg.norm(aux_1, 2)
f = F.transpose()
idx = cfg.find(F >= 0)
descriptors = F[idx]
return Descriptors |
#!/usr/bin/env python3
'''
Given a string, write a function to check if it is a permutation of a palindrome.
A palindrome is a word or phrase that is the same forwards and backwards.
A permutation is a rearrangement of letters.
The palindrome does not need to be limited to just dictionary words
'''
def palindrome_permutation(string): # O(n)
if len(string) < 2: # any single character or empty string
return True
counts = [string.count(c) for c in set(string) if c != ' '] # 'tacocat' -> [2,2,2,1]
if all(n % 2 == 0 for n in counts): # all characters have an even count
return True
return [n % 2 == 1 for n in counts].count(True) == 1 # only 1 character can have odd count | """
Given a string, write a function to check if it is a permutation of a palindrome.
A palindrome is a word or phrase that is the same forwards and backwards.
A permutation is a rearrangement of letters.
The palindrome does not need to be limited to just dictionary words
"""
def palindrome_permutation(string):
if len(string) < 2:
return True
counts = [string.count(c) for c in set(string) if c != ' ']
if all((n % 2 == 0 for n in counts)):
return True
return [n % 2 == 1 for n in counts].count(True) == 1 |
# ../../../../goal/translate.py --gcrootfinder=asmgcc --gc=semispace src8
class A:
pass
def foo(rec, a1, a2, a3, a4, a5, a6):
if rec > 0:
b = A()
foo(rec-1, b, b, b, b, b, b)
foo(rec-1, b, b, b, b, b, b)
foo(rec-1, a6, a5, a4, a3, a2, a1)
# __________ Entry point __________
def entry_point(argv):
foo(5, A(), A(), A(), A(), A(), A())
return 0
# _____ Define and setup target ___
def target(*args):
return entry_point, None
| class A:
pass
def foo(rec, a1, a2, a3, a4, a5, a6):
if rec > 0:
b = a()
foo(rec - 1, b, b, b, b, b, b)
foo(rec - 1, b, b, b, b, b, b)
foo(rec - 1, a6, a5, a4, a3, a2, a1)
def entry_point(argv):
foo(5, a(), a(), a(), a(), a(), a())
return 0
def target(*args):
return (entry_point, None) |
# by Kami Bigdely
# Split temporary variable
patty = 70 # [gr]
pickle = 20 # [gr]
tomatoes = 25 # [gr]
lettuce = 15 # [gr]
buns = 95 # [gr]
kimchi = 30 # [gr]
mayo = 5 # [gr]
golden_fried_onion = 20 # [gr]
ny_burger_weight = (2 * patty + 4 * pickle + 3 *
tomatoes + 2 * lettuce + 2 * buns)
kimchi_burger_weight = (2 * patty + 4 * pickle + 3 * tomatoes +
kimchi + mayo + golden_fried_onion + 2 * buns)
if __name__ == "__main__":
print(f"NY Burger Weight {ny_burger_weight}lbs")
print(f"Seoul Kimchi Burger Weight {kimchi_burger_weight}lbs")
| patty = 70
pickle = 20
tomatoes = 25
lettuce = 15
buns = 95
kimchi = 30
mayo = 5
golden_fried_onion = 20
ny_burger_weight = 2 * patty + 4 * pickle + 3 * tomatoes + 2 * lettuce + 2 * buns
kimchi_burger_weight = 2 * patty + 4 * pickle + 3 * tomatoes + kimchi + mayo + golden_fried_onion + 2 * buns
if __name__ == '__main__':
print(f'NY Burger Weight {ny_burger_weight}lbs')
print(f'Seoul Kimchi Burger Weight {kimchi_burger_weight}lbs') |
def get_nonempty_wallets_number_query():
pipeline = [
{'$match': {'balance': {'$gt': 0}}
},
{'$group': {
'_id': 'null',
'count': {'$sum': 1}
}
},
{'$project': {
'_id': 0,
'count': 1
}
}
]
return pipeline
def get_highest_block_number_in_db_query():
pipeline = [
{'$sort': {'height': -1}
},
{'$limit': 1
},
{'$project': {
'height': 1
}
}
]
return pipeline
def get_blocks_in_range_query(lower_height, upper_height, projection):
pipeline = [
{'$match': {'height': {'$gte': lower_height}}
},
{'$match': {'height': {'$lte': upper_height}}
},
{'$sort': {'height': 1}
},
{'$project': projection
}
]
return pipeline
def get_last_n_blocks_query(interval, projection):
pipeline = [
{'$sort': {'height': -1}
},
{'$limit': interval
},
{'$project': projection
}
]
return pipeline
def get_total_coin_supply_query():
pipeline = [
{'$group': {
'_id': 'null',
'total_coin_supply': {'$sum': '$balance'}
}
},
{'$project': {
'total_coin_supply': 1,
'_id': 0
}
}
]
return pipeline
def get_blocks_coinbase_addresses_count_query(interval, lower_height, upper_height):
projection = {'tx': {'$arrayElemAt': ['$tx', 0]}}
if interval > 0:
pipeline = get_last_n_blocks_query(interval, projection)
else:
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [
{'$unwind': '$tx.vout'},
{'$match': {'tx.vout.scriptPubKey.addresses': {'$ne': []}}},
{'$project': {
'addresses': '$tx.vout.scriptPubKey.addresses'
}
},
{'$group': {
'_id': '$addresses',
'count': {'$sum': 1}
}
},
{'$project': {
'address': {'$arrayElemAt': ['$_id', 0]},
'count': 1,
'_id': 0
}
}
]
return pipeline
def get_transactions_average_volume_query(interval, lower_height, upper_height):
projection = {
'height': 1,
'time': 1,
'tx': {
'$cond': {
'if': {'$eq': [{'$size': '$tx'}, 1]},
'then': '$$REMOVE',
'else': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}
}
},
'count': {
'$cond': {
'if': {'$eq': [{'$size': '$tx'}, 1]},
'then': '$$REMOVE',
'else': {'$size': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}}
}
}
}
boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)]
boundaries[-1] += 1
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [
{'$project': {
'height': 1,
'value': {
'$sum': {
'$reduce': {
'input': '$tx.vout.value',
'initialValue': [],
'in': {'$concatArrays': ['$$value', '$$this']}
}
}
},
'count': 1
}
},
{'$match': {
'value': {'$gt': 0}
}
},
{'$bucket': {
'groupBy': '$height',
'boundaries': boundaries,
'default': boundaries[-1],
'output': {
'lower_height': {'$min': '$height'},
'upper_height': {'$max': '$height'},
'sum': {'$sum': '$value'},
'min': {'$min': '$value'},
'max': {'$max': '$value'},
'count': {'$sum': '$count'}
}
}
},
{'$project': {
'lower_height': 1,
'upper_height': 1,
'sum': 1,
'avg': {'$divide': ['$sum', '$count']},
'min': 1,
'max': 1,
'count': 1
}
}
]
return pipeline
def get_blocks_average_difficulty_query(interval, lower_height, upper_height):
projection = {
'time': 1,
'height': 1,
'difficulty': 1
}
boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)]
boundaries[-1] += 1
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [
{'$bucket': {
'groupBy': '$height',
'boundaries': boundaries,
'default': boundaries[-1],
'output': {
'lower_height': {'$min': '$height'},
'upper_height': {'$max': '$height'},
'avg_difficulty': {'$avg': '$difficulty'}
}
}
}
]
return pipeline
| def get_nonempty_wallets_number_query():
pipeline = [{'$match': {'balance': {'$gt': 0}}}, {'$group': {'_id': 'null', 'count': {'$sum': 1}}}, {'$project': {'_id': 0, 'count': 1}}]
return pipeline
def get_highest_block_number_in_db_query():
pipeline = [{'$sort': {'height': -1}}, {'$limit': 1}, {'$project': {'height': 1}}]
return pipeline
def get_blocks_in_range_query(lower_height, upper_height, projection):
pipeline = [{'$match': {'height': {'$gte': lower_height}}}, {'$match': {'height': {'$lte': upper_height}}}, {'$sort': {'height': 1}}, {'$project': projection}]
return pipeline
def get_last_n_blocks_query(interval, projection):
pipeline = [{'$sort': {'height': -1}}, {'$limit': interval}, {'$project': projection}]
return pipeline
def get_total_coin_supply_query():
pipeline = [{'$group': {'_id': 'null', 'total_coin_supply': {'$sum': '$balance'}}}, {'$project': {'total_coin_supply': 1, '_id': 0}}]
return pipeline
def get_blocks_coinbase_addresses_count_query(interval, lower_height, upper_height):
projection = {'tx': {'$arrayElemAt': ['$tx', 0]}}
if interval > 0:
pipeline = get_last_n_blocks_query(interval, projection)
else:
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [{'$unwind': '$tx.vout'}, {'$match': {'tx.vout.scriptPubKey.addresses': {'$ne': []}}}, {'$project': {'addresses': '$tx.vout.scriptPubKey.addresses'}}, {'$group': {'_id': '$addresses', 'count': {'$sum': 1}}}, {'$project': {'address': {'$arrayElemAt': ['$_id', 0]}, 'count': 1, '_id': 0}}]
return pipeline
def get_transactions_average_volume_query(interval, lower_height, upper_height):
projection = {'height': 1, 'time': 1, 'tx': {'$cond': {'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}}}, 'count': {'$cond': {'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$size': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}}}}}
boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)]
boundaries[-1] += 1
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [{'$project': {'height': 1, 'value': {'$sum': {'$reduce': {'input': '$tx.vout.value', 'initialValue': [], 'in': {'$concatArrays': ['$$value', '$$this']}}}}, 'count': 1}}, {'$match': {'value': {'$gt': 0}}}, {'$bucket': {'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': {'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'sum': {'$sum': '$value'}, 'min': {'$min': '$value'}, 'max': {'$max': '$value'}, 'count': {'$sum': '$count'}}}}, {'$project': {'lower_height': 1, 'upper_height': 1, 'sum': 1, 'avg': {'$divide': ['$sum', '$count']}, 'min': 1, 'max': 1, 'count': 1}}]
return pipeline
def get_blocks_average_difficulty_query(interval, lower_height, upper_height):
projection = {'time': 1, 'height': 1, 'difficulty': 1}
boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)]
boundaries[-1] += 1
pipeline = get_blocks_in_range_query(lower_height, upper_height, projection)
pipeline += [{'$bucket': {'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': {'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'avg_difficulty': {'$avg': '$difficulty'}}}}]
return pipeline |
class ship:
name = "Unknown"
maelstrom_location_data = None
quadrant = ''
sector = ''
def __init__(self, name = "Unknown", maelstrom_location_data = None):
self.name = name
self.maelstrom_location_data = maelstrom_location_data
def getMaelstromLocationData(self):
return self.maelstrom_location_data
def setMaelstromCoordinates(self, quadrant, sector):
self.quadrant = quadrant
self.sector = sector
def setNewMaelstromLocation(self, maelstrom_location_data):
self.maelstrom_location_data = maelstrom_location_data
def getShipCoordinates(self):
return self.maelstrom_location_data.getCoordinates()
def getShipQuadrant(self):
return self.maelstrom_location_data.getQuadrant()
def getShipSector(self):
return self.maelstrom_location_data.getSector()
def getMontressorPerceptionCheck(self, quadrant, sector):
return self.maelstrom_location_data.getMontressorPerceptionCheck(quadrant, sector)
| class Ship:
name = 'Unknown'
maelstrom_location_data = None
quadrant = ''
sector = ''
def __init__(self, name='Unknown', maelstrom_location_data=None):
self.name = name
self.maelstrom_location_data = maelstrom_location_data
def get_maelstrom_location_data(self):
return self.maelstrom_location_data
def set_maelstrom_coordinates(self, quadrant, sector):
self.quadrant = quadrant
self.sector = sector
def set_new_maelstrom_location(self, maelstrom_location_data):
self.maelstrom_location_data = maelstrom_location_data
def get_ship_coordinates(self):
return self.maelstrom_location_data.getCoordinates()
def get_ship_quadrant(self):
return self.maelstrom_location_data.getQuadrant()
def get_ship_sector(self):
return self.maelstrom_location_data.getSector()
def get_montressor_perception_check(self, quadrant, sector):
return self.maelstrom_location_data.getMontressorPerceptionCheck(quadrant, sector) |
def pow(x,y):
if y==0:
return 1
else:
temp = pow(x,int(y/2))
mult = x if y>0 else 1/x
if y%2==1:
return mult * temp * temp
else:
return temp * temp
if __name__ == "__main__":
x = 2
y = 5
res = pow(x,y)
print(res)
x = 3
y = -2
res = pow(x,y)
print(res)
x = 1
y = 0
res = pow(x,y)
print(res) | def pow(x, y):
if y == 0:
return 1
else:
temp = pow(x, int(y / 2))
mult = x if y > 0 else 1 / x
if y % 2 == 1:
return mult * temp * temp
else:
return temp * temp
if __name__ == '__main__':
x = 2
y = 5
res = pow(x, y)
print(res)
x = 3
y = -2
res = pow(x, y)
print(res)
x = 1
y = 0
res = pow(x, y)
print(res) |
class Person:
def say_hi(self):
print('Hello, how are you?')
vinit = Person() # object created
vinit.say_hi() # object calls class method.
| class Person:
def say_hi(self):
print('Hello, how are you?')
vinit = person()
vinit.say_hi() |
# Implementation of the queue data structure.
# A list is used to store queue elements, where the tail
# of the queue is element 0, and the head is
# the last element
class Queue:
'''
Constructor. Initializes the list items
'''
def __init__(self):
self.items = []
'''
Returns true if queue is empty, false otherwise
'''
def is_empty(self):
return self.items == []
'''
Enqueue: Add item to end (tail) of the queue
'''
def enqueue(self, item):
self.items.insert(0,item)
'''
Dequeue: Remove item from font of the queue
'''
def dequeue(self):
return self.items.pop()
'''
Returns queue size
'''
def size(self):
return len(self.items)
def main():
# Illustrates FIFO behavior
q = Queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print("Queue size: ", q.size())
if __name__ == '__main__':
main() | class Queue:
"""
Constructor. Initializes the list items
"""
def __init__(self):
self.items = []
'\n Returns true if queue is empty, false otherwise\n '
def is_empty(self):
return self.items == []
'\n Enqueue: Add item to end (tail) of the queue\n '
def enqueue(self, item):
self.items.insert(0, item)
'\n Dequeue: Remove item from font of the queue\n '
def dequeue(self):
return self.items.pop()
'\n Returns queue size\n '
def size(self):
return len(self.items)
def main():
q = queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print('Queue size: ', q.size())
if __name__ == '__main__':
main() |
filename = 'programing.txt'
with open(filename, 'a') as f:
f.write('I also like data science\n')
f.write('I\'m James Noria.\n') #add new things
| filename = 'programing.txt'
with open(filename, 'a') as f:
f.write('I also like data science\n')
f.write("I'm James Noria.\n") |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = ""
services_str = "/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/RestartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceMargin.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetCompliancePunch.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceSlope.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetSpeed.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetTorqueLimit.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StopController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/TorqueEnable.srv"
pkg_name = "dynamixel_controllers"
dependencies_str = ""
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = ""
PYTHON_EXECUTABLE = "/usr/bin/python2"
package_has_static_sources = 'TRUE' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| messages_str = ''
services_str = '/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/RestartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceMargin.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetCompliancePunch.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceSlope.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetSpeed.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetTorqueLimit.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StopController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/TorqueEnable.srv'
pkg_name = 'dynamixel_controllers'
dependencies_str = ''
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = ''
python_executable = '/usr/bin/python2'
package_has_static_sources = 'TRUE' == 'TRUE'
genmsg_check_deps_script = '/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py' |
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --#
def is_divisible_by(n, numbers):
if not numbers or 0 in numbers:
raise ValueError
for num in numbers:
if n % num != 0:
return False
return True
#-- THIS LINE SHOULD BE THE LAST LINE OF YOUR SUBMISSION! ---#
### DO NOT SUBMIT THE FOLLOWING LINES!!! THESE ARE FOR LOCAL TESTING ONLY!
assert(is_divisible_by(30, [3, 6, 15]))
assert(not is_divisible_by(30, [3, 6, 29]))
try:
is_divisible_by(30, [0, 6, 29])
assert(False) # expected an exception!
except ValueError:
print( "Well Done") # the correct exception was thrown | def is_divisible_by(n, numbers):
if not numbers or 0 in numbers:
raise ValueError
for num in numbers:
if n % num != 0:
return False
return True
assert is_divisible_by(30, [3, 6, 15])
assert not is_divisible_by(30, [3, 6, 29])
try:
is_divisible_by(30, [0, 6, 29])
assert False
except ValueError:
print('Well Done') |
registry_repositories = [
{
"registry_name": "resoto-do-plugin-test",
"name": "hw",
"tag_count": 1,
"manifest_count": 1,
"latest_manifest": {
"digest": "sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e",
"registry_name": "resoto-do-plugin-test",
"repository": "hw",
"compressed_size_bytes": 5164,
"size_bytes": 12660,
"updated_at": "2022-03-14T13:32:34Z",
"tags": ["latest"],
"blobs": [
{
"digest": "sha256:18e5af7904737ba5ef7fbbd7d59de5ebe6c4437907bd7fc436bf9b3ef3149ea9",
"compressed_size_bytes": 1483,
},
{
"digest": "sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e",
"compressed_size_bytes": 425,
},
{
"digest": "sha256:9523dd148d42344dc126560861fcb71ff901964cd4c15575f9d9cefe389cd818",
"compressed_size_bytes": 3256,
},
],
},
}
]
| registry_repositories = [{'registry_name': 'resoto-do-plugin-test', 'name': 'hw', 'tag_count': 1, 'manifest_count': 1, 'latest_manifest': {'digest': 'sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e', 'registry_name': 'resoto-do-plugin-test', 'repository': 'hw', 'compressed_size_bytes': 5164, 'size_bytes': 12660, 'updated_at': '2022-03-14T13:32:34Z', 'tags': ['latest'], 'blobs': [{'digest': 'sha256:18e5af7904737ba5ef7fbbd7d59de5ebe6c4437907bd7fc436bf9b3ef3149ea9', 'compressed_size_bytes': 1483}, {'digest': 'sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e', 'compressed_size_bytes': 425}, {'digest': 'sha256:9523dd148d42344dc126560861fcb71ff901964cd4c15575f9d9cefe389cd818', 'compressed_size_bytes': 3256}]}}] |
def OnEditApart(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if s1 in s2 or s2 in s1:
return True
mismatch = 0
for i in range(len(s1)):
if s1[i]!=s2[i]:
mismatch+=1
if mismatch > 1:
return False
return True
| def on_edit_apart(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if s1 in s2 or s2 in s1:
return True
mismatch = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
mismatch += 1
if mismatch > 1:
return False
return True |
S = list(map(str, input()))
if '7' in S:
print('Yes')
else:
print('No') | s = list(map(str, input()))
if '7' in S:
print('Yes')
else:
print('No') |
# python3
class JobQueue:
def read_data(self):
self.num_workers, m = map(int, input().split())
self.array = [[0]*2 for i in range(self.num_workers)]
self.jobs = list(map(int, input().split()))
assert m == len(self.jobs)
self.workers = [None] * len(self.jobs)
self.start = [0] * len(self.jobs)
def initialize(self):
worker = 0
for i in range(min(self.num_workers,len(self.jobs))):
self.array[i] = [self.jobs[i],i]
self.workers[i] = worker
worker+=1
self.start[i] = 0
for i in range(self.num_workers//2, -1,-1):
self.swapdown(i)
def write_response(self):
for i in range(len(self.jobs)):
print(self.workers[i], self.start[i])
def swapdown(self,i):
min_index = i
l = 2*i+1 if (2*i+1<self.num_workers) else -1
r = 2*i+2 if (2*i+2<self.num_workers) else -1
if (l != -1) and ((self.array[l][0] < self.array[min_index][0]) or ((self.array[l][0] == self.array[min_index][0]) and self.array[l][1] < self.array[min_index][1] )):
min_index = l
if (r != -1) and ((self.array[r][0] < self.array[min_index][0]) or ((self.array[r][0] == self.array[min_index][0]) and (self.array[r][1] < self.array[min_index][1]))):
min_index = r
if i != min_index:
self.array[i], self.array[min_index] = \
self.array[min_index], self.array[i]
self.swapdown(min_index)
def sorttheheap(self):
for i in range(self.num_workers//2, -1,-1):
self.swapdown(i)
def assign_jobs(self):
self.initialize()
lasttime = 0
if len(self.jobs)>self.num_workers:
for i in range(self.num_workers,len(self.jobs)):
# print(1,self.array)
self.swapdown(0) #don't need to sort here only swapping would do
# print(2,self.array)
lasttime =self.array[0][0]
# if self.array[0][0]!=self.array[1][0]:
self.workers[i] = self.array[0][1]
self.start[i] = lasttime
# elif self.array[0][0] ==self.array[1][0]:
# temp=0
# print(self.array)
self.array[0][0] += self.jobs[i]
def solve(self):
self.read_data()
self.assign_jobs()
self.write_response()
if __name__ == '__main__':
job_queue = JobQueue()
job_queue.solve() | class Jobqueue:
def read_data(self):
(self.num_workers, m) = map(int, input().split())
self.array = [[0] * 2 for i in range(self.num_workers)]
self.jobs = list(map(int, input().split()))
assert m == len(self.jobs)
self.workers = [None] * len(self.jobs)
self.start = [0] * len(self.jobs)
def initialize(self):
worker = 0
for i in range(min(self.num_workers, len(self.jobs))):
self.array[i] = [self.jobs[i], i]
self.workers[i] = worker
worker += 1
self.start[i] = 0
for i in range(self.num_workers // 2, -1, -1):
self.swapdown(i)
def write_response(self):
for i in range(len(self.jobs)):
print(self.workers[i], self.start[i])
def swapdown(self, i):
min_index = i
l = 2 * i + 1 if 2 * i + 1 < self.num_workers else -1
r = 2 * i + 2 if 2 * i + 2 < self.num_workers else -1
if l != -1 and (self.array[l][0] < self.array[min_index][0] or (self.array[l][0] == self.array[min_index][0] and self.array[l][1] < self.array[min_index][1])):
min_index = l
if r != -1 and (self.array[r][0] < self.array[min_index][0] or (self.array[r][0] == self.array[min_index][0] and self.array[r][1] < self.array[min_index][1])):
min_index = r
if i != min_index:
(self.array[i], self.array[min_index]) = (self.array[min_index], self.array[i])
self.swapdown(min_index)
def sorttheheap(self):
for i in range(self.num_workers // 2, -1, -1):
self.swapdown(i)
def assign_jobs(self):
self.initialize()
lasttime = 0
if len(self.jobs) > self.num_workers:
for i in range(self.num_workers, len(self.jobs)):
self.swapdown(0)
lasttime = self.array[0][0]
self.workers[i] = self.array[0][1]
self.start[i] = lasttime
self.array[0][0] += self.jobs[i]
def solve(self):
self.read_data()
self.assign_jobs()
self.write_response()
if __name__ == '__main__':
job_queue = job_queue()
job_queue.solve() |
# https://leetcode.com/problems/queue-reconstruction-by-height
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
| class Solution:
def reconstruct_queue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output |
# Have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174.
def kaprekars_constant(str):
# code goes here
return str
| def kaprekars_constant(str):
return str |
try:
f = open("textfile", "r")
f.write("write a TEST LINE ")
except TypeError:
print("There was a type error")
except OSError:
print("Hey you have an OS error")
except:
print("All other exception")
finally:
print("I always run") | try:
f = open('textfile', 'r')
f.write('write a TEST LINE ')
except TypeError:
print('There was a type error')
except OSError:
print('Hey you have an OS error')
except:
print('All other exception')
finally:
print('I always run') |
def selectionSort(alist):
for slot in range(len(alist) - 1, 0, -1):
iMax = 0
for index in range(1, slot + 1):
if alist[index] > alist[iMax]:
iMax = index
alist[slot], alist[iMax] = alist[iMax], alist[slot]
| def selection_sort(alist):
for slot in range(len(alist) - 1, 0, -1):
i_max = 0
for index in range(1, slot + 1):
if alist[index] > alist[iMax]:
i_max = index
(alist[slot], alist[iMax]) = (alist[iMax], alist[slot]) |
src = Glob('*.c')
component = aos_component('libid2', src)
component.add_global_includes('include')
component.add_comp_deps('security/plat_gen', 'security/libkm')
component.add_global_macros('CONFIG_AOS_SUPPORT=1')
component.add_prebuilt_libs('lib/' + component.get_arch() + '/libid2.a')
| src = glob('*.c')
component = aos_component('libid2', src)
component.add_global_includes('include')
component.add_comp_deps('security/plat_gen', 'security/libkm')
component.add_global_macros('CONFIG_AOS_SUPPORT=1')
component.add_prebuilt_libs('lib/' + component.get_arch() + '/libid2.a') |
my_list = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2;
def map(list_, f):
return [f(x) for x in list_]
def map_iter(list_, f):
new_list = []
for i in list_:
new_list.append(f(i))
return new_list
| my_list = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2
def map(list_, f):
return [f(x) for x in list_]
def map_iter(list_, f):
new_list = []
for i in list_:
new_list.append(f(i))
return new_list |
# https://www.codewars.com/kata/returning-strings/train/python
# My solution
def greet(name):
return "Hello, %s how are you doing today?" % name
# ...
def greet(name):
return f'Hello, {name} how are you doing today?'
# ...
def greet(name):
return "Hello, {} how are you doing today?".format(name)
| def greet(name):
return 'Hello, %s how are you doing today?' % name
def greet(name):
return f'Hello, {name} how are you doing today?'
def greet(name):
return 'Hello, {} how are you doing today?'.format(name) |
def envelopeHiBounds(valueList, wnd):
return envelopeBounds(valueList, wnd, 0.025)
def envelopeLoBounds(valueList, wnd):
return envelopeBounds(valueList, wnd, 0.025)
def envelopeBounds(valueList, wnd, ratio):
return valueList.ewm(wnd).mean() * (1 + ratio)
| def envelope_hi_bounds(valueList, wnd):
return envelope_bounds(valueList, wnd, 0.025)
def envelope_lo_bounds(valueList, wnd):
return envelope_bounds(valueList, wnd, 0.025)
def envelope_bounds(valueList, wnd, ratio):
return valueList.ewm(wnd).mean() * (1 + ratio) |
# test lists
assert 3 in [1, 2, 3]
assert 3 not in [1, 2]
assert not (3 in [1, 2])
assert not (3 not in [1, 2, 3])
# test strings
assert "foo" in "foobar"
assert "whatever" not in "foobar"
# test bytes
# TODO: uncomment this when bytes are implemented
# assert b"foo" in b"foobar"
# assert b"whatever" not in b"foobar"
assert b"1" < b"2"
assert b"1" <= b"2"
assert b"5" <= b"5"
assert b"4" > b"2"
assert not b"1" >= b"2"
assert b"10" >= b"10"
try:
bytes() > 2
except TypeError:
pass
else:
assert False, "TypeError not raised"
# test tuple
assert 1 in (1, 2)
assert 3 not in (1, 2)
# test set
assert 1 in set([1, 2])
assert 3 not in set([1, 2])
# test dicts
# TODO: test dicts when keys other than strings will be allowed
assert "a" in {"a": 0, "b": 0}
assert "c" not in {"a": 0, "b": 0}
# test iter
assert 3 in iter([1, 2, 3])
assert 3 not in iter([1, 2])
# test sequence
# TODO: uncomment this when ranges are usable
# assert 1 in range(0, 2)
# assert 3 not in range(0, 2)
# test __contains__ in user objects
class MyNotContainingClass():
pass
try:
1 in MyNotContainingClass()
except TypeError:
pass
else:
assert False, "TypeError not raised"
class MyContainingClass():
def __init__(self, value):
self.value = value
def __contains__(self, something):
return something == self.value
assert 2 in MyContainingClass(2)
assert 1 not in MyContainingClass(2)
| assert 3 in [1, 2, 3]
assert 3 not in [1, 2]
assert not 3 in [1, 2]
assert not 3 not in [1, 2, 3]
assert 'foo' in 'foobar'
assert 'whatever' not in 'foobar'
assert b'1' < b'2'
assert b'1' <= b'2'
assert b'5' <= b'5'
assert b'4' > b'2'
assert not b'1' >= b'2'
assert b'10' >= b'10'
try:
bytes() > 2
except TypeError:
pass
else:
assert False, 'TypeError not raised'
assert 1 in (1, 2)
assert 3 not in (1, 2)
assert 1 in set([1, 2])
assert 3 not in set([1, 2])
assert 'a' in {'a': 0, 'b': 0}
assert 'c' not in {'a': 0, 'b': 0}
assert 3 in iter([1, 2, 3])
assert 3 not in iter([1, 2])
class Mynotcontainingclass:
pass
try:
1 in my_not_containing_class()
except TypeError:
pass
else:
assert False, 'TypeError not raised'
class Mycontainingclass:
def __init__(self, value):
self.value = value
def __contains__(self, something):
return something == self.value
assert 2 in my_containing_class(2)
assert 1 not in my_containing_class(2) |
# coding=utf-8
__author__ = 'mlaptev'
if __name__ == "__main__":
matrix = []
line = input()
while line != 'end':
matrix.append([int(i) for i in line.split()])
line = input()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i-1][j] + matrix[(i+1)%len(matrix)][j] + matrix[i][j-1] + matrix[i][(j+1)%len(matrix[i])],
end=' ')
print()
| __author__ = 'mlaptev'
if __name__ == '__main__':
matrix = []
line = input()
while line != 'end':
matrix.append([int(i) for i in line.split()])
line = input()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i - 1][j] + matrix[(i + 1) % len(matrix)][j] + matrix[i][j - 1] + matrix[i][(j + 1) % len(matrix[i])], end=' ')
print() |
def nonstring_iterable(obj):
try: iter(obj)
except TypeError: return False
else: return not isinstance(obj, basestring)
| def nonstring_iterable(obj):
try:
iter(obj)
except TypeError:
return False
else:
return not isinstance(obj, basestring) |
# If the list grows large, it might be worth using a dictionary
isps = ('gmail.', 'yahoo.', 'earthlink.', 'comcast.', 'att.', 'movistar.', 'hotmail.', 'mail.', 'googlemail.',
'msn.', 'bellsouth.', 'telus.', 'optusnet.', 'qq.', 'sky.', 'icloud.', 'mac.', 'sympatico.',
'xtra.', 'web.', 'cox.', 'ymail.', 'aim.', 'rogers.', 'verizon.', 'rocketmail.', 'google.', 'optonline.',
'sbcglobal.', 'aol.', 'me.', 'btinternet.', 'charter.', 'shaw.')
def is_isp_domain(domain):
'Return True if the domain is a known ISP; False otherwise.'
for isp in isps:
if domain.startswith(isp):
return True
return False
def is_isp_email(email):
'Return True if the domain for this email is a known ISP; False otherwise.'
domain = email.split('@')[1]
return is_isp_domain(domain)
| isps = ('gmail.', 'yahoo.', 'earthlink.', 'comcast.', 'att.', 'movistar.', 'hotmail.', 'mail.', 'googlemail.', 'msn.', 'bellsouth.', 'telus.', 'optusnet.', 'qq.', 'sky.', 'icloud.', 'mac.', 'sympatico.', 'xtra.', 'web.', 'cox.', 'ymail.', 'aim.', 'rogers.', 'verizon.', 'rocketmail.', 'google.', 'optonline.', 'sbcglobal.', 'aol.', 'me.', 'btinternet.', 'charter.', 'shaw.')
def is_isp_domain(domain):
"""Return True if the domain is a known ISP; False otherwise."""
for isp in isps:
if domain.startswith(isp):
return True
return False
def is_isp_email(email):
"""Return True if the domain for this email is a known ISP; False otherwise."""
domain = email.split('@')[1]
return is_isp_domain(domain) |
class Solution:
def isPalindrome(self, s: str) -> bool:
l1 = ord('a')
r1 = ord('z')
l2 = ord('A')
r2 = ord('Z')
l3 = ord('0')
r3 = ord('9')
diff = ord('a') - ord('A')
seq = [
chr(ord(ch) - diff) if l1 <= ord(ch) <= r1 else ch
for ch in s
if l1 <= ord(ch) <= r1
or l2 <= ord(ch) <= r2
or l3 <= ord(ch) <= r3
]
return seq == seq[::-1] | class Solution:
def is_palindrome(self, s: str) -> bool:
l1 = ord('a')
r1 = ord('z')
l2 = ord('A')
r2 = ord('Z')
l3 = ord('0')
r3 = ord('9')
diff = ord('a') - ord('A')
seq = [chr(ord(ch) - diff) if l1 <= ord(ch) <= r1 else ch for ch in s if l1 <= ord(ch) <= r1 or l2 <= ord(ch) <= r2 or l3 <= ord(ch) <= r3]
return seq == seq[::-1] |
# -*- coding: utf-8 -*-
__author__ = 'Audrey Roy Greenfeld'
__email__ = 'aroy@alum.mit.edu'
__version__ = '0.1.0'
| __author__ = 'Audrey Roy Greenfeld'
__email__ = 'aroy@alum.mit.edu'
__version__ = '0.1.0' |
def number_of_divisors(divisor: int) -> int:
global requests
global divisors
if divisor in divisors:
return divisors[divisor]
requests.add(divisor)
count = 2
for i in range(2, int(divisor**0.5) + 1):
if not (divisor % i):
count += 2
divisors[divisor] = count
return count
if __name__ == "__main__":
requests = set()
divisors = {}
print(number_of_divisors(2000000000))
print(number_of_divisors(6))
print(number_of_divisors(6))
print(number_of_divisors(2000000000))
print(divisors)
| def number_of_divisors(divisor: int) -> int:
global requests
global divisors
if divisor in divisors:
return divisors[divisor]
requests.add(divisor)
count = 2
for i in range(2, int(divisor ** 0.5) + 1):
if not divisor % i:
count += 2
divisors[divisor] = count
return count
if __name__ == '__main__':
requests = set()
divisors = {}
print(number_of_divisors(2000000000))
print(number_of_divisors(6))
print(number_of_divisors(6))
print(number_of_divisors(2000000000))
print(divisors) |
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
totalRemain = 0
remainFromStart = 0
start = None
for i in range(len(gas)):
remain = gas[i] - cost[i] # remain when cross the station
remainFromStart += remain
if remainFromStart < 0:
start = None
remainFromStart = 0
elif start is None:
start = i
totalRemain += remain
return start if totalRemain >= 0 else -1 | class Solution:
def can_complete_circuit(self, gas: List[int], cost: List[int]) -> int:
total_remain = 0
remain_from_start = 0
start = None
for i in range(len(gas)):
remain = gas[i] - cost[i]
remain_from_start += remain
if remainFromStart < 0:
start = None
remain_from_start = 0
elif start is None:
start = i
total_remain += remain
return start if totalRemain >= 0 else -1 |
# Membaca file hello.txt dengan fungsi readlines()
print(">>> Membaca file hello.txt dengan fungsi readlines()")
file = open("hello.txt", "r")
all_lines = file.readlines()
file.close()
print(all_lines)
# Membaca file hello.txt dengan menerapkan looping
print(">>> Membaca file hello.txt dengan menerapkan looping")
file = open("hello.txt", "r")
for line in file:
print(line)
file.close() | print('>>> Membaca file hello.txt dengan fungsi readlines()')
file = open('hello.txt', 'r')
all_lines = file.readlines()
file.close()
print(all_lines)
print('>>> Membaca file hello.txt dengan menerapkan looping')
file = open('hello.txt', 'r')
for line in file:
print(line)
file.close() |
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def get_person(self):
return '<Person ({0}, {1})'.format(self.name, self.age)
p = Person('Manuel', 21)
print('Type of Object: {0}, Memory Address: {1}'.format(type(p), id(p))) | class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def get_person(self):
return '<Person ({0}, {1})'.format(self.name, self.age)
p = person('Manuel', 21)
print('Type of Object: {0}, Memory Address: {1}'.format(type(p), id(p))) |
class Solution:
def countAndSay(self, n: int) -> str:
say = '1'
while n > 1 :
n -= 1
temp = say
tag = temp[0]
count = 1
say = ''
for j in range(1, len(temp)):
if temp[j] == tag:
count += 1
else:
say += str(count) + tag
tag = temp[j]
count = 1
say += str(count) + tag
return say | class Solution:
def count_and_say(self, n: int) -> str:
say = '1'
while n > 1:
n -= 1
temp = say
tag = temp[0]
count = 1
say = ''
for j in range(1, len(temp)):
if temp[j] == tag:
count += 1
else:
say += str(count) + tag
tag = temp[j]
count = 1
say += str(count) + tag
return say |
# v1
# can only buy then sell once
def max_profit_1(prices):
if not prices: return 0
low = prices[0] # lowest price so far
profit = 0
for price in prices:
if low >= price:
low = price
else:
profit = max(profit, price - low)
return profit
# O(n) time and space
# v3
# can only buy then sell twice
# brute force: find the max profit of prices[:i] then the max profit of prices[i:]
# optimization: use an array to record the max profit of prices[:i] for each i
# and another array to record the max profit of prices[i:] for each i (DP)
def max_profit_3(prices):
if not prices:
return 0
profits = [0] * len(prices)
# max profit of prices[:i] for each i
max_profit_left = 0
min_price = prices[0]
for i in range(1, len(prices)):
min_price = min(min_price, prices[i])
max_profit_left = max(max_profit_left, prices[i] - min_price)
profits[i] = max_profit_left
# max profit of prices[i:] for each i
max_profit_right = 0
max_price = prices[-1]
for i in range(len(prices) - 1, 0, -1):
max_price = max(max_price, prices[i])
max_profit_right = max(max_profit_right, max_price - prices[i])
profits[i] += max_profit_right
return max(profits)
# O(n) time and space
# v4
# can only buy then sell for k times
#
# with cooldown (cannot buy after the day sold)
# assume all prices are non-negative
def max_profit_cooldown(prices):
'''
1) state definition
hold[i]: max profit when holding a position on day i
unhold[i]: max profit not holding a position on day i
2) base cases:
hold[0] = -prices[0]
hold[1] = max(-prices[0], -prices[1])
unhold[0] = 0
unhold[1] = max(0, hold[0] + prices[1])
3) state transfer function:
hold[i] = max(hold[i-1], # not buying on day i
unhold[i-2] - prices[i]) # buying on day i
unhold[i] = max(unhold[i-1], # no position on day i-1
hold[i-1] + prices[i]) # hold a position on dy i-1 and sell on day i
'''
if not prices or len(prices) < 2:
return 0
hold = [0] * len(prices)
unhold = [0] * len(prices)
hold[0] = -prices[0]
hold[1] = max(-prices[0], - prices[1])
unhold[1] = max(0, hold[0] + prices[1])
for i in range(2, len(prices)):
hold[i] = max(hold[i-1], unhold[i-2] - prices[i])
unhold[i] = max(unhold[i-1], hold[i-1] + prices[i])
return unhold[-1]
# O(3 ^ n) for brute force
# O(n) time and space
# space can be optimized to O(1)
| def max_profit_1(prices):
if not prices:
return 0
low = prices[0]
profit = 0
for price in prices:
if low >= price:
low = price
else:
profit = max(profit, price - low)
return profit
def max_profit_3(prices):
if not prices:
return 0
profits = [0] * len(prices)
max_profit_left = 0
min_price = prices[0]
for i in range(1, len(prices)):
min_price = min(min_price, prices[i])
max_profit_left = max(max_profit_left, prices[i] - min_price)
profits[i] = max_profit_left
max_profit_right = 0
max_price = prices[-1]
for i in range(len(prices) - 1, 0, -1):
max_price = max(max_price, prices[i])
max_profit_right = max(max_profit_right, max_price - prices[i])
profits[i] += max_profit_right
return max(profits)
def max_profit_cooldown(prices):
"""
1) state definition
hold[i]: max profit when holding a position on day i
unhold[i]: max profit not holding a position on day i
2) base cases:
hold[0] = -prices[0]
hold[1] = max(-prices[0], -prices[1])
unhold[0] = 0
unhold[1] = max(0, hold[0] + prices[1])
3) state transfer function:
hold[i] = max(hold[i-1], # not buying on day i
unhold[i-2] - prices[i]) # buying on day i
unhold[i] = max(unhold[i-1], # no position on day i-1
hold[i-1] + prices[i]) # hold a position on dy i-1 and sell on day i
"""
if not prices or len(prices) < 2:
return 0
hold = [0] * len(prices)
unhold = [0] * len(prices)
hold[0] = -prices[0]
hold[1] = max(-prices[0], -prices[1])
unhold[1] = max(0, hold[0] + prices[1])
for i in range(2, len(prices)):
hold[i] = max(hold[i - 1], unhold[i - 2] - prices[i])
unhold[i] = max(unhold[i - 1], hold[i - 1] + prices[i])
return unhold[-1] |
def preorderTraversal(root):
if root is None:
return []
nodes = []
def visit(node, nodes):
if node is None:
return
nodes.append(node.val)
visit(node.left, nodes)
visit(node.right, nodes)
visit(root, nodes)
return nodes
| def preorder_traversal(root):
if root is None:
return []
nodes = []
def visit(node, nodes):
if node is None:
return
nodes.append(node.val)
visit(node.left, nodes)
visit(node.right, nodes)
visit(root, nodes)
return nodes |
def encrypt(input, key):
encrypted = []
for i in range(0, len(input)):
a = ord(input[i])
for j in range (0, key):
a = a + 1
if (a>122):
a = 97
encrypted.append(chr(a))
return "".join(encrypted)
def decrypt(input, key):
decrypted = []
for i in range(0, len(input)):
a = ord(input[i])
for o in range (0, key):
a = a - 1
if (a<97):
a = 122
decrypted.append(chr(a))
return "".join(decrypted)
def main():
try:
print("Press 1 to Encrypt")
print("Press 2 to Decrypt")
choice = input("Choice: ")
if choice == '1':
print("Enter the Key")
key = int(input("Key: "))
print("Enter PlainText")
plainText = input("Plain Text: ")
print("Encrypted Text is : ", encrypt(plainText, key))
if choice == '2':
print("Enter the Key")
key = int(input("Key: "))
print("Enter CipherText")
cipherText = input("Cipher Text: ")
print("Encrypted Text is : ", decrypt(cipherText, key))
except Exception as e:
print(e)
if __name__ == '__main__':
main() | def encrypt(input, key):
encrypted = []
for i in range(0, len(input)):
a = ord(input[i])
for j in range(0, key):
a = a + 1
if a > 122:
a = 97
encrypted.append(chr(a))
return ''.join(encrypted)
def decrypt(input, key):
decrypted = []
for i in range(0, len(input)):
a = ord(input[i])
for o in range(0, key):
a = a - 1
if a < 97:
a = 122
decrypted.append(chr(a))
return ''.join(decrypted)
def main():
try:
print('Press 1 to Encrypt')
print('Press 2 to Decrypt')
choice = input('Choice: ')
if choice == '1':
print('Enter the Key')
key = int(input('Key: '))
print('Enter PlainText')
plain_text = input('Plain Text: ')
print('Encrypted Text is : ', encrypt(plainText, key))
if choice == '2':
print('Enter the Key')
key = int(input('Key: '))
print('Enter CipherText')
cipher_text = input('Cipher Text: ')
print('Encrypted Text is : ', decrypt(cipherText, key))
except Exception as e:
print(e)
if __name__ == '__main__':
main() |
number_of_input_bits = 1
mux_x = 0.002 # in m
mux_y = 0.0012 # in m
for i in range(number_of_input_bits):
positionx = 0.0 + mux_x * i
line = "Mux1" + str(i) + "\t" + str(mux_x) + "\t" + str(mux_y) + "\t"
line += str(round(positionx, 8)) + "\t"
positiony = 0.0
line += str(round(positiony, 8))
print(line)
line = "Mux0" + str(i) + "\t" + str(mux_x) + "\t" + str(mux_y) + "\t"
line += str(round(positionx, 8)) + "\t"
positiony = mux_y
line += str(round(positiony, 8))
print(line)
print("flip\t0.01\t0.013\t" + str(number_of_input_bits * mux_x) + "\t0.0")
| number_of_input_bits = 1
mux_x = 0.002
mux_y = 0.0012
for i in range(number_of_input_bits):
positionx = 0.0 + mux_x * i
line = 'Mux1' + str(i) + '\t' + str(mux_x) + '\t' + str(mux_y) + '\t'
line += str(round(positionx, 8)) + '\t'
positiony = 0.0
line += str(round(positiony, 8))
print(line)
line = 'Mux0' + str(i) + '\t' + str(mux_x) + '\t' + str(mux_y) + '\t'
line += str(round(positionx, 8)) + '\t'
positiony = mux_y
line += str(round(positiony, 8))
print(line)
print('flip\t0.01\t0.013\t' + str(number_of_input_bits * mux_x) + '\t0.0') |
k,s=map(int,input().split())
x=list(input())
for i in range(s):
if x[i].isalpha() and x[i].isupper():
print(chr(ord('A')+(ord(x[i])-ord('A')+k)%26),end='')
elif x[i].isalpha():
print(chr(ord('a')+(ord(x[i])-ord('a')+k)%26),end='')
else:
print(x[i],end='') | (k, s) = map(int, input().split())
x = list(input())
for i in range(s):
if x[i].isalpha() and x[i].isupper():
print(chr(ord('A') + (ord(x[i]) - ord('A') + k) % 26), end='')
elif x[i].isalpha():
print(chr(ord('a') + (ord(x[i]) - ord('a') + k) % 26), end='')
else:
print(x[i], end='') |
def reverse(string):
string = "".join(reversed(string)) #used reversed function for reversing the String
return string
str = input("Enter A String:")
print ("The Entered String is : ",end="") #end is used here so that output will be in same line.
print (str)
print ("The Reversed String is : ",end="")
print (reverse(str))
| def reverse(string):
string = ''.join(reversed(string))
return string
str = input('Enter A String:')
print('The Entered String is : ', end='')
print(str)
print('The Reversed String is : ', end='')
print(reverse(str)) |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = {}
for idx in range(len(nums)):
currentNum = nums[idx]
difference = target-currentNum
if difference not in hashMap and currentNum not in hashMap:
hashMap[difference] = idx
else:
return [hashMap[currentNum], idx]
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
hash_map = {}
for idx in range(len(nums)):
current_num = nums[idx]
difference = target - currentNum
if difference not in hashMap and currentNum not in hashMap:
hashMap[difference] = idx
else:
return [hashMap[currentNum], idx] |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'My Farm',
'version' : '1.1',
'category': 'Services',
'installable': True,
'application': True,
'depends': ['project'],
'data': [
'data/res.country.state.csv',
'data/seq.xml',
'security/ir.model.access.csv',
'views/farm_configuration_farm_locations.xml',
'views/farm_configuration_fleets.xml',
'views/farm_configuration_farmers.xml',
'views/farm_configuration_farm_locations_detail.xml',
'views/farm_configuration_stages.xml',
'views/farm_crops.xml',
'views/farm_dieases_cure.xml',
'views/farm_incidents.xml',
'views/farm_projects.xml',
'views/farm_crop_process.xml',
'views/farm_crop_requests.xml',
'views/farm_menu.xml',
],
'asset': {
'web.assets_backend': [
'farm/static/src/**/*'
]
},
'license': 'LGPL-3'
} | {'name': 'My Farm', 'version': '1.1', 'category': 'Services', 'installable': True, 'application': True, 'depends': ['project'], 'data': ['data/res.country.state.csv', 'data/seq.xml', 'security/ir.model.access.csv', 'views/farm_configuration_farm_locations.xml', 'views/farm_configuration_fleets.xml', 'views/farm_configuration_farmers.xml', 'views/farm_configuration_farm_locations_detail.xml', 'views/farm_configuration_stages.xml', 'views/farm_crops.xml', 'views/farm_dieases_cure.xml', 'views/farm_incidents.xml', 'views/farm_projects.xml', 'views/farm_crop_process.xml', 'views/farm_crop_requests.xml', 'views/farm_menu.xml'], 'asset': {'web.assets_backend': ['farm/static/src/**/*']}, 'license': 'LGPL-3'} |
i = 2
S = 1
while i <= 100:
S = S + (1 / i)
i += 1
print('{:.2f}'.format(S)) | i = 2
s = 1
while i <= 100:
s = S + 1 / i
i += 1
print('{:.2f}'.format(S)) |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This is a dummy grpcio==1.35.0 package used for E2E
# testing in Azure Functions Python Worker.
__version__ = '1.35.0'
| __version__ = '1.35.0' |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
count = 0
arr.sort ( )
for i in range ( 0 , n - 1 ) :
if ( arr [ i ] != arr [ i + 1 ] and arr [ i ] != arr [ i + 1 ] - 1 ) :
count += arr [ i + 1 ] - arr [ i ] - 1 ;
return count
#TOFILL
if __name__ == '__main__':
param = [
([4, 4, 5, 7, 7, 9, 13, 15, 18, 19, 25, 27, 27, 29, 32, 36, 48, 51, 53, 53, 55, 65, 66, 67, 72, 74, 74, 76, 77, 79, 80, 81, 82, 83, 83, 86, 87, 97, 98, 98, 99],30,),
([34, 6, -16, -26, -80, -90, -74, 16, -84, 64, -8, 14, -52, -26, -90, -84, 94, 92, -88, -84, 72],17,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],24,),
([25, 29, 12, 79, 23, 92, 54, 43, 26, 10, 43, 39, 32, 12, 62, 13, 13],14,),
([-94, -86, -72, -64, -64, -58, -56, -56, -56, -56, -54, -54, -52, -42, -42, -40, -36, -32, -28, -22, -20, -18, -12, -8, -6, -4, 0, 2, 4, 10, 16, 30, 32, 48, 48, 60, 70, 74, 76, 84],35,),
([1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0],29,),
([4, 5, 8, 12, 16, 16, 17, 20, 20, 23, 26, 26, 27, 28, 32, 34, 40, 40, 41, 41, 44, 45, 47, 49, 51, 52, 54, 57, 60, 62, 63, 64, 66, 68, 69, 70, 71, 76, 77, 80, 80, 80, 90, 91, 92, 94, 96, 98, 99],42,),
([66, -46, -92, -40, 76, 74, 10, 20, 56, -46, 88, -18, 48, 96, -48, -86, 38, -98, 50, 4, -52, -38, 14, -48, 96, 16, -74, -26, 80, 14, -92, -60, -78, -68, 96, -72, -44, -92, 2, 60, 4, 48, 84, -92],37,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],17,),
([49, 84, 66],2,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) | def f_gold(arr, n):
count = 0
arr.sort()
for i in range(0, n - 1):
if arr[i] != arr[i + 1] and arr[i] != arr[i + 1] - 1:
count += arr[i + 1] - arr[i] - 1
return count
if __name__ == '__main__':
param = [([4, 4, 5, 7, 7, 9, 13, 15, 18, 19, 25, 27, 27, 29, 32, 36, 48, 51, 53, 53, 55, 65, 66, 67, 72, 74, 74, 76, 77, 79, 80, 81, 82, 83, 83, 86, 87, 97, 98, 98, 99], 30), ([34, 6, -16, -26, -80, -90, -74, 16, -84, 64, -8, 14, -52, -26, -90, -84, 94, 92, -88, -84, 72], 17), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 24), ([25, 29, 12, 79, 23, 92, 54, 43, 26, 10, 43, 39, 32, 12, 62, 13, 13], 14), ([-94, -86, -72, -64, -64, -58, -56, -56, -56, -56, -54, -54, -52, -42, -42, -40, -36, -32, -28, -22, -20, -18, -12, -8, -6, -4, 0, 2, 4, 10, 16, 30, 32, 48, 48, 60, 70, 74, 76, 84], 35), ([1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0], 29), ([4, 5, 8, 12, 16, 16, 17, 20, 20, 23, 26, 26, 27, 28, 32, 34, 40, 40, 41, 41, 44, 45, 47, 49, 51, 52, 54, 57, 60, 62, 63, 64, 66, 68, 69, 70, 71, 76, 77, 80, 80, 80, 90, 91, 92, 94, 96, 98, 99], 42), ([66, -46, -92, -40, 76, 74, 10, 20, 56, -46, 88, -18, 48, 96, -48, -86, 38, -98, 50, 4, -52, -38, 14, -48, 96, 16, -74, -26, 80, 14, -92, -60, -78, -68, 96, -72, -44, -92, 2, 60, 4, 48, 84, -92], 37), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 17), ([49, 84, 66], 2)]
n_success = 0
for (i, parameters_set) in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success += 1
print('#Results: %i, %i' % (n_success, len(param))) |
board = ["-","-","-","-","-","-","-","-","-"]
gamegoing = True
winner = None
current_player = "X"
def disp_board():
print(board[0]+ "|" + board[1] + "|" + board[2])
print(board[3]+ "|" + board[4] + "|" + board[5])
print(board[6]+ "|" + board[7] + "|" + board[8])
def play_game():
disp_board()
while gamegoing:
turn(current_player)
gameover()
flip()
if winner =="X" or winner =="0":
print(winner +" won.")
elif winner == None:
print("Tie.")
def turn(player):
pos = input(player + " Choose a position from 1-9: ")
valid = False
while not valid:
while pos not in ["1","2","3","4","5","6","7","8","9"]:
pos = input("Invalid input." + player + " Choose a position from 1-9: ")
pos = int(pos)-1
if board[pos] == "-":
valid = True
else:
print("You can't go there.")
board[pos] = player
disp_board()
def gameover():
checkwin()
checktie()
def checkwin():
global winner
rwin = checkrow()
cwin = checkcol()
dwin = checkdiag()
if rwin:
winner = rwin
elif cwin:
winner = cwin
elif dwin:
winner = dwin
else:
winner = None
def checkrow():
global gamegoing
row1 = board[0] == board[1] == board[2] != "-"
row2 = board[3] == board[4] == board[5] != "-"
row3 = board[6] == board[7] == board[8] != "-"
if row1 or row2 or row3:
gamegoing = False
if row1:
return board[0]
elif row2:
return board[3]
elif row3:
return board[6]
def checkcol():
global gamegoing
col1 = board[0] == board[3] == board[6] != "-"
col2 = board[1] == board[4] == board[7] != "-"
col3 = board[2] == board[5] == board[8] != "-"
if col1 or col2 or col3:
gamegoing = False
if col1:
return board[0]
elif col2:
return board[1]
elif col3:
return board[2]
def checkdiag():
global gamegoing
diag1 = board[0] == board[4] == board[8] != "-"
diag2 = board[2] == board[4] == board[6] != "-"
if diag1 or diag2:
gamegoing = False
if diag1:
return board[0]
elif diag2:
return board[2]
def checktie():
global gamegoing
if "-" not in board:
gamegoing = False
def flip():
global current_player
if current_player =="X":
current_player = "O"
elif current_player =="O":
current_player = "X"
play_game()
| board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
gamegoing = True
winner = None
current_player = 'X'
def disp_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
def play_game():
disp_board()
while gamegoing:
turn(current_player)
gameover()
flip()
if winner == 'X' or winner == '0':
print(winner + ' won.')
elif winner == None:
print('Tie.')
def turn(player):
pos = input(player + ' Choose a position from 1-9: ')
valid = False
while not valid:
while pos not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
pos = input('Invalid input.' + player + ' Choose a position from 1-9: ')
pos = int(pos) - 1
if board[pos] == '-':
valid = True
else:
print("You can't go there.")
board[pos] = player
disp_board()
def gameover():
checkwin()
checktie()
def checkwin():
global winner
rwin = checkrow()
cwin = checkcol()
dwin = checkdiag()
if rwin:
winner = rwin
elif cwin:
winner = cwin
elif dwin:
winner = dwin
else:
winner = None
def checkrow():
global gamegoing
row1 = board[0] == board[1] == board[2] != '-'
row2 = board[3] == board[4] == board[5] != '-'
row3 = board[6] == board[7] == board[8] != '-'
if row1 or row2 or row3:
gamegoing = False
if row1:
return board[0]
elif row2:
return board[3]
elif row3:
return board[6]
def checkcol():
global gamegoing
col1 = board[0] == board[3] == board[6] != '-'
col2 = board[1] == board[4] == board[7] != '-'
col3 = board[2] == board[5] == board[8] != '-'
if col1 or col2 or col3:
gamegoing = False
if col1:
return board[0]
elif col2:
return board[1]
elif col3:
return board[2]
def checkdiag():
global gamegoing
diag1 = board[0] == board[4] == board[8] != '-'
diag2 = board[2] == board[4] == board[6] != '-'
if diag1 or diag2:
gamegoing = False
if diag1:
return board[0]
elif diag2:
return board[2]
def checktie():
global gamegoing
if '-' not in board:
gamegoing = False
def flip():
global current_player
if current_player == 'X':
current_player = 'O'
elif current_player == 'O':
current_player = 'X'
play_game() |
'''
Created on Feb 9, 2018
@author: gongyo
'''
colors = ["red", 'yellow']
colors.append("black")
def compare(c1="str", c2="str"):
return c1 < c2
compare2 = lambda c1, c2: (c1 < c2);
colors.sort(cmp=compare2, key=None, reverse=False)
| """
Created on Feb 9, 2018
@author: gongyo
"""
colors = ['red', 'yellow']
colors.append('black')
def compare(c1='str', c2='str'):
return c1 < c2
compare2 = lambda c1, c2: c1 < c2
colors.sort(cmp=compare2, key=None, reverse=False) |
def extractCwastranslationsWordpressCom(item):
'''
Parser for 'cwastranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('tsifb', 'Transmigrated into a School Idol and Forced to Do Business', 'translated'),
('transmigrated into a school idol and forced to do business', 'Transmigrated into a School Idol and Forced to Do Business', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | def extract_cwastranslations_wordpress_com(item):
"""
Parser for 'cwastranslations.wordpress.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('tsifb', 'Transmigrated into a School Idol and Forced to Do Business', 'translated'), ('transmigrated into a school idol and forced to do business', 'Transmigrated into a School Idol and Forced to Do Business', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
# version scheme: (major, minor, micro, release_level)
#
# major:
# 0 .. not all planned features done
# 1 .. all features available
# 2 .. if significant API change (2, 3, ...)
#
# minor:
# changes with new features or minor API changes
#
# micro:
# changes with bug fixes, maybe also minor API changes
#
# release_state:
# a .. alpha: adding new features - non public development state
# b .. beta: testing new features - public development state
# rc .. release candidate: testing release - public testing
# release: public release
#
# examples:
# major pre release alpha 2: VERSION = "0.9a2"; version = (0, 9, 0, 'a2')
# major release candidate 0: VERSION = "0.9rc0"; version = (0, 9, 0, 'rc0')
# major release: VERSION = "0.9"; version = (0, 9, 0, 'release')
# 1. bug fix release beta0: VERSION = "0.9.1b0"; version = (0, 9, 1, 'b0')
# 2. bug fix release: VERSION = "0.9.2"; version = (0, 9, 2, 'release')
version = (0, 15, 2, 'b0')
__version__ = "0.15.2b0"
| version = (0, 15, 2, 'b0')
__version__ = '0.15.2b0' |
class UVMDefaultServer:
def __init__(self):
self.m_quit_count = 0
self.m_max_quit_count = 0
self.max_quit_overridable = True
self.m_severity_count = {}
self.m_id_count = {}
## uvm_tr_database m_message_db;
## uvm_tr_stream m_streams[string][string]; // ro.name,rh.name
| class Uvmdefaultserver:
def __init__(self):
self.m_quit_count = 0
self.m_max_quit_count = 0
self.max_quit_overridable = True
self.m_severity_count = {}
self.m_id_count = {} |
#Factorial of number
n = int(input("enter a number "))
f = 1
if (n < 0):
print("number is negative")
elif (n == 0):
print("factorial=",1)
else:
for i in range(1,n+1):
f = f * i
print("factorial =",f) | n = int(input('enter a number '))
f = 1
if n < 0:
print('number is negative')
elif n == 0:
print('factorial=', 1)
else:
for i in range(1, n + 1):
f = f * i
print('factorial =', f) |
# dimensions of our images.
img_width, img_height = 150, 150
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 5005
nb_validation_samples = 218
epochs = 1
batch_size = 16
| (img_width, img_height) = (150, 150)
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 5005
nb_validation_samples = 218
epochs = 1
batch_size = 16 |
# -*- coding: utf-8 -
__VERSION__ = (0, 4, 7)
__SERVER_NAME__ = 'lin/{}.{}.{}'.format(*__VERSION__)
| __version__ = (0, 4, 7)
__server_name__ = 'lin/{}.{}.{}'.format(*__VERSION__) |
f=open("./matrix.txt","r") #create the dictionary for the score
diz={}
matrix=[]
for line in f:
line=line.rstrip()
line=line.split()
matrix.append(line)
for i in range(len(matrix[0])):
for j in range(1,len(matrix)):
diz[matrix[0][i]+matrix[j][0]]=int(matrix[i+1][j])
mat=diz
seq1="ACACT"
seq2="AAT"
def score(s1,s2,S,d):
F=[]
trace_back=[]
m=len(s1)+1
n=len(s2)+1
F=[[0]*m for x in range(n)]
trace_back=[[0]*m for x in range(n)]
for i in range(len(F[0][:-1])):#initialize first row of the zero matrix with gaps (dall'inizio fino al penultimo)
F[0][i+1]=F[0][i]+d
trace_back[0][i+1]="L"
for i in range(len(F[:-1])):#initialize first column of the zero matrix with gaps (dall'inizio fino al penultimo)
F[i+1][0]=F[i][0]+d
trace_back[i+1][0]="U"
for i in range(1,n):#iteration based on the maximization of the value
for j in range(1,m):
diag=F[i-1][j-1]+S[s1[j-1]+s2[i-1]]#match
left=F[i][j-1]+d #gap in the second sequence
up=F[i-1][j]+d#gap in the first sequence
F[i][j]=max(diag,left,up)
#(2)crate trace back matrix
if F[i][j]==diag:
trace_back[i][j]="D"
elif F[i][j]==left:
trace_back[i][j]="L"
elif F[i][j]==up:
trace_back[i][j]="U"
al1=""
al2=""
c=""
j=len(s1)#5
i=len(s2)#4
while j>0 and i>0:
if trace_back[i][j]=="D":
al1+=s1[j-1]
al2+=s2[i-1]
j-=1
i-=1
elif trace_back[i][j]=="U":
al1+="-"
al2+=s2[i-1]
i-=1
elif trace_back[i][j]=="L":
al1+=s1[j-1]
al2+="-"
j-=1
al1=al1[::-1]
al2=al2[::-1]
for i in range(len(al1)):
if al1[i]=="-" or al2[i]=="-":
c+=" "
elif al1[i]==al2[i]:
c+="|"
elif al1[i]!=al2[i]:
c+="*"
return al1,al2,F[len(s2)][len(s1)],c,F
final_alignment=score(seq1,seq2,mat,-2)
print("The best alignment is:")
print(final_alignment[0])
print(final_alignment[4])
print(final_alignment[1])
print("The score of the alignment is: ",final_alignment[2])
| f = open('./matrix.txt', 'r')
diz = {}
matrix = []
for line in f:
line = line.rstrip()
line = line.split()
matrix.append(line)
for i in range(len(matrix[0])):
for j in range(1, len(matrix)):
diz[matrix[0][i] + matrix[j][0]] = int(matrix[i + 1][j])
mat = diz
seq1 = 'ACACT'
seq2 = 'AAT'
def score(s1, s2, S, d):
f = []
trace_back = []
m = len(s1) + 1
n = len(s2) + 1
f = [[0] * m for x in range(n)]
trace_back = [[0] * m for x in range(n)]
for i in range(len(F[0][:-1])):
F[0][i + 1] = F[0][i] + d
trace_back[0][i + 1] = 'L'
for i in range(len(F[:-1])):
F[i + 1][0] = F[i][0] + d
trace_back[i + 1][0] = 'U'
for i in range(1, n):
for j in range(1, m):
diag = F[i - 1][j - 1] + S[s1[j - 1] + s2[i - 1]]
left = F[i][j - 1] + d
up = F[i - 1][j] + d
F[i][j] = max(diag, left, up)
if F[i][j] == diag:
trace_back[i][j] = 'D'
elif F[i][j] == left:
trace_back[i][j] = 'L'
elif F[i][j] == up:
trace_back[i][j] = 'U'
al1 = ''
al2 = ''
c = ''
j = len(s1)
i = len(s2)
while j > 0 and i > 0:
if trace_back[i][j] == 'D':
al1 += s1[j - 1]
al2 += s2[i - 1]
j -= 1
i -= 1
elif trace_back[i][j] == 'U':
al1 += '-'
al2 += s2[i - 1]
i -= 1
elif trace_back[i][j] == 'L':
al1 += s1[j - 1]
al2 += '-'
j -= 1
al1 = al1[::-1]
al2 = al2[::-1]
for i in range(len(al1)):
if al1[i] == '-' or al2[i] == '-':
c += ' '
elif al1[i] == al2[i]:
c += '|'
elif al1[i] != al2[i]:
c += '*'
return (al1, al2, F[len(s2)][len(s1)], c, F)
final_alignment = score(seq1, seq2, mat, -2)
print('The best alignment is:')
print(final_alignment[0])
print(final_alignment[4])
print(final_alignment[1])
print('The score of the alignment is: ', final_alignment[2]) |
# Set this to your GitHub auth token
GitHubAuthToken = 'add_here_your_token'
# Set this to the path of the git executable
gitExecutablePath = 'git'
# Set this to true to download also private repos if the token has private repo rights
include_private_repos = False
# Set this to False to skip existing repos
update_existing_repos = True
# Set to 0 for no messages, 1 for simple messages, and 2 for progress bars
verbose = 1
# Select how to write to disk (or how to send queries to the database)
always_write_to_disk = True
# Change these settings to store data in disk/database
use_database = 'disk' # (available options: disk, mongo)
# Disk settings
dataFolderPath = 'data' # Set this to the folder where data are downloaded
# Database settings
database_host_and_port = "mongodb://localhost:27017/" # change this to the hostname and port of your database
num_bulk_operations = 1000 # set the number of operations that are sent as a bulk to the database
# Select what to download
download_issues = True
download_issue_comments = True
download_issue_events = True
download_commits = True
download_commit_comments = True
download_contributors = True
download_source_code = False
# Select whether the downloaded issues and commits information will be full
download_issues_full = True
download_commits_full = True
| git_hub_auth_token = 'add_here_your_token'
git_executable_path = 'git'
include_private_repos = False
update_existing_repos = True
verbose = 1
always_write_to_disk = True
use_database = 'disk'
data_folder_path = 'data'
database_host_and_port = 'mongodb://localhost:27017/'
num_bulk_operations = 1000
download_issues = True
download_issue_comments = True
download_issue_events = True
download_commits = True
download_commit_comments = True
download_contributors = True
download_source_code = False
download_issues_full = True
download_commits_full = True |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../../../build/common.gypi',
],
'variables': {
'irt_sources': [
# irt_support_sources
'irt_entry.c',
'irt_interfaces.c',
'irt_malloc.c',
'irt_private_pthread.c',
'irt_private_tls.c',
'irt_query_list.c',
# irt_common_interfaces
'irt_basic.c',
'irt_code_data_alloc.c',
'irt_fdio.c',
'irt_filename.c',
'irt_memory.c',
'irt_dyncode.c',
'irt_thread.c',
'irt_futex.c',
'irt_mutex.c',
'irt_cond.c',
'irt_sem.c',
'irt_tls.c',
'irt_blockhook.c',
'irt_clock.c',
'irt_dev_getpid.c',
'irt_exception_handling.c',
'irt_dev_list_mappings.c',
'irt_random.c',
# support_srcs
# We also get nc_init_private.c, nc_thread.c and nc_tsd.c via
# #includes of .c files.
'../pthread/nc_mutex.c',
'../pthread/nc_condvar.c',
'../nacl/sys_private.c',
'../valgrind/dynamic_annotations.c',
],
# On x86-64 we build the IRT with sandbox base-address hiding. This means that
# all of its components must be built with LLVM's assembler. Currently the
# unwinder library is built with nacl-gcc and so does not use base address
# hiding. The IRT does not use exceptions, so we do not actually need the
# unwinder at all. To prevent it from being linked into the IRT, we provide
# stub implementations of its functions that are referenced from libc++abi
# (which is build with exception handling enabled) and from crtbegin.c.
'stub_sources': [
'../../../pnacl/support/bitcode/unwind_stubs.c',
'frame_info_stubs.c',
],
'irt_nonbrowser': [
'irt_core_resource.c',
'irt_entry_core.c',
'irt_pnacl_translator_common.c',
'irt_pnacl_translator_compile.c',
'irt_pnacl_translator_link.c',
],
},
'targets': [
{
'target_name': 'irt_core_nexe',
'type': 'none',
'variables': {
'nexe_target': 'irt_core',
'build_glibc': 0,
'build_newlib': 0,
'build_irt': 1,
},
'sources': ['<@(irt_nonbrowser)'],
'link_flags': [
'-Wl,--start-group',
'-lirt_browser',
'-limc_syscalls',
'-lplatform',
'-lgio',
'-Wl,--end-group',
'-lm',
],
'dependencies': [
'irt_browser_lib',
'<(DEPTH)/native_client/src/shared/gio/gio.gyp:gio_lib',
'<(DEPTH)/native_client/src/shared/platform/platform.gyp:platform_lib',
'<(DEPTH)/native_client/src/tools/tls_edit/tls_edit.gyp:tls_edit#host',
'<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:imc_syscalls_lib',
'<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:nacl_lib_newlib',
],
},
{
'target_name': 'irt_browser_lib',
'type': 'none',
'variables': {
'nlib_target': 'libirt_browser.a',
'build_glibc': 0,
'build_newlib': 0,
'build_irt': 1,
},
'sources': ['<@(irt_sources)','<@(stub_sources)'],
'dependencies': [
'<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:nacl_lib_newlib',
],
},
],
}
| {'includes': ['../../../build/common.gypi'], 'variables': {'irt_sources': ['irt_entry.c', 'irt_interfaces.c', 'irt_malloc.c', 'irt_private_pthread.c', 'irt_private_tls.c', 'irt_query_list.c', 'irt_basic.c', 'irt_code_data_alloc.c', 'irt_fdio.c', 'irt_filename.c', 'irt_memory.c', 'irt_dyncode.c', 'irt_thread.c', 'irt_futex.c', 'irt_mutex.c', 'irt_cond.c', 'irt_sem.c', 'irt_tls.c', 'irt_blockhook.c', 'irt_clock.c', 'irt_dev_getpid.c', 'irt_exception_handling.c', 'irt_dev_list_mappings.c', 'irt_random.c', '../pthread/nc_mutex.c', '../pthread/nc_condvar.c', '../nacl/sys_private.c', '../valgrind/dynamic_annotations.c'], 'stub_sources': ['../../../pnacl/support/bitcode/unwind_stubs.c', 'frame_info_stubs.c'], 'irt_nonbrowser': ['irt_core_resource.c', 'irt_entry_core.c', 'irt_pnacl_translator_common.c', 'irt_pnacl_translator_compile.c', 'irt_pnacl_translator_link.c']}, 'targets': [{'target_name': 'irt_core_nexe', 'type': 'none', 'variables': {'nexe_target': 'irt_core', 'build_glibc': 0, 'build_newlib': 0, 'build_irt': 1}, 'sources': ['<@(irt_nonbrowser)'], 'link_flags': ['-Wl,--start-group', '-lirt_browser', '-limc_syscalls', '-lplatform', '-lgio', '-Wl,--end-group', '-lm'], 'dependencies': ['irt_browser_lib', '<(DEPTH)/native_client/src/shared/gio/gio.gyp:gio_lib', '<(DEPTH)/native_client/src/shared/platform/platform.gyp:platform_lib', '<(DEPTH)/native_client/src/tools/tls_edit/tls_edit.gyp:tls_edit#host', '<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:imc_syscalls_lib', '<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:nacl_lib_newlib']}, {'target_name': 'irt_browser_lib', 'type': 'none', 'variables': {'nlib_target': 'libirt_browser.a', 'build_glibc': 0, 'build_newlib': 0, 'build_irt': 1}, 'sources': ['<@(irt_sources)', '<@(stub_sources)'], 'dependencies': ['<(DEPTH)/native_client/src/untrusted/nacl/nacl.gyp:nacl_lib_newlib']}]} |
# b1 - bought stock once
# s1 - bought stock and then sold once
# b2 - bought stock the second time
# s2 - bought and sold twice
class Solution:
def maxProfit(self, prices: List[int]) -> int:
b1 = s1 = b2 = s2 = float('-inf')
for p in prices:
b1, s1, b2, s2 = max(b1, - p), max(s1, b1 + p), max(b2, s1 - p), max(s2, b2 + p)
return max(0, s1, s2) | class Solution:
def max_profit(self, prices: List[int]) -> int:
b1 = s1 = b2 = s2 = float('-inf')
for p in prices:
(b1, s1, b2, s2) = (max(b1, -p), max(s1, b1 + p), max(b2, s1 - p), max(s2, b2 + p))
return max(0, s1, s2) |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_apache_kafka_kafka_2_12",
artifact = "org.apache.kafka:kafka_2.12:1.1.1",
artifact_sha256 = "d7b77e3b150519724d542dfb5da1584b9cba08fb1272ff1e3b3d735937e22632",
srcjar_sha256 = "2a1a9ed91ad065bf62be64dbb4fd5e552ff90c42fc07e67ace4f82413304c3dd",
deps = [
"@com_101tec_zkclient",
"@com_fasterxml_jackson_core_jackson_databind",
"@com_typesafe_scala_logging_scala_logging_2_12",
"@com_yammer_metrics_metrics_core",
"@net_sf_jopt_simple_jopt_simple",
"@org_apache_kafka_kafka_clients",
"@org_apache_zookeeper_zookeeper",
"@org_scala_lang_scala_library",
"@org_scala_lang_scala_reflect",
"@org_slf4j_slf4j_api"
],
excludes = [
"org.slf4j:slf4j-log4j12",
"log4j:log4j",
],
)
| load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='org_apache_kafka_kafka_2_12', artifact='org.apache.kafka:kafka_2.12:1.1.1', artifact_sha256='d7b77e3b150519724d542dfb5da1584b9cba08fb1272ff1e3b3d735937e22632', srcjar_sha256='2a1a9ed91ad065bf62be64dbb4fd5e552ff90c42fc07e67ace4f82413304c3dd', deps=['@com_101tec_zkclient', '@com_fasterxml_jackson_core_jackson_databind', '@com_typesafe_scala_logging_scala_logging_2_12', '@com_yammer_metrics_metrics_core', '@net_sf_jopt_simple_jopt_simple', '@org_apache_kafka_kafka_clients', '@org_apache_zookeeper_zookeeper', '@org_scala_lang_scala_library', '@org_scala_lang_scala_reflect', '@org_slf4j_slf4j_api'], excludes=['org.slf4j:slf4j-log4j12', 'log4j:log4j']) |
(_, d) = tuple(map(int, input().strip().split(' ')))
arr = list(map(int, input().strip().split(' ')))
new_arr = arr[d:] + arr[:d]
print(' '.join(map(str, new_arr)))
| (_, d) = tuple(map(int, input().strip().split(' ')))
arr = list(map(int, input().strip().split(' ')))
new_arr = arr[d:] + arr[:d]
print(' '.join(map(str, new_arr))) |
class DebugConfig:
# base
SECRET_KEY = b'IL_PROGRAMMATORE_RESPONSABILE_MI_CAMBIERA! OVVIO AMO!'
SERVER_NAME = 'localhost:5000'
# database
MYSQL_DATABASE_HOST = 'localhost'
MYSQL_DATABASE_PORT = 3306
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = ''
MYSQL_DATABASE_DB = 'ingegneria'
#bcrypt
BCRYPT_HANDLE_LONG_PASSWORDS = True
| class Debugconfig:
secret_key = b'IL_PROGRAMMATORE_RESPONSABILE_MI_CAMBIERA! OVVIO AMO!'
server_name = 'localhost:5000'
mysql_database_host = 'localhost'
mysql_database_port = 3306
mysql_database_user = 'root'
mysql_database_password = ''
mysql_database_db = 'ingegneria'
bcrypt_handle_long_passwords = True |
# Exercise 1: Squaring Numbers
numbers = [1,1,2,3,5,8,13,21,34,55]
squared_numbers = [number**2 for number in numbers]
print(squared_numbers) | numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers) |
LIST_ALGORITHMS_TOPIC = 'list_algorithms'
SET_ALGORITHM_TOPIC = 'set_algorithm'
GET_SAMPLE_LIST_TOPIC = 'get_sample_list'
TAKE_SAMPLE_TOPIC = 'take_sample'
REMOVE_SAMPLE_TOPIC = 'remove_sample'
COMPUTE_CALIBRATION_TOPIC = 'compute_calibration'
SAVE_CALIBRATION_TOPIC = 'save_calibration'
CHECK_STARTING_POSE_TOPIC = 'check_starting_pose'
ENUMERATE_TARGET_POSES_TOPIC = 'enumerate_target_poses'
SELECT_TARGET_POSE_TOPIC = 'select_target_pose'
PLAN_TO_SELECTED_TARGET_POSE_TOPIC = 'plan_to_selected_target_pose'
EXECUTE_PLAN_TOPIC = 'execute_plan'
| list_algorithms_topic = 'list_algorithms'
set_algorithm_topic = 'set_algorithm'
get_sample_list_topic = 'get_sample_list'
take_sample_topic = 'take_sample'
remove_sample_topic = 'remove_sample'
compute_calibration_topic = 'compute_calibration'
save_calibration_topic = 'save_calibration'
check_starting_pose_topic = 'check_starting_pose'
enumerate_target_poses_topic = 'enumerate_target_poses'
select_target_pose_topic = 'select_target_pose'
plan_to_selected_target_pose_topic = 'plan_to_selected_target_pose'
execute_plan_topic = 'execute_plan' |
items = [{'id': 1, 'name': 'laptop', 'value': 1000},
{'id': 2, 'name': 'chair', 'value': 300},
{'id': 3, 'name': 'book', 'value': 20}]
def duplicate_items(items):
return [{key: value for key, value in x.items()} for x in items]
| items = [{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300}, {'id': 3, 'name': 'book', 'value': 20}]
def duplicate_items(items):
return [{key: value for (key, value) in x.items()} for x in items] |
DEPS = [
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
]
# TODO(phajdan.jr): provide coverage (http://crbug.com/693058).
DISABLE_STRICT_COVERAGE = True
| deps = ['recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step']
disable_strict_coverage = True |
{
'name': 'eCommerce',
'category': 'Website/Website',
'sequence': 55,
'summary': 'Sell your products online',
'website': 'https://www.odoo.com/page/e-commerce',
'version': '1.0',
'description': "",
'depends': ['website', 'sale', 'website_payment', 'website_mail', 'website_form', 'website_rating', 'digest'],
'data': [
'security/ir.model.access.csv',
'security/website_sale.xml',
'data/data.xml',
'data/mail_template_data.xml',
'data/digest_data.xml',
'views/product_views.xml',
'views/account_views.xml',
'views/onboarding_views.xml',
'views/sale_report_views.xml',
'views/sale_order_views.xml',
'views/crm_team_views.xml',
'views/templates.xml',
'views/snippets.xml',
'views/res_config_settings_views.xml',
'views/digest_views.xml',
'views/website_sale_visitor_views.xml',
],
'demo': [
'data/demo.xml',
],
'qweb': ['static/src/xml/*.xml'],
'installable': True,
'application': True,
'uninstall_hook': 'uninstall_hook',
}
| {'name': 'eCommerce', 'category': 'Website/Website', 'sequence': 55, 'summary': 'Sell your products online', 'website': 'https://www.odoo.com/page/e-commerce', 'version': '1.0', 'description': '', 'depends': ['website', 'sale', 'website_payment', 'website_mail', 'website_form', 'website_rating', 'digest'], 'data': ['security/ir.model.access.csv', 'security/website_sale.xml', 'data/data.xml', 'data/mail_template_data.xml', 'data/digest_data.xml', 'views/product_views.xml', 'views/account_views.xml', 'views/onboarding_views.xml', 'views/sale_report_views.xml', 'views/sale_order_views.xml', 'views/crm_team_views.xml', 'views/templates.xml', 'views/snippets.xml', 'views/res_config_settings_views.xml', 'views/digest_views.xml', 'views/website_sale_visitor_views.xml'], 'demo': ['data/demo.xml'], 'qweb': ['static/src/xml/*.xml'], 'installable': True, 'application': True, 'uninstall_hook': 'uninstall_hook'} |
class Bola:
def __init__(self, cor, circunferencia, material):
self.cor = cor
self.circunferencia = circunferencia
self.material = material
def troca_cor(self, n_cor):
self.cor = n_cor
def mostrar_cor(self):
return self.cor
bola = Bola('preta', 25,'couro')
print(bola.mostrar_cor())
bola.troca_cor('verde')
print(bola.mostrar_cor())
| class Bola:
def __init__(self, cor, circunferencia, material):
self.cor = cor
self.circunferencia = circunferencia
self.material = material
def troca_cor(self, n_cor):
self.cor = n_cor
def mostrar_cor(self):
return self.cor
bola = bola('preta', 25, 'couro')
print(bola.mostrar_cor())
bola.troca_cor('verde')
print(bola.mostrar_cor()) |
soma = 0
for i in range(100):
num = i + 1
print(num)
soma += num ** 2
print(soma)
| soma = 0
for i in range(100):
num = i + 1
print(num)
soma += num ** 2
print(soma) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.