content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Revision Date: 08/10/2018
Author: Bevan Glynn
Language: Python 2.7
Style: PEP8
Repo: https://github.com/Bayesian-thought/code-sample
Overview: This code demonstrations the use of functions and class structures
that return specific elements based on user input and inheritance
"""
def main():
brand_options = {... | """
Revision Date: 08/10/2018
Author: Bevan Glynn
Language: Python 2.7
Style: PEP8
Repo: https://github.com/Bayesian-thought/code-sample
Overview: This code demonstrations the use of functions and class structures
that return specific elements based on user input and inheritance
"""
def main():
brand_options = {1:... |
N = int(input())
phone_book = {}
for i in range(N):
a = str(input()).split(" ")
name = a[0]
phone = int(a[1])
phone_book[name] = phone
# for j in range(N):
while True:
try:
name = str(input())
if name in phone_book:
phone = phone_book[name]
print(name + "=" + str(phone))
else:
print("Not found")
... | n = int(input())
phone_book = {}
for i in range(N):
a = str(input()).split(' ')
name = a[0]
phone = int(a[1])
phone_book[name] = phone
while True:
try:
name = str(input())
if name in phone_book:
phone = phone_book[name]
print(name + '=' + str(phone))
e... |
CP_SERVICE_PORT = 5000
LG_SERVICE_URL = "http://127.0.0.1:5001"
RM_SERVICE_URL = "http://127.0.0.1:5002"
OC_SERVICE_URL = "http://127.0.0.1:5003"
LC_SERVICE_URL = "http://127.0.0.1:5004"
| cp_service_port = 5000
lg_service_url = 'http://127.0.0.1:5001'
rm_service_url = 'http://127.0.0.1:5002'
oc_service_url = 'http://127.0.0.1:5003'
lc_service_url = 'http://127.0.0.1:5004' |
def can_access(event, ssm_client, is_header=False) -> bool:
store = event["headers"] if is_header else event["queryStringParameters"]
request_token = store.get("Authorization")
if request_token is None:
return False
resp = ssm_client.get_parameter(Name="BookmarksPassword", WithDecryption=True)
... | def can_access(event, ssm_client, is_header=False) -> bool:
store = event['headers'] if is_header else event['queryStringParameters']
request_token = store.get('Authorization')
if request_token is None:
return False
resp = ssm_client.get_parameter(Name='BookmarksPassword', WithDecryption=True)
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# 1st recursive solution
def helper(node, lowe... | class Solution:
def is_valid_bst(self, root: TreeNode) -> bool:
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
left_subtree_info = helper(node.left, lower, node.val)
right_subtree_info = helper(node.right, node.val, u... |
__auther__ = 'jamfly'
def encrypt(text, shift):
result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
else:
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
result += char
return result
def decrypt(t... | __auther__ = 'jamfly'
def encrypt(text, shift):
result = ''
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
else:
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
... |
registry = []
def register(klass):
"""Adds the wrapped class to the registry"""
registry.append(klass)
return klass
| registry = []
def register(klass):
"""Adds the wrapped class to the registry"""
registry.append(klass)
return klass |
APPLICATION_STATUS_CHOICES = (
('Pending', 'Pending'),
('Accept', 'Accept'),
('Reject', 'Reject'),
)
KNOWN_MEASURE_CHOICES = (
('Years', 'Years'),
('Months', 'Months'),
)
REFERENCE_TYPE_CHOICES = (
('Professional', 'Professional'),
('Academic', 'Academic'),
('Social', 'Social')
) | application_status_choices = (('Pending', 'Pending'), ('Accept', 'Accept'), ('Reject', 'Reject'))
known_measure_choices = (('Years', 'Years'), ('Months', 'Months'))
reference_type_choices = (('Professional', 'Professional'), ('Academic', 'Academic'), ('Social', 'Social')) |
def extractWwwIllanovelsCom(item):
'''
Parser for 'www.illanovels.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('my little happiness', 'my little happiness', 'tr... | def extract_www_illanovels_com(item):
"""
Parser for 'www.illanovels.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 = [('my little happiness', 'my little happiness', 'transla... |
"""Classes defining the states for the state machine of the flashcards application.
"""
__all__ = ['State', 'MainMenu', 'AddCard', 'Practice', 'End']
class State:
"""General state.
"""
pass
class MainMenu(State):
"""Main menu, asking the user what to do.
"""
pass
class AddCard(State):
... | """Classes defining the states for the state machine of the flashcards application.
"""
__all__ = ['State', 'MainMenu', 'AddCard', 'Practice', 'End']
class State:
"""General state.
"""
pass
class Mainmenu(State):
"""Main menu, asking the user what to do.
"""
pass
class Addcard(State):
... |
# Time: O(n)
# Space: O(1)
# prefix sum, math
class Solution(object):
def maximumSumScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prefix = suffix = 0
result = float("-inf")
right = len(nums)-1
for left in xrange(len(nums)):
... | class Solution(object):
def maximum_sum_score(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prefix = suffix = 0
result = float('-inf')
right = len(nums) - 1
for left in xrange(len(nums)):
prefix += nums[left]
suffix +=... |
__author__ = 'Andy'
class DevicePollingProcess(object):
def __init__(self, poll_fn, output_queue, kill_event):
self.poll_fn = poll_fn
self.output_queue = output_queue
self.kill_event = kill_event
def read(self):
while not self.kill_event.is_set():
self.output_queue... | __author__ = 'Andy'
class Devicepollingprocess(object):
def __init__(self, poll_fn, output_queue, kill_event):
self.poll_fn = poll_fn
self.output_queue = output_queue
self.kill_event = kill_event
def read(self):
while not self.kill_event.is_set():
self.output_queue... |
'''
This is python implementation of largest rectangle in histogram problem
'''
'''
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1,
find the area of largest rectangle in the histogram.
'''
def largestRectangleArea(lst: List[int]) -> int:
if len(lst)==0:
... | """
This is python implementation of largest rectangle in histogram problem
"""
"\nGiven n non-negative integers representing the histogram's bar height where the width of each bar is 1, \nfind the area of largest rectangle in the histogram.\n"
def largest_rectangle_area(lst: List[int]) -> int:
if len(lst) == 0:
... |
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
return (len(re.split(''.join([str(n)+'|' for n in J]),S))-1)
| class Solution:
def num_jewels_in_stones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
return len(re.split(''.join([str(n) + '|' for n in J]), S)) - 1 |
# Basic data types
x = 3
print(type(x)) # Prints "<class 'int'>"
print(x) # Prints "3"
print(x + 1) # Addition; prints "4"
print(x - 1) # Subtraction; prints "2"
print(x * 2) # Mul... | x = 3
print(type(x))
print(x)
print(x + 1)
print(x - 1)
print(x * 2)
print(x ** 2)
x += 1
print(x)
x *= 2
print(x)
y = 2.5
print(type(y))
print(y, y + 1, y * 2, y ** 2)
t = True
f = False
print(type(t))
print(t and f)
print(t or f)
print(not t)
print(t != f)
hello = 'hello'
world = 'world'
print(hello)
print(len(hello)... |
'''
Created on Nov 2, 2013
@author: peterb
'''
TOPIC = "topic"
QUEUE = "queue"
COUNT = "count"
METHOD = "method"
OPTIONS = "options"
LOG_FORMAT = "[%(levelname)1.1s %(asctime)s %(process)d %(thread)x %(module)s:%(lineno)d] %(message)s" | """
Created on Nov 2, 2013
@author: peterb
"""
topic = 'topic'
queue = 'queue'
count = 'count'
method = 'method'
options = 'options'
log_format = '[%(levelname)1.1s %(asctime)s %(process)d %(thread)x %(module)s:%(lineno)d] %(message)s' |
'''
LeetCode Strings Q.415 Add Strings
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Without using builtin libraries.
'''
def addStrings(num1, num2):
num1 = num1[::-1]
num2 = num2[::-1]
def solve(num1, num2):
n1 = len(num1)
n2 = ... | """
LeetCode Strings Q.415 Add Strings
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Without using builtin libraries.
"""
def add_strings(num1, num2):
num1 = num1[::-1]
num2 = num2[::-1]
def solve(num1, num2):
n1 = len(num1)
n2 = l... |
#
# PySNMP MIB module PowerConnect3248-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PowerConnect3248-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:34:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
# This script proves that we are allowed to have scripts
# with the same name as a built-in site package, e.g. `site.py`.
# This script also shows that the module doesn't load until called.
print("Super secret script output") # noqa: T001
| print('Super secret script output') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 19 14:49:58 2019
@author: thomas
"""
for a in range(32,48):
print(str(a)+' $\leftarrow$ '+chr(a)+' & '+str(a+16)+' $\leftarrow$ '+chr(a+16)+' & '
+str(a+32)+' $\leftarrow$ '+chr(a+32)+' & '
+str(a+48)+' $\leftarrow$ '+chr(a+... | """
Created on Tue Mar 19 14:49:58 2019
@author: thomas
"""
for a in range(32, 48):
print(str(a) + ' $\\leftarrow$ ' + chr(a) + ' & ' + str(a + 16) + ' $\\leftarrow$ ' + chr(a + 16) + ' & ' + str(a + 32) + ' $\\leftarrow$ ' + chr(a + 32) + ' & ' + str(a + 48) + ' $\\leftarrow$ ' + chr(a + 48) + ' \\\\') |
__all__ = ['global_config']
class _Config(object):
def __repr__(self):
return repr(self.__dict__)
class RobeepConfig(_Config):
pass
_config = _Config()
_config.robeep = dict()
_config.robeep['name'] = 'robeep agent'
_config.robeep['host'] = 'localhost'
_config.robeep['port'] = 8086
_config.robeep[... | __all__ = ['global_config']
class _Config(object):
def __repr__(self):
return repr(self.__dict__)
class Robeepconfig(_Config):
pass
_config = __config()
_config.robeep = dict()
_config.robeep['name'] = 'robeep agent'
_config.robeep['host'] = 'localhost'
_config.robeep['port'] = 8086
_config.robeep['u... |
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_list = list(s)
t_list = list(t)
s_list.sort()
t_list.sort()
if (s_list == t_list):
return True
else:
... | class Solution:
def is_anagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_list = list(s)
t_list = list(t)
s_list.sort()
t_list.sort()
if s_list == t_list:
return True
else:
return Fals... |
#!/usr/bin/env python
#coding=utf-8
_temple_wd = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<script src='https://cdn.bootcss.com/echarts/3.2.2/echarts.simple.js'></script>
<script type="text/javascript" src="http://data-visual.cn/datav/src/js/echarts/extension/ech... | _temple_wd = '\n<!DOCTYPE html>\n<html>\n\n<head>\n <meta charset="utf-8">\n <title>ECharts</title>\n <script src=\'https://cdn.bootcss.com/echarts/3.2.2/echarts.simple.js\'></script>\n <script type="text/javascript" src="http://data-visual.cn/datav/src/js/echarts/extension/echarts-wordcloud.min.js"></scrip... |
base_config = {
'agent': '@spinup_bis.algos.tf2.SUNRISE',
'total_steps': 3000000,
'num_test_episodes': 30,
'ac_kwargs': {
'hidden_sizes': [256, 256],
'activation': 'relu',
},
'ac_number': 5,
'autotune_alpha': True,
'beta_bernoulli': 1.,
}
params_grid = {
'task': [
... | base_config = {'agent': '@spinup_bis.algos.tf2.SUNRISE', 'total_steps': 3000000, 'num_test_episodes': 30, 'ac_kwargs': {'hidden_sizes': [256, 256], 'activation': 'relu'}, 'ac_number': 5, 'autotune_alpha': True, 'beta_bernoulli': 1.0}
params_grid = {'task': ['Hopper-v2', 'Walker2d-v2', 'Ant-v2', 'Humanoid-v2'], 'seed': ... |
# Step 1: Annotate `get_name`.
# Step 2: Annotate `greet`.
# Step 3: Identify the bug in `greet`.
# Step 4: Green sticky on!
def num_vowels(s: str) -> int:
result = 0
for letter in s:
if letter in "aeiouAEIOU":
result += 1
return result
def get_name():
return "YOUR NAME HERE"
def ... | def num_vowels(s: str) -> int:
result = 0
for letter in s:
if letter in 'aeiouAEIOU':
result += 1
return result
def get_name():
return 'YOUR NAME HERE'
def greet(name):
print('Hello ' + name + '! Your name contains ' + num_vowels(name) + ' vowels.')
greet(get_name()) |
def tree_maximum(self):
atual = self.root
anterior = None
while atual != None:
anterior = atual
atual = atual.dir
return anterior | def tree_maximum(self):
atual = self.root
anterior = None
while atual != None:
anterior = atual
atual = atual.dir
return anterior |
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
for i in range(14):
print(i)
# 42, 43, 44, 45, ..., 99
for i in range(42, 100):
print(i)
# odd numbers between 0 to 100
for i in range(1, 100, 2):
print(i) | for i in range(14):
print(i)
for i in range(42, 100):
print(i)
for i in range(1, 100, 2):
print(i) |
"""Kata: Find the odd int - Find the int that is in the sequence odd amt times.
#1 Best Practices Solution by cerealdinner, ynnake, sfr, netpsychosis,
VadimPopov, user7514902 (plus 291 more warriors)
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
... | """Kata: Find the odd int - Find the int that is in the sequence odd amt times.
#1 Best Practices Solution by cerealdinner, ynnake, sfr, netpsychosis,
VadimPopov, user7514902 (plus 291 more warriors)
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
... |
def sumd(a1):
c=0
a=a1
while(a!=0):
c+=int(a%10)
a//=10
return c
n=int(input())
ans=0
for i in range(n-97,n+1):
if(i+sumd(i)+sumd(sumd(i))==n):
ans+=1
print(ans) | def sumd(a1):
c = 0
a = a1
while a != 0:
c += int(a % 10)
a //= 10
return c
n = int(input())
ans = 0
for i in range(n - 97, n + 1):
if i + sumd(i) + sumd(sumd(i)) == n:
ans += 1
print(ans) |
VOCAB_FILE = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/vocab.txt'
BERT_CONFIG_FILE = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/config.json'
# BC5CDR_WEIGHT = 'weights/bc5cdr_wt.pt'
# BIONLP13CG_WEIGHT = 'weights/bionlp13cg_wt.pt'
BERT_WEIGHTS =... | vocab_file = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/vocab.txt'
bert_config_file = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/config.json'
bert_weights = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/pytorch_w... |
def minkowski(ratings_1, ratings_2, r):
"""Computes the Minkowski distance.
Both ratings_1 and rating_2 are dictionaries of the form
{'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5}
"""
distance = 0
commonRatings = False
for key in ratings_1:
if key in ratings_2:
distance += ... | def minkowski(ratings_1, ratings_2, r):
"""Computes the Minkowski distance.
Both ratings_1 and rating_2 are dictionaries of the form
{'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5}
"""
distance = 0
common_ratings = False
for key in ratings_1:
if key in ratings_2:
distance +=... |
# ----
# |C s |
# | @ S|
# |C s>|
# ----
level.description("Your ears become more in tune with the surroundings. "
"Listen to find enemies and captives!")
level.tip("Use warrior.listen to find spaces with other units, "
"and warrior.direction_of to determine what direction they're in.")
l... | level.description('Your ears become more in tune with the surroundings. Listen to find enemies and captives!')
level.tip("Use warrior.listen to find spaces with other units, and warrior.direction_of to determine what direction they're in.")
level.clue('Walk towards an enemy or captive with warrior.walk_(warrior.directi... |
class Struct:
def __init__(self, id, loci):
self.id = id
self.loci = loci
def make_dict(self, num, mydict, pattrn):
mydict[pattrn] = num
| class Struct:
def __init__(self, id, loci):
self.id = id
self.loci = loci
def make_dict(self, num, mydict, pattrn):
mydict[pattrn] = num |
CUSTOM_TEMPLATES = {
# https://iot.mi.com/new/doc/embedded-development/ble/object-definition#%E7%89%99%E5%88%B7%E4%BA%8B%E4%BB%B6
'ble_toothbrush_events': "{%- set dat = props.get('event.16') | default('{}',true) | from_json %}"
"{%- set tim = dat.timestamp | default(0,true) | times... | custom_templates = {'ble_toothbrush_events': "{%- set dat = props.get('event.16') | default('{}',true) | from_json %}{%- set tim = dat.timestamp | default(0,true) | timestamp_local %}{%- set val = dat.get('value',[]).0 | default('0000') %}{%- set typ = val[0:2] | int(0,16) %}{%- set num = val[2:4] | int(0,16) %}{{ {'ev... |
class GenericsPrettyPrinter:
''' Pretty printing of ugeneric_t instances.
'''
def __init__(self, value):
#print(str(value))
self.v = value
def to_string (self):
t = self.v['t']
v = self.v['v']
#print(str(t))
#print(str(v))
if t['type'] >= 11: # m... | class Genericsprettyprinter:
""" Pretty printing of ugeneric_t instances.
"""
def __init__(self, value):
self.v = value
def to_string(self):
t = self.v['t']
v = self.v['v']
if t['type'] >= 11:
return 'G_MEMCHUNK{.data = %s, .size = %s}' % (v['ptr'], t['memch... |
class TinyIntError(Exception):
def __init__(self):
self.message = 'El numero entregado NO es un dato tipo TinyInt'
def __str__(self):
return self.message
| class Tinyinterror(Exception):
def __init__(self):
self.message = 'El numero entregado NO es un dato tipo TinyInt'
def __str__(self):
return self.message |
'''
SciPy Introduction
What is SciPy?
* SciPy is a scientific computation library that uses NumPy underneath.
* SciPy stands for Scientific Python.
* It provides more utility functions for optimization, stats and signal processing.
* Like NumPy, SciPy is open source so we can use it freely.
* SciPy was created by Num... | """
SciPy Introduction
What is SciPy?
* SciPy is a scientific computation library that uses NumPy underneath.
* SciPy stands for Scientific Python.
* It provides more utility functions for optimization, stats and signal processing.
* Like NumPy, SciPy is open source so we can use it freely.
* SciPy was created by Num... |
def normalize(name):
if name[-4:] == '.pho':
name = name[:-4]
return "{}.pho".format(name)
| def normalize(name):
if name[-4:] == '.pho':
name = name[:-4]
return '{}.pho'.format(name) |
# Author: Andrew Jewett (jewett.aij at g mail)
# License: MIT License (See LICENSE.md)
# Copyright (c) 2013
espt_delim_atom_fields = set(["pos", "type", "v", "f",
"bond",
"temp", "gamma",
"q",
"... | espt_delim_atom_fields = set(['pos', 'type', 'v', 'f', 'bond', 'temp', 'gamma', 'q', 'quat', 'omega', 'torque', 'rinertia', 'fix', 'unfix', 'ext_force', 'exclude', 'delete', 'mass', 'dipm', 'dip', 'virtual', 'vs_relative', 'distance', 'vs_auto_relate_to'])
def lines_w_slashes(text):
"""
Iterate over the lines... |
class tree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left: 'tree|None' = left
self.right: 'tree|None' = right
def inorder(self):
if self.left:
yield from self.left.inorder()
yield self.data
if self.right:
yiel... | class Tree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left: 'tree|None' = left
self.right: 'tree|None' = right
def inorder(self):
if self.left:
yield from self.left.inorder()
yield self.data
if self.right:
yie... |
"""
Space : O(n)
Time : O(n)
"""
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
s1, s2 = '', ''
for x in word1:
s1 += x
for y in word2:
s2 += y
return s1 == s2
| """
Space : O(n)
Time : O(n)
"""
class Solution:
def array_strings_are_equal(self, word1: List[str], word2: List[str]) -> bool:
(s1, s2) = ('', '')
for x in word1:
s1 += x
for y in word2:
s2 += y
return s1 == s2 |
n = 42
f = -7.03
s = 'string cheese'
# 42 -7.030000 string cheese
print('%d %f %s'% (n, f, s) )
# align to the right
# 42 -7.030000 string cheese
print('%10d %10f %10s'%(n, f, s) )
# align to the right with sign
# +42 -7.030000 string cheese
print('%+10d %+10f %+10s'%(n, f, s) )
# align to the left
#... | n = 42
f = -7.03
s = 'string cheese'
print('%d %f %s' % (n, f, s))
print('%10d %10f %10s' % (n, f, s))
print('%+10d %+10f %+10s' % (n, f, s))
print('%-10d %-10f %-10s' % (n, f, s))
print('%10.4d %10.4f %10.4s' % (n, f, s))
print('%.4d %.4f %.4s' % (n, f, s))
print('%*.*d %*.*f %*.*s' % (10, 4, n, 10, 4, f, 10, 4, s))
p... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Masu utility methods."""
| """Masu utility methods.""" |
def main():
""" Cuerpo principal """
# Entrada
while True:
cad = str(input('Ingrese un texto: '))
if len(cad) == 0:
print('Error, la cadena no puede ser vacia.')
else:
break
# Proceso
cad_copy = cad.lower()
palindromo = lambda cad: cad == cad... | def main():
""" Cuerpo principal """
while True:
cad = str(input('Ingrese un texto: '))
if len(cad) == 0:
print('Error, la cadena no puede ser vacia.')
else:
break
cad_copy = cad.lower()
palindromo = lambda cad: cad == cad[::-1]
if palindromo(cad_copy)... |
# Time Complexity: O(nlogn)
def merge(nums1, nums2):
i, j, merged = 0, 0, []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
return merged+nums1[i:]+nums2[j:]... | def merge(nums1, nums2):
(i, j, merged) = (0, 0, [])
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
return merged + nums1[i:] + nums2[j:]
def merge_sort(arr)... |
# Kasia Connell, 2019
# Solution to question 6
# The program will take user's input string and output every second word
# References:
# Ian's video tutorials: https://web.microsoftstream.com/video/909896e3-9d9d-45fe-aba0-a1930fe08a7f
# Programiz: https://www.programiz.com/python-programming/methods/string/join
# Stac... | string = input('Enter a string of text:')
p = string.split()[::2]
separator = ' '
print(separator.join(p)) |
class IFormattable:
""" Provides functionality to format the value of an object into a string representation. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return IFormattable()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def ToString(self,format,formatProvider):
"... | class Iformattable:
""" Provides functionality to format the value of an object into a string representation. """
def zzz(self):
"""hardcoded/mock instance of the class"""
return i_formattable()
instance = zzz()
'hardcoded/returns an instance of the class'
def to_string(self, forma... |
SIZE = 20 # quadratic size of labyrinth
WIDTH, HEIGHT = SIZE, SIZE # can be set to any wanted non-quadratic size
WALL_SYMBOL = '#'
EMPTY_SYMBOL = '.'
NUM_WORMHOLES = 20
WORMHOLE_LENGTH = WIDTH * HEIGHT / 33
DIRECTION_CHANGE_CHANCE = 25
| size = 20
(width, height) = (SIZE, SIZE)
wall_symbol = '#'
empty_symbol = '.'
num_wormholes = 20
wormhole_length = WIDTH * HEIGHT / 33
direction_change_chance = 25 |
class Student:
def __init__(self, student_record):
self.id = student_record[0]
self.cognome = student_record[1]
self.nome = student_record[2]
self.matricola = student_record[3]
self.cf = student_record[4]
self.desiderata = student_record[5]
self.sesso = stude... | class Student:
def __init__(self, student_record):
self.id = student_record[0]
self.cognome = student_record[1]
self.nome = student_record[2]
self.matricola = student_record[3]
self.cf = student_record[4]
self.desiderata = student_record[5]
self.sesso = stude... |
# Power digit sum
# Problem 16
# 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 21000?
# oh well... python
print(sum((int(c) for c in str(2 ** 1000)))) | print(sum((int(c) for c in str(2 ** 1000)))) |
def deprecated(reason):
string_types = (type(b''), type(u''))
if isinstance(reason, string_types):
def decorator(func1):
fmt1 = "Call to deprecated function {name} ({reason})."
@functools.wraps(func1)
def new_func1(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings... | def deprecated(reason):
string_types = (type(b''), type(u''))
if isinstance(reason, string_types):
def decorator(func1):
fmt1 = 'Call to deprecated function {name} ({reason}).'
@functools.wraps(func1)
def new_func1(*args, **kwargs):
warnings.simplefi... |
class MacroFiles:
def cfclos(self, **kwargs):
"""Closes the "command" file.
APDL Command: ``*CFCLOS``
Notes
-----
This command is valid in any processor.
"""
command = f"*CFCLOS,"
return self.run(command, **kwargs)
def cfopen(self, fname="", ext... | class Macrofiles:
def cfclos(self, **kwargs):
"""Closes the "command" file.
APDL Command: ``*CFCLOS``
Notes
-----
This command is valid in any processor.
"""
command = f'*CFCLOS,'
return self.run(command, **kwargs)
def cfopen(self, fname='', ex... |
#!/usr/bin/python
# t.py
# test program for Python line counter.
print("Hello, World!")
print("Hello again.") # Code line with comment, too.
print('''Hello again again.''')
print("""Looks like a block comment but isn't.""")
''' begin block comment with single quotes
inside block comment
'''
""" begin block c... | print('Hello, World!')
print('Hello again.')
print('Hello again again.')
print("Looks like a block comment but isn't.")
' begin block comment with single quotes\n inside block comment\n'
' begin block comment with double quotes\n inside second block comment\n'
'\nblock comment containing blank line\n\n# and line ... |
# Solution to problem 6
# Rebecca Turley, 2019-02-18
# secondstring.py
# The user is asked to enter a sentence, which is then shortened to x in the programme to simplify working with it (rather than having to use the full sentence each time)
x = input ("Please enter a sentence: ")
# enumerate is a function that re... | x = input('Please enter a sentence: ')
for (i, s) in enumerate(x.split()):
if i % 2 == 0:
print(s, end=' ') |
def bytes_to_hex(input_bytes: bytes):
"""Takes in a byte string. Outputs that string as hex"""
return input_bytes.hex()
def hex_to_bytes(input_hex: str):
"""Takes in a hex string. Outputs that string as bytes"""
return bytes.fromhex(input_hex)
| def bytes_to_hex(input_bytes: bytes):
"""Takes in a byte string. Outputs that string as hex"""
return input_bytes.hex()
def hex_to_bytes(input_hex: str):
"""Takes in a hex string. Outputs that string as bytes"""
return bytes.fromhex(input_hex) |
#
# PySNMP MIB module Nortel-Magellan-Passport-IpiVcMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-IpiVcMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def levelOrder(root):
#Write your code here
q = []
q.append(root)
while q:
n = q[0]
print(n.info,end=" ")
if n.left:
... | """
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def level_order(root):
q = []
q.append(root)
while q:
n = q[0]
print(n.info, end=' ')
if n.left:
q.append(n.left)
if n.rig... |
#
# PySNMP MIB module CISCO-SWITCH-USAGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-USAGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
"""
Question 24 :
Python has many build-in functions, and if you do not know
how to use it, you can read document online or books. But Python
has a build-in socument function for every build-in function.
Write a program to print some Python build-in functions
documents, suchas abs(), int(), input()... | """
Question 24 :
Python has many build-in functions, and if you do not know
how to use it, you can read document online or books. But Python
has a build-in socument function for every build-in function.
Write a program to print some Python build-in functions
documents, suchas abs(), int(), input()... |
n = input()
j = [int(x) for x in list(str(n))]
count = 0
for i in range(3):
if j[i] == 1:
count = count + 1
print(count) | n = input()
j = [int(x) for x in list(str(n))]
count = 0
for i in range(3):
if j[i] == 1:
count = count + 1
print(count) |
(some_really_long_variable_name_you_should_never_use_1,
some_really_long_variable_name_you_should_never_use_2,
some_really_long_variable_name_you_should_never_use_3) = (1, 2, 3)
print(some_really_long_variable_name_you_should_never_use_1,
some_really_long_variable_name_you_should_never_use_2,
some_really_long_variable_... | (some_really_long_variable_name_you_should_never_use_1, some_really_long_variable_name_you_should_never_use_2, some_really_long_variable_name_you_should_never_use_3) = (1, 2, 3)
print(some_really_long_variable_name_you_should_never_use_1, some_really_long_variable_name_you_should_never_use_2, some_really_long_variable_... |
non_agent_args = {
'env': {'help': 'gym environment id', 'required': True},
'n-envs': {
'help': 'Number of environments to create',
'default': 1,
'type': int,
'hp_type': 'categorical',
},
'preprocess': {
'help': 'If specified, states will be treated as atari frame... | non_agent_args = {'env': {'help': 'gym environment id', 'required': True}, 'n-envs': {'help': 'Number of environments to create', 'default': 1, 'type': int, 'hp_type': 'categorical'}, 'preprocess': {'help': 'If specified, states will be treated as atari frames\nand preprocessed accordingly', 'action': 'store_true'}, 'l... |
# coding: utf-8
class Parser(object):
def __init__(self):
pass | class Parser(object):
def __init__(self):
pass |
aa = [[0 for x in range(42)] for y in range(42)]
a = [[0 for x in range(42)] for y in range(42)]
version = 0
z = 0
sum = 0
def solve1(out):
global version
num1 = 0
num2 = 0
num3 = 0
z = 256
for i in range(34, 37):
for j in range(39, 42):
if a[i][j] != 0:
num... | aa = [[0 for x in range(42)] for y in range(42)]
a = [[0 for x in range(42)] for y in range(42)]
version = 0
z = 0
sum = 0
def solve1(out):
global version
num1 = 0
num2 = 0
num3 = 0
z = 256
for i in range(34, 37):
for j in range(39, 42):
if a[i][j] != 0:
num1... |
def primefactors(arr):
p = []
for i in range(0, len(arr)):
factor = []
if arr[i] > 1:
for j in range(2, arr[i]+1):
if arr[i]%j == 0:
factor.append(j)
for j in range(0, len(factor)):
if factor[j] > 1:
if facto... | def primefactors(arr):
p = []
for i in range(0, len(arr)):
factor = []
if arr[i] > 1:
for j in range(2, arr[i] + 1):
if arr[i] % j == 0:
factor.append(j)
for j in range(0, len(factor)):
if factor[j] > 1:
if facto... |
expected_output ={
"lentry_label": {
16: {
"aal": {
"deagg_vrf_id": 0,
"eos0": {"adj_hdl": "0x65000016", "hw_hdl": "0x7ff7910f32b8"},
"eos1": {"adj_hdl": "0x65000016", "hw_hdl": "0x7ff7910f30a8"},
"id": 1174405122,
"... | expected_output = {'lentry_label': {16: {'aal': {'deagg_vrf_id': 0, 'eos0': {'adj_hdl': '0x65000016', 'hw_hdl': '0x7ff7910f32b8'}, 'eos1': {'adj_hdl': '0x65000016', 'hw_hdl': '0x7ff7910f30a8'}, 'id': 1174405122, 'lbl': 16, 'lspa_handle': '0'}, 'backwalk_cnt': 0, 'lentry_hdl': '0x46000002', 'lspa_handle': '0', 'modify_c... |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Prints letter 'T' to the console. #
# Program ... | def print_letter_t():
for x in range(10):
print('*', end='')
print()
for x in range(10):
print('*'.center(10, ' '))
if __name__ == '__main__':
print_letter_t() |
people = {1: 'fred', 0: 'harry', 9: 'andy'}
print(sorted(people.keys()))
print(sorted(people.values()))
print(sorted(people.items()))
print(dict(sorted(people.items()))) # really???
person = people.get(1, None)
assert person == 'fred'
person = people.get(8, None)
assert person is None
| people = {1: 'fred', 0: 'harry', 9: 'andy'}
print(sorted(people.keys()))
print(sorted(people.values()))
print(sorted(people.items()))
print(dict(sorted(people.items())))
person = people.get(1, None)
assert person == 'fred'
person = people.get(8, None)
assert person is None |
def replace(s, old, new):
temp = s.split(old)
temp2 = new.join(temp)
return temp2
print(replace("Mississippi", "i", "I"))
| def replace(s, old, new):
temp = s.split(old)
temp2 = new.join(temp)
return temp2
print(replace('Mississippi', 'i', 'I')) |
class Loader:
@classmethod
def load(cls, slide: "Slide"):
raise NotImplementedError
@classmethod
def close(cls, slide: "Slide"):
raise NotImplementedError
| class Loader:
@classmethod
def load(cls, slide: 'Slide'):
raise NotImplementedError
@classmethod
def close(cls, slide: 'Slide'):
raise NotImplementedError |
#
# @lc app=leetcode.cn id=1196 lang=python3
#
# [1196] filling-bookcase-shelves
#
None
# @lc code=end | None |
# Validador de CPF
# exemplo 2
cpf = '16899535009'
novo_cpf = cpf[:-2]
soma1 = 0
soma2 = 0
for e, r in enumerate(range(10, 1, -1)):
soma1 = soma1 + int(novo_cpf[e]) * int(r)
digito_1 = 11 - (soma1 % 11)
if digito_1 > 9:
digito_1 = 0
novo_cpf += str(digito_1)
for e, r in enumerate(range(11, 1, -1)):
soma... | cpf = '16899535009'
novo_cpf = cpf[:-2]
soma1 = 0
soma2 = 0
for (e, r) in enumerate(range(10, 1, -1)):
soma1 = soma1 + int(novo_cpf[e]) * int(r)
digito_1 = 11 - soma1 % 11
if digito_1 > 9:
digito_1 = 0
novo_cpf += str(digito_1)
for (e, r) in enumerate(range(11, 1, -1)):
soma2 = soma2 + int(novo_cpf[e]) * in... |
class Meld:
cards = list()
canasta = False
mixed = False
wild = False
cardType = str
def __init__(self, cards):
self.cards = cards
if len(cards) > 7:
self.canasta = True
self.wild = True
self.cardType = '2'
for card in self.cards:
if card['code'][0] != '2' or card['code'][0] != 'X':
self.wil... | class Meld:
cards = list()
canasta = False
mixed = False
wild = False
card_type = str
def __init__(self, cards):
self.cards = cards
if len(cards) > 7:
self.canasta = True
self.wild = True
self.cardType = '2'
for card in self.cards:
... |
class NervenException(Exception):
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return 'NervenException: %s' % self.msg
class OptionDoesNotExist(NervenException):
def __repr__(self):
return 'Config option %s does not exist.' % self.msg
| class Nervenexception(Exception):
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return 'NervenException: %s' % self.msg
class Optiondoesnotexist(NervenException):
def __repr__(self):
return 'Config option %s does not exist.' % self.msg |
def largest_prime(n):
"Output the largest prime factor of a number"
i = 2
while n != 1:
for i in range(2,n+1):
if n%i == 0:
n = int(n/i)
p = i
break
else:
pass
return p
#The following function is unnc... | def largest_prime(n):
"""Output the largest prime factor of a number"""
i = 2
while n != 1:
for i in range(2, n + 1):
if n % i == 0:
n = int(n / i)
p = i
break
else:
pass
return p
def is_prime(n):
"""Det... |
'''
@author: Pranshu Aggarwal
@problem: https://hack.codingblocks.com/app/practice/1/484/problem
'''
def pattern_with_zeros(n):
for row in range(1, n + 1):
for col in range(1, row + 1):
if (col == 1) or (col == row): print(row, end = '')
else: print(0, end = '')
... | """
@author: Pranshu Aggarwal
@problem: https://hack.codingblocks.com/app/practice/1/484/problem
"""
def pattern_with_zeros(n):
for row in range(1, n + 1):
for col in range(1, row + 1):
if col == 1 or col == row:
print(row, end='')
else:
print(0, en... |
def OddLengthSum(arr):
sum = 0
l = len(arr)
for i in range(l):
for j in range(i, l, 2):
for k in range(i, j + 1, 1):
sum += arr[k]
return sum
arr = [ 1, 4, 2, 5, 3 ]
print(OddLengthSum(arr))
| def odd_length_sum(arr):
sum = 0
l = len(arr)
for i in range(l):
for j in range(i, l, 2):
for k in range(i, j + 1, 1):
sum += arr[k]
return sum
arr = [1, 4, 2, 5, 3]
print(odd_length_sum(arr)) |
def get(client: object) -> dict:
"""Get a list of core school user roles.
Documentation:
https://developer.sky.blackbaud.com/docs/services/school/operations/v1rolesget
Args:
client (object): The SKY API client object.
Returns:
Dictionary of results.
"""
url = f'https:/... | def get(client: object) -> dict:
"""Get a list of core school user roles.
Documentation:
https://developer.sky.blackbaud.com/docs/services/school/operations/v1rolesget
Args:
client (object): The SKY API client object.
Returns:
Dictionary of results.
"""
url = f'https:/... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present BlueTensor.ai
"""
| """
License: MIT
Copyright (c) 2019 - present BlueTensor.ai
""" |
def maxArea(arr):
pass
if __name__ == '__main__':
arr=[]
print(maxArea(arr)) | def max_area(arr):
pass
if __name__ == '__main__':
arr = []
print(max_area(arr)) |
# Copyright (c) 2019 Monolix
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
class Function:
def __init__(self, function, description, returns):
self.function = function
self.name = function.__name__
self.example = function.__doc__
self.de... | class Function:
def __init__(self, function, description, returns):
self.function = function
self.name = function.__name__
self.example = function.__doc__
self.description = description
self.returns = returns.__name__ |
class ImageStatus:
New = "NEW"
Done = "DONE"
Skipped = "SKIPPED"
InProgress = "IN PROGRESS"
ToReview = "TO REVIEW"
AutoLabelled = "AUTO-LABELLED"
class ExportFormat:
JSON_v11 = "json_v1.1"
SEMANTIC_PNG = "semantic_png"
JSON_COCO = "json_coco"
IMAGES = "images"
class SemanticF... | class Imagestatus:
new = 'NEW'
done = 'DONE'
skipped = 'SKIPPED'
in_progress = 'IN PROGRESS'
to_review = 'TO REVIEW'
auto_labelled = 'AUTO-LABELLED'
class Exportformat:
json_v11 = 'json_v1.1'
semantic_png = 'semantic_png'
json_coco = 'json_coco'
images = 'images'
class Semantic... |
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
prefix=""
t=[]
for i in searchWord:
prefix+=i
k=[]
for z in products:
if z[:len(prefix)]==prefix:
... | class Solution:
def suggested_products(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
prefix = ''
t = []
for i in searchWord:
prefix += i
k = []
for z in products:
if z[:len(prefix)] == prefix:
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
"""
class ContinueError(Exception):
pass
class BreakError(Exception):
pass
class ExitError(Exception):
pass
class CommnadNotFoundError(Exception):
pass
| """
"""
class Continueerror(Exception):
pass
class Breakerror(Exception):
pass
class Exiterror(Exception):
pass
class Commnadnotfounderror(Exception):
pass |
"""
cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;')
"""
cmd.do('alter 3fa0, resi=str(int(resi)+100);sort;')
# Description: Add or substract a residue number offset.
# Source: https://www.pymolwiki.org/index.php/Sync
| """
cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;')
"""
cmd.do('alter 3fa0, resi=str(int(resi)+100);sort;') |
class DbCache:
__slots__ = "cache", "database", "iteration"
def __init__(self, database):
self.cache = {}
self.database = database
self.iteration = -1
def get(self, *flags, **forced_flags):
required = {flag: True for flag in flags}
required.update(forced_flags)
... | class Dbcache:
__slots__ = ('cache', 'database', 'iteration')
def __init__(self, database):
self.cache = {}
self.database = database
self.iteration = -1
def get(self, *flags, **forced_flags):
required = {flag: True for flag in flags}
required.update(forced_flags)
... |
#Buttons
SW1 = 21
SW2 = 20
SW3 = 16
#in and out
IN1 = 19
IN2 = 26
OUT1 = 5
OUT2 = 6
OUT3 = 13
#servos
SERVO = 27
# GPI for lcd
LCD_RS = 4
LCD_E = 17
LCD_D4 = 18
LCD_D5 = 22
LCD_D6 = 23
LCD_D7 = 24
| sw1 = 21
sw2 = 20
sw3 = 16
in1 = 19
in2 = 26
out1 = 5
out2 = 6
out3 = 13
servo = 27
lcd_rs = 4
lcd_e = 17
lcd_d4 = 18
lcd_d5 = 22
lcd_d6 = 23
lcd_d7 = 24 |
# Programa que leia sete valores numericos e cadastre os em uma lista unica que mantenha separados os valores pares e impares
# mostre os valores pares e impares de forma crescente
lista = [[], []]
num = 0
for n in range(0, 7):
num = int(input(f'Digite o {n+1} valor: '))
if num % 2 == 0:
lista[0].appe... | lista = [[], []]
num = 0
for n in range(0, 7):
num = int(input(f'Digite o {n + 1} valor: '))
if num % 2 == 0:
lista[0].append(num)
else:
lista[1].append(num)
print(f'Os valores pares digitados foram: {sorted(lista[0])}')
print(f'Os valores impares digitados foram: {sorted(lista[1])}') |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"prepare_data": "00_core.ipynb",
"train_valid_split": "00_core.ipynb",
"Availability": "00_core.ipynb",
"LinearMNL": "00_core.ipynb",
"DataLoaders": "00_core.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'prepare_data': '00_core.ipynb', 'train_valid_split': '00_core.ipynb', 'Availability': '00_core.ipynb', 'LinearMNL': '00_core.ipynb', 'DataLoaders': '00_core.ipynb', 'EarlyStopping': '00_core.ipynb', 'Learner': '00_core.ipynb'}
modules = ['core.py']... |
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
ans = 0
numToIndex = {num: i for i, num in enumerate(nums)}
for i, num in enumerate(nums):
target = num + k
if target in numToIndex and numToIndex[target] != i:
ans += 1
del numToIndex[target]
return ans... | class Solution:
def find_pairs(self, nums: List[int], k: int) -> int:
ans = 0
num_to_index = {num: i for (i, num) in enumerate(nums)}
for (i, num) in enumerate(nums):
target = num + k
if target in numToIndex and numToIndex[target] != i:
ans += 1
... |
#!/usr/bin/env python3
# Day 29: Unique Paths
#
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in
# the diagram below).
# The robot can only move either down or right at any point in time. The robot
# is trying to reach the bottom-right corner of the grid.
# How many possible unique paths ... | class Solution:
def unique_paths(self, m: int, n: int) -> int:
memo = [[None for _ in range(n)] for _ in range(m)]
def compute(memo, m, n):
if memo[m][n] is not None:
return memo[m][n]
if m == 0 or n == 0:
memo[m][n] = 1
else:
... |
# Helper module for a test_reflect test
1//0
| 1 // 0 |
DEBUG = True
#SECRET_KEY = 'not a very secret key'
ADMINS = (
)
#ALLOWED_HOSTS = ["*"]
STATIC_ROOT = '/local/aplus/static/'
MEDIA_ROOT = '/local/aplus/media/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'aplus',
},
}
CACHES = {
'default': {
'BACKE... | debug = True
admins = ()
static_root = '/local/aplus/static/'
media_root = '/local/aplus/media/'
databases = {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'aplus'}}
caches = {'default': {'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/run/aplus/django-cache'}}
remote_pa... |
SAMPLE_DATASET = """HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.
22 27 97 102"""
SAMPLE_OUTPUT = "Humpty Dumpty"
def solution(dataset):
words = dataset[0]
indices = [int(indice) for indice in dataset[1].split()]
word1 = words[indic... | sample_dataset = 'HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.\n22 27 97 102'
sample_output = 'Humpty Dumpty'
def solution(dataset):
words = dataset[0]
indices = [int(indice) for indice in dataset[1].split()]
word1 = words[indices[0... |
# thingsboardwrapper/device.py
class TENANT(object):
def __init__(self):
pass
def getDevicesIds(self,base_url, session):
response = session.get(base_url +'/api/tenant/devices', params = {'limit':'100'})
json_dict = response.json()
deviceIds = []
for i in range(0, len(json_dict['data'])):
deviceIds.appe... | class Tenant(object):
def __init__(self):
pass
def get_devices_ids(self, base_url, session):
response = session.get(base_url + '/api/tenant/devices', params={'limit': '100'})
json_dict = response.json()
device_ids = []
for i in range(0, len(json_dict['data'])):
... |
def get_secret_key(BASE_DIR):
key = ''
with open(f'{BASE_DIR}/passport/private_key.pem') as secret_file:
key = secret_file.read().replace('\n', '').replace(
'-', '').replace('BEGIN RSA PRIVATE KEY', '').replace('END RSA PRIVATE KEY', '')
return key | def get_secret_key(BASE_DIR):
key = ''
with open(f'{BASE_DIR}/passport/private_key.pem') as secret_file:
key = secret_file.read().replace('\n', '').replace('-', '').replace('BEGIN RSA PRIVATE KEY', '').replace('END RSA PRIVATE KEY', '')
return key |
"""
https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
"""
| """
https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
""" |
def main():
num_words = int(input())
for _ in range(num_words):
current_word = input()
if len(current_word) > 10:
print(
f"{current_word[0]}{len(current_word) - 2}{current_word[-1]}")
else:
print(current_word)
main()
| def main():
num_words = int(input())
for _ in range(num_words):
current_word = input()
if len(current_word) > 10:
print(f'{current_word[0]}{len(current_word) - 2}{current_word[-1]}')
else:
print(current_word)
main() |
ALPHA = 0.25
PENALIZATION = 0
| alpha = 0.25
penalization = 0 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.