content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class State:
def __init__(self):
self.StateId = 0
self.StateName = ""
class City:
def __init__(self):
self.CityId = 0
self.CityName = ""
self.StateId = 0
class Properties:
def __init__(self):
self.Area=0
self.Age=0
self... | class State:
def __init__(self):
self.StateId = 0
self.StateName = ''
class City:
def __init__(self):
self.CityId = 0
self.CityName = ''
self.StateId = 0
class Properties:
def __init__(self):
self.Area = 0
self.Age = 0
self.Rooms = 0
... |
# substituindo com o metodo replace
s1 = 'Um mafagafinho, dois mafagafinhos, tres mafagafinhos...'
print(s1.replace('mafagafinho', 'gatinho'))
# podemos adicionar a quantidade substituicao que sera feitas
print(s1.replace('mafagafinho', 'gatinho', 1))
| s1 = 'Um mafagafinho, dois mafagafinhos, tres mafagafinhos...'
print(s1.replace('mafagafinho', 'gatinho'))
print(s1.replace('mafagafinho', 'gatinho', 1)) |
class Movies(object):
def __init__(self, **kwargs):
short_plot = kwargs.get('Plot')[0:170]
self.title = kwargs.get('Title')
self.poster_link = kwargs.get('Poster')
self.rated = kwargs.get('Rated')
self.type = kwargs.get('Type')
self.awards = kwargs.get('Awards')
... | class Movies(object):
def __init__(self, **kwargs):
short_plot = kwargs.get('Plot')[0:170]
self.title = kwargs.get('Title')
self.poster_link = kwargs.get('Poster')
self.rated = kwargs.get('Rated')
self.type = kwargs.get('Type')
self.awards = kwargs.get('Awards')
... |
class Solution:
def maxLength(self, arr: List[str]) -> int:
results = [""]
max_len = 0
for word in arr:
for concat_str in results:
new_str = concat_str + word
if len(new_str) == len(set(new_str)):
results.append(new_str)
... | class Solution:
def max_length(self, arr: List[str]) -> int:
results = ['']
max_len = 0
for word in arr:
for concat_str in results:
new_str = concat_str + word
if len(new_str) == len(set(new_str)):
results.append(new_str)
... |
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# The idea is to use 2D dynamic programming from the top-left
# if the characters are match,
# we set the cell = 1 + top-left
# if the characters aren't match,
# we set the ... | class Solution:
def longest_common_subsequence(self, text1: str, text2: str) -> int:
dp = [[0 for _ in range(len(text2))] for _ in range(len(text1))]
for i in range(len(text1)):
for j in range(len(text2)):
if text1[i] == text2[j]:
dp[i][j] = 1 + (dp[i... |
N=int(input())
for i in range (-(N-1),N):
for j in range (-2*(N-1),2*(N-1)+1):
if j%2==0 and (abs(j//2)+abs(i))< N:
print (chr(abs(j//2)+abs(i)+ord('a')),end='')
else:
print('-',end='')
print() | n = int(input())
for i in range(-(N - 1), N):
for j in range(-2 * (N - 1), 2 * (N - 1) + 1):
if j % 2 == 0 and abs(j // 2) + abs(i) < N:
print(chr(abs(j // 2) + abs(i) + ord('a')), end='')
else:
print('-', end='')
print() |
# coding: utf8
# try something like
def index():
rows = db((db.activity.type=='project')&(db.activity.status=='accepted')).select()
if rows:
return dict(projects=rows)
else:
return plugin_flatpage()
@auth.requires_login()
def apply():
project = db.activity[request.args(1)]
partaker... | def index():
rows = db((db.activity.type == 'project') & (db.activity.status == 'accepted')).select()
if rows:
return dict(projects=rows)
else:
return plugin_flatpage()
@auth.requires_login()
def apply():
project = db.activity[request.args(1)]
partaker = db((db.partaker.activity == ... |
N = int(input())
C = set()
for _ in range(N):
S, T = map(str, input().split())
C.add(tuple([S, T]))
if len(C) == N:
print("No")
else:
print("Yes") | n = int(input())
c = set()
for _ in range(N):
(s, t) = map(str, input().split())
C.add(tuple([S, T]))
if len(C) == N:
print('No')
else:
print('Yes') |
class DoubleLinkedList:
def __init__(self, value):
self.prev = self
self.next = self
self.value = value
def get_next(self):
return self.next
def get_prev(self):
return self.prev
def get_value(self):
return self.value
def move_clockwise(self, steps=... | class Doublelinkedlist:
def __init__(self, value):
self.prev = self
self.next = self
self.value = value
def get_next(self):
return self.next
def get_prev(self):
return self.prev
def get_value(self):
return self.value
def move_clockwise(self, steps... |
golfcube = dm.sample_data.golf()
stratcube = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.05)
stratcube.register_section('demo', dm.section.StrikeSection(distance_idx=10))
fig, ax = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(12, 9))
ax = ax.flatten()
for i, var in enumerate(['time', 'eta', 'veloci... | golfcube = dm.sample_data.golf()
stratcube = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.05)
stratcube.register_section('demo', dm.section.StrikeSection(distance_idx=10))
(fig, ax) = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(12, 9))
ax = ax.flatten()
for (i, var) in enumerate(['time', 'eta', 'velo... |
def test_malware_have_actors(attck_fixture):
"""
All MITRE Enterprise ATT&CK Malware should have Actors
Args:
attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture
"""
for malware in attck_fixture.enterprise.malwares:
if malware.actors:
assert getattr(... | def test_malware_have_actors(attck_fixture):
"""
All MITRE Enterprise ATT&CK Malware should have Actors
Args:
attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture
"""
for malware in attck_fixture.enterprise.malwares:
if malware.actors:
assert getattr(... |
__all__ = ['USBQException', 'USBQInvocationError', 'USBQDeviceNotConnected']
class USBQException(Exception):
'Base of all USBQ exceptions'
class USBQInvocationError(USBQException):
'Error invoking USBQ'
class USBQDeviceNotConnected(USBQException):
'USBQ device not connected.'
| __all__ = ['USBQException', 'USBQInvocationError', 'USBQDeviceNotConnected']
class Usbqexception(Exception):
"""Base of all USBQ exceptions"""
class Usbqinvocationerror(USBQException):
"""Error invoking USBQ"""
class Usbqdevicenotconnected(USBQException):
"""USBQ device not connected.""" |
"""
[2017-11-13] Challenge #340 [Easy] First Recurring Character
https://www.reddit.com/r/dailyprogrammer/comments/7cnqtw/20171113_challenge_340_easy_first_recurring/
# Description
Write a program that outputs the first recurring character in a string.
# Formal Inputs & Outputs
## Input Description
A string of alphab... | """
[2017-11-13] Challenge #340 [Easy] First Recurring Character
https://www.reddit.com/r/dailyprogrammer/comments/7cnqtw/20171113_challenge_340_easy_first_recurring/
# Description
Write a program that outputs the first recurring character in a string.
# Formal Inputs & Outputs
## Input Description
A string of alphab... |
def test_exposed(ua):
"""Test if the UnitAgent exposes all required methods."""
assert ua.update_forecast is ua.model.update_forecast
assert ua.init_negotiation is ua.planner.init_negotiation
assert ua.stop_negotiation is ua.planner.stop_negotiation
assert ua.set_schedule is ua.unit.set_schedule
... | def test_exposed(ua):
"""Test if the UnitAgent exposes all required methods."""
assert ua.update_forecast is ua.model.update_forecast
assert ua.init_negotiation is ua.planner.init_negotiation
assert ua.stop_negotiation is ua.planner.stop_negotiation
assert ua.set_schedule is ua.unit.set_schedule
... |
test = {
'name': 'nodots',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (nodots '(1 . 2))
(1 2)
""",
'hidden': False,
'locked': False
},
{
'code': r"""
scm> (nodots '(1 2 . 3))
... | test = {'name': 'nodots', 'points': 1, 'suites': [{'cases': [{'code': "\n scm> (nodots '(1 . 2))\n (1 2)\n ", 'hidden': False, 'locked': False}, {'code': "\n scm> (nodots '(1 2 . 3))\n (1 2 3)\n ", 'hidden': False, 'locked': False}, {'code': "\n scm> (nodot... |
# Copyright (c) 2009 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.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'security_tests',
'type': 'shared_library',
'source... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'security_tests', 'type': 'shared_library', 'sources': ['../../../sandbox/win/tests/validation_tests/commands.cc', '../../../sandbox/win/tests/validation_tests/commands.h', 'ipc_security_tests.cc', 'ipc_security_tests.h', 'security_tests.cc']}]} |
"""
generates high value cutoff filtered versions for case study 1 and 2 converted delay measurements
"""
DATA_PATHS = [
'CS1_SendFixed_50ms_JoinDupFilter',
'CS1_SendFixed_50ms_JoinNoFilter',
'CS1_SendFixed_100ms_JoinDupFilter',
'CS1_SendFixed_100ms_JoinNoFilter',
'CS1_SendVariable_50ms_JoinDupFilt... | """
generates high value cutoff filtered versions for case study 1 and 2 converted delay measurements
"""
data_paths = ['CS1_SendFixed_50ms_JoinDupFilter', 'CS1_SendFixed_50ms_JoinNoFilter', 'CS1_SendFixed_100ms_JoinDupFilter', 'CS1_SendFixed_100ms_JoinNoFilter', 'CS1_SendVariable_50ms_JoinDupFilter', 'CS1_SendVariable... |
"""
0845. Longest Mountain in Array
Medium
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the e... | """
0845. Longest Mountain in Array
Medium
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the e... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: money_dp.py
@time: 2019/4/22 23:17
@desc:
find least number of money to achieve a total amount
'''
def money_dp(total):
money = [1, 5, 11] # value of each money
number ... | """
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: money_dp.py
@time: 2019/4/22 23:17
@desc:
find least number of money to achieve a total amount
"""
def money_dp(total):
money = [1, 5, 11]
number = [0] * (total + 1)
for i in range(1, total + 1):
cos... |
class Solution:
def majorityElement(self, nums) -> int:
dic={}
for num in nums:
dic[num]=dic.get(num,0)+1
#guess,dic.get(num,0)=dic.get(num,0)+1 is non-existential,for in syntax field,we can't assign to function call
for num in nums:
i... | class Solution:
def majority_element(self, nums) -> int:
dic = {}
for num in nums:
dic[num] = dic.get(num, 0) + 1
for num in nums:
if dic.get(num, 0) >= len(nums) / 2:
return num |
class BaseAnnotationAdapter(object):
def __iter__(self):
return self
def __next__(self):
"""
Needs to be implemented in order to iterate through the annotations
:return: A tuple (leaf_annotation, image_path, i) where
leaf annotation is a list of coordina... | class Baseannotationadapter(object):
def __iter__(self):
return self
def __next__(self):
"""
Needs to be implemented in order to iterate through the annotations
:return: A tuple (leaf_annotation, image_path, i) where
leaf annotation is a list of coordina... |
[2,8,"t","pncmjxlvckfbtrjh"],
[8,9,"l","lzllllldsl"],
[3,11,"c","ccchcccccclxnkcmc"],
[3,10,"h","xcvxkdqshh"],
[4,5,"s","gssss"],
[7,14,"m","mmcmqmmxmmmnmmrmcxc"],
[3,12,"n","grnxnbsmzttnzbnnn"],
[5,9,"j","ddqwznjhjcjn"],
[8,9,"d","fddddddmd"],
[6,8,"t","qtlwttsqg"],
[7,15,"m","lxzxrdbmmtvwhgm"],
[6,10,"h","hhnhhhhxhkh... | ([2, 8, 't', 'pncmjxlvckfbtrjh'],)
([8, 9, 'l', 'lzllllldsl'],)
([3, 11, 'c', 'ccchcccccclxnkcmc'],)
([3, 10, 'h', 'xcvxkdqshh'],)
([4, 5, 's', 'gssss'],)
([7, 14, 'm', 'mmcmqmmxmmmnmmrmcxc'],)
([3, 12, 'n', 'grnxnbsmzttnzbnnn'],)
([5, 9, 'j', 'ddqwznjhjcjn'],)
([8, 9, 'd', 'fddddddmd'],)
([6, 8, 't', 'qtlwttsqg'],)
([... |
# Rename this to keys.py if running locally,
# and replace the API keys with your own information.
# This project uses an EC2 instance with
# Elasticache providing the redis broker and an
# RDS instance of postgresql.
EMAIL_HOST_USER = 'YOUR_EMAIL_ADDRESS@gmail.com'
EMAIL_HOST_PASSWORD = 'YOUR_EMAIL_PASSWORD'
SETTING... | email_host_user = 'YOUR_EMAIL_ADDRESS@gmail.com'
email_host_password = 'YOUR_EMAIL_PASSWORD'
settings_key = 'YOUR_SETTINGS_KEY'
site_url = 'LOCALHOST_OR_YOUR_URL'
twilio_sid = 'YOUR_TWILIO_SID'
twilio_token = 'YOUR_TWILIO_TOKEN'
server_number = 'YOUR_TWILIO_NUMBER'
twilio_callback_url = 'http://YOUR_SITE_URL.com/api/ca... |
a = [2, 3]
for n in range(5, 10 ** 7, 2):
i = 1
while a[i] <= n ** .5:
if n % a[i] == 0:
break
i = i + 1
else:
a.append(n)
print(a)
| a = [2, 3]
for n in range(5, 10 ** 7, 2):
i = 1
while a[i] <= n ** 0.5:
if n % a[i] == 0:
break
i = i + 1
else:
a.append(n)
print(a) |
# Time: O(n + m), m is the number of targets
# Space: O(n)
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
... | class Solution(object):
def find_replace_string(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
s = list(S)
bucket = [None] * len(S)
for i... |
"""
The Procedure to add new version:
1.New Version created
2.Add the new version to GATHER_COMMANDS_VERSION dictionary
3.Ask the developer about new files on new version
4.Add file names to relevant list
OCS4.6 Link:
https://github.com/openshift/ocs-operator/blob/fefc8a0e04e314801809df2e5292a20fae8456b8/must-gather/c... | """
The Procedure to add new version:
1.New Version created
2.Add the new version to GATHER_COMMANDS_VERSION dictionary
3.Ask the developer about new files on new version
4.Add file names to relevant list
OCS4.6 Link:
https://github.com/openshift/ocs-operator/blob/fefc8a0e04e314801809df2e5292a20fae8456b8/must-gather/c... |
def extract_coupon(description):
coupon = ''
for s in range(len(description)):
if description[s].isnumeric() or description[s] == '.':
coupon = coupon + description[s]
#print(c)
if description[s] == '%':
break
try:
float(coupon)
except:
... | def extract_coupon(description):
coupon = ''
for s in range(len(description)):
if description[s].isnumeric() or description[s] == '.':
coupon = coupon + description[s]
if description[s] == '%':
break
try:
float(coupon)
except:
coupon = coupon[1:]
... |
key = [int(num) for num in input().split()]
data = input()
length = len(key)
results_dict = {}
while not data == 'find':
message = ""
counter = 0
for el in data:
if counter == length:
counter = 0
asc = ord(el)
asc -= key[counter]
ord_asc = chr(asc)
messag... | key = [int(num) for num in input().split()]
data = input()
length = len(key)
results_dict = {}
while not data == 'find':
message = ''
counter = 0
for el in data:
if counter == length:
counter = 0
asc = ord(el)
asc -= key[counter]
ord_asc = chr(asc)
message... |
# use the with key word to open file ass mb_object
with open("mbox-short.txt", "r") as mb_object:
# Iterate over each line and remove leading spaces;
# print contents after converting them to uppercase
for line in mb_object:
line = line.strip()
print(line.upper()) | with open('mbox-short.txt', 'r') as mb_object:
for line in mb_object:
line = line.strip()
print(line.upper()) |
################
# First class functions allow us to treat functions as any other variables or objects
# Closures are functions that are local inner functions within outer functions that remember the arguments passed to the outer functions
#################
def square(x):
return x*x
def my_map_function(func , arg_l... | def square(x):
return x * x
def my_map_function(func, arg_list):
result = []
for item in arg_list:
result.append(func(item))
return result
int_array = [1, 2, 3, 4, 5]
f = my_map_function(square, int_array)
def logger(msg):
def log_message():
print('Log:', msg)
return log_messa... |
class AbstractPlayer:
def __init__(self):
raise NotImplementedError()
def explain(self, word, n_words):
raise NotImplementedError()
def guess(self, words, n_words):
raise NotImplementedError()
class LocalDummyPlayer(AbstractPlayer):
def __init__(self):
pass
def e... | class Abstractplayer:
def __init__(self):
raise not_implemented_error()
def explain(self, word, n_words):
raise not_implemented_error()
def guess(self, words, n_words):
raise not_implemented_error()
class Localdummyplayer(AbstractPlayer):
def __init__(self):
pass
... |
""" 1108. Defanging an IP Address
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Con... | """ 1108. Defanging an IP Address
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Con... |
# Acesso as elementos da tupla
numeros = 1,2,3,5,7,11
print(numeros[0])
print(numeros[1])
print(numeros[2])
print(numeros[3])
print(numeros[4])
print(numeros[5]) | numeros = (1, 2, 3, 5, 7, 11)
print(numeros[0])
print(numeros[1])
print(numeros[2])
print(numeros[3])
print(numeros[4])
print(numeros[5]) |
__title__ = 'contactTree-api'
__package_name = 'contactTree-api'
__version__ = '0.1.0'
__description__ = ''
__author__ = 'Dionisis Pettas'
__email__ = ''
__github__ = 'https://github.com/deepettas/contact-tree'
__licence__ = 'MIT' | __title__ = 'contactTree-api'
__package_name = 'contactTree-api'
__version__ = '0.1.0'
__description__ = ''
__author__ = 'Dionisis Pettas'
__email__ = ''
__github__ = 'https://github.com/deepettas/contact-tree'
__licence__ = 'MIT' |
def add_native_methods(clazz):
def nOpen__int__(a0, a1):
raise NotImplementedError()
def nClose__long__(a0, a1):
raise NotImplementedError()
def nSendShortMessage__long__int__long__(a0, a1, a2, a3):
raise NotImplementedError()
def nSendLongMessage__long__byte____int__long__(a0... | def add_native_methods(clazz):
def n_open__int__(a0, a1):
raise not_implemented_error()
def n_close__long__(a0, a1):
raise not_implemented_error()
def n_send_short_message__long__int__long__(a0, a1, a2, a3):
raise not_implemented_error()
def n_send_long_message__long__byte___... |
"""
django:
https://docs.djangoproject.com/en/3.0/ref/settings/#allowed-hosts
https://docs.djangoproject.com/en/3.0/ref/settings/#internal-ips
"""
ALLOWED_HOSTS = "*"
INTERNAL_IPS = ("127.0.0.1", "localhost", "172.18.0.1")
| """
django:
https://docs.djangoproject.com/en/3.0/ref/settings/#allowed-hosts
https://docs.djangoproject.com/en/3.0/ref/settings/#internal-ips
"""
allowed_hosts = '*'
internal_ips = ('127.0.0.1', 'localhost', '172.18.0.1') |
i = 4 # variation on testWhile.py
while (i < 9):
i = i+2
print(i)
| i = 4
while i < 9:
i = i + 2
print(i) |
"""TODO
Ecrire un paquet de tools
Ecrire un outil XSS
Ecrire un README avec https://github.com/RichardLitt/standard-readme/blob/master/README.md
Completer touts les script avec PayloadAllTheThing pour ajouter des payloads a chaque exploit
Rassembler toutes les LFI dans une classe / pareil pour les RFI
-Faire un analyse... | """TODO
Ecrire un paquet de tools
Ecrire un outil XSS
Ecrire un README avec https://github.com/RichardLitt/standard-readme/blob/master/README.md
Completer touts les script avec PayloadAllTheThing pour ajouter des payloads a chaque exploit
Rassembler toutes les LFI dans une classe / pareil pour les RFI
-Faire un analyse... |
class RelayOutput:
def enable_relay(self, name: str):
pass
def reset(self):
pass
| class Relayoutput:
def enable_relay(self, name: str):
pass
def reset(self):
pass |
'''
Create a tuple with some words. Show for each word its vowels.
'''
vowels = ('a', 'e', 'i', 'o', 'u')
words = (
'Learn', 'Programming', 'Language', 'Python', 'Course', 'Free',
'Study', 'Practice', 'Work', 'Market', 'Programmer', 'Future'
)
for word in words:
print(f'\nThe word \033[34m{word}\033[... | """
Create a tuple with some words. Show for each word its vowels.
"""
vowels = ('a', 'e', 'i', 'o', 'u')
words = ('Learn', 'Programming', 'Language', 'Python', 'Course', 'Free', 'Study', 'Practice', 'Work', 'Market', 'Programmer', 'Future')
for word in words:
print(f'\nThe word \x1b[34m{word}\x1b[m contains', ... |
f = open('surf.txt')
maior = 0
for linha in f:
nome, pontos = linha.split()
if float(pontos) > maior:
maior = float(pontos)
f.close()
print (maior)
| f = open('surf.txt')
maior = 0
for linha in f:
(nome, pontos) = linha.split()
if float(pontos) > maior:
maior = float(pontos)
f.close()
print(maior) |
""" errors module """
class PyungoError(Exception):
""" pyungo custom exception """
pass
| """ errors module """
class Pyungoerror(Exception):
""" pyungo custom exception """
pass |
#!/usr/bin.env python
# Copyright (C) Pearson Assessments - 2020. All Rights Reserved.
# Proprietary - Use with Pearson Written Permission Only
memo = {}
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
... | memo = {}
class Solution(object):
def word_break(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
if s in memo:
return memo[s]
if len(s) == 0:
return False
if len(s) == 1:
return s in... |
'''https://leetcode.com/problems/palindrome-linked-list/'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Solution 1
# Time Complexity - O(n)
# Space Complexity - O(n)
class Solution:
def isPalindrome(self, head: ListNode) -... | """https://leetcode.com/problems/palindrome-linked-list/"""
class Solution:
def is_palindrome(self, head: ListNode) -> bool:
s = []
while head:
s += [head.val]
head = head.next
return s == s[::-1]
class Solution:
def is_palindrome(self, head: ListNode) -> bool... |
def calculate(**kwargs):
operation_lookup = {
'add': kwargs.get('first', 0) + kwargs.get('second', 0),
'subtract': kwargs.get('first', 0) - kwargs.get('second', 0),
'divide': kwargs.get('first', 0) / kwargs.get('second', 1),
'multiply': kwargs.get('first', 0) * kwargs.get('second', ... | def calculate(**kwargs):
operation_lookup = {'add': kwargs.get('first', 0) + kwargs.get('second', 0), 'subtract': kwargs.get('first', 0) - kwargs.get('second', 0), 'divide': kwargs.get('first', 0) / kwargs.get('second', 1), 'multiply': kwargs.get('first', 0) * kwargs.get('second', 0)}
is_float = kwargs.get('mak... |
# ---------------------------------------------------------------------------------------
#
# Title: Permutations
#
# Link: https://leetcode.com/problems/permutations/
#
# Difficulty: Medium
#
# Language: Python
#
# -----------------------------------------------------------------------------------... | class Permutations:
def permute(self, nums):
return self.phelper(nums, [], [])
def phelper(self, nums, x, y):
for i in nums:
if i not in x:
x.append(i)
if len(x) == len(nums):
y.append(x.copy())
else:
... |
"""Top-level package for nesc-coo."""
__author__ = """Betterme"""
__email__ = 'yuanjie@example.com'
__version__ = '0.0.0'
| """Top-level package for nesc-coo."""
__author__ = 'Betterme'
__email__ = 'yuanjie@example.com'
__version__ = '0.0.0' |
"""APIv3-specific CLI settings
"""
__all__ = []
# Abaco settings
# Aloe settings
# Keys settings
| """APIv3-specific CLI settings
"""
__all__ = [] |
'''
modifier: 01
eqtime: 25
'''
def main():
info('Jan Air Script x1')
gosub('jan:WaitForMiniboneAccess')
gosub('jan:PrepareForAirShot')
gosub('jan:EvacPipette2')
gosub('common:FillPipette2')
gosub('jan:PrepareForAirShotExpansion')
gosub('common:ExpandPipette2')
| """
modifier: 01
eqtime: 25
"""
def main():
info('Jan Air Script x1')
gosub('jan:WaitForMiniboneAccess')
gosub('jan:PrepareForAirShot')
gosub('jan:EvacPipette2')
gosub('common:FillPipette2')
gosub('jan:PrepareForAirShotExpansion')
gosub('common:ExpandPipette2') |
def SaveOrder(orderDict):
file = open("orderLog.txt", 'w')
total = 0
for item, price in orderDict.items():
file.write(item+'-->'+str(price)+'\n')
total += price
file.write('Total = '+str(total))
file.close()
def main():
order = {
'Pizza':100,
'Snak... | def save_order(orderDict):
file = open('orderLog.txt', 'w')
total = 0
for (item, price) in orderDict.items():
file.write(item + '-->' + str(price) + '\n')
total += price
file.write('Total = ' + str(total))
file.close()
def main():
order = {'Pizza': 100, 'Snaks': 200, 'Pasta': 50... |
# Generator A starts with 783
# Generator B starts with 325
REAL_START=[783, 325]
SAMPLE_START=[65, 8921]
FACTORS=[16807, 48271]
DIVISOR=2147483647 # 0b1111111111111111111111111111111 2^31
def next_a_value(val, factor):
while True:
val = (val * factor) % DIVISOR
if val & 3 == 0:
return ... | real_start = [783, 325]
sample_start = [65, 8921]
factors = [16807, 48271]
divisor = 2147483647
def next_a_value(val, factor):
while True:
val = val * factor % DIVISOR
if val & 3 == 0:
return val
def next_b_value(val, factor):
while True:
val = val * factor % DIVISOR
... |
# -*- coding: utf-8 -*-
class ArgumentTypeError(TypeError):
pass
class ArgumentValueError(ValueError):
pass
| class Argumenttypeerror(TypeError):
pass
class Argumentvalueerror(ValueError):
pass |
"""
Manage stakeholders like a pro!
"""
__author__ = "critical-path"
__version__ = "0.1.6"
| """
Manage stakeholders like a pro!
"""
__author__ = 'critical-path'
__version__ = '0.1.6' |
# VALIDAR SE A CIDADE DIGITADA INICIA COM O NOME SANTO:
cidade = str(input('Digite a cidade em que nasceu... ')).strip()
print(cidade[:5].upper() == 'SANTO')
| cidade = str(input('Digite a cidade em que nasceu... ')).strip()
print(cidade[:5].upper() == 'SANTO') |
ls = list(map(int, input().split()))
count = 0
for i in ls:
if ls[i] == 1:
count += 1
print(count)
| ls = list(map(int, input().split()))
count = 0
for i in ls:
if ls[i] == 1:
count += 1
print(count) |
def abc(a,b,c):
for i in a:
b(a)
if c():
if b(a) > 100:
b(a)
elif 100 > 0:
b(a)
else:
b(a)
else:
b(100)
return 100
def ex():
try:
fh = open("testfile", "w")
fh.write("a")
except IOError:
print("b... | def abc(a, b, c):
for i in a:
b(a)
if c():
if b(a) > 100:
b(a)
elif 100 > 0:
b(a)
else:
b(a)
else:
b(100)
return 100
def ex():
try:
fh = open('testfile', 'w')
fh.write('a')
except IOError:
print(... |
# 4. Write a Python program to check a list is empty or not. Take few lists with one of them empty.
fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana']
fruits1 = []
fruits2 = ['mango', 'strawberry', 'peach']
# print (fruits[3])
# print (fruits[-2])
# print (fruits[1])
# #
# print (fruits[0])
# print (fruits)
#
# f... | fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana']
fruits1 = []
fruits2 = ['mango', 'strawberry', 'peach']
fruits.append('apple')
fruits.append('banana')
fruits.append('pear')
fruits.append('cherry')
print(fruits)
fruits.append('apple')
fruits.append('banana')
fruits.append('pear')
fruits.append('cherry')
print(fr... |
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = [i for i in str(x)]
y.reverse()
try:
y = int(''.join(y))
except ValueError:
pass
return x == y
| class Solution:
def is_palindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = [i for i in str(x)]
y.reverse()
try:
y = int(''.join(y))
except ValueError:
pass
return x == y |
include("common.py")
def cyanamidationGen():
r = RuleGen("Cyanamidation")
r.left.extend([
'# H2NCN',
'edge [ source 0 target 1 label "#" ]',
'# The other',
'edge [ source 105 target 150 label "-" ]',
])
r.context.extend([
'# H2NCN',
'node [ id 0 label "N" ]',
'node [ id 1 label "C" ]',
'node [ id 2... | include('common.py')
def cyanamidation_gen():
r = rule_gen('Cyanamidation')
r.left.extend(['# H2NCN', 'edge [ source 0 target 1 label "#" ]', '# The other', 'edge [ source 105 target 150 label "-" ]'])
r.context.extend(['# H2NCN', 'node [ id 0 label "N" ]', 'node [ id 1 label "C" ]', 'node [ id 2 label "N"... |
number = int(input())
divider = number // 2
numbers = ''
while divider != 1:
if 0 == number % divider:
numbers += " " + str(divider)
divider -= 1
if 0 == len(numbers):
print('Prime Number')
else:
print(numbers[1:])
| number = int(input())
divider = number // 2
numbers = ''
while divider != 1:
if 0 == number % divider:
numbers += ' ' + str(divider)
divider -= 1
if 0 == len(numbers):
print('Prime Number')
else:
print(numbers[1:]) |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
return reduce(lambda x, y: x + [i + [y] for i in x], nums, [[]])
| class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
return reduce(lambda x, y: x + [i + [y] for i in x], nums, [[]]) |
HEARTBEAT = "0"
TESTREQUEST = "1"
RESENDREQUEST = "2"
REJECT = "3"
SEQUENCERESET = "4"
LOGOUT = "5"
IOI = "6"
ADVERTISEMENT = "7"
EXECUTIONREPORT = "8"
ORDERCANCELREJECT = "9"
QUOTESTATUSREQUEST = "a"
LOGON = "A"
DERIVATIVESECURITYLIST = "AA"
NEWORDERMULTILEG = "AB"
MULTILEGORDERCANCELREPLACE = "AC"
TRADECAPTUREREPORTR... | heartbeat = '0'
testrequest = '1'
resendrequest = '2'
reject = '3'
sequencereset = '4'
logout = '5'
ioi = '6'
advertisement = '7'
executionreport = '8'
ordercancelreject = '9'
quotestatusrequest = 'a'
logon = 'A'
derivativesecuritylist = 'AA'
newordermultileg = 'AB'
multilegordercancelreplace = 'AC'
tradecapturereportr... |
# Given two integers, swap them with no additional variable
# 1. With temporal variable t
def swap(a,b):
t = b
a = b
b = t
return a, b
# 2. With no variable
def swap(a,b):
a = b - a
b = b - a # b = b -(b-a) = a
a = b + a # b = a + b - a = b...Swapped
return a, b
... | def swap(a, b):
t = b
a = b
b = t
return (a, b)
def swap(a, b):
a = b - a
b = b - a
a = b + a
return (a, b)
def swap(a, b):
a = a ^ b
b = a ^ b
a = b ^ a
return (a, b) |
# Time: O(n)
# Space: O(1)
# dp
class Solution(object):
def minimumTime(self, s):
"""
:type s: str
:rtype: int
"""
left = 0
result = left+(len(s)-0)
for i in xrange(1, len(s)+1):
left = min(left+2*(s[i-1] == '1'), i)
result = min(resu... | class Solution(object):
def minimum_time(self, s):
"""
:type s: str
:rtype: int
"""
left = 0
result = left + (len(s) - 0)
for i in xrange(1, len(s) + 1):
left = min(left + 2 * (s[i - 1] == '1'), i)
result = min(result, left + (len(s) -... |
class Solution:
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
res, cur = set(), set()
for x in A:
cur = {x | y for y in cur} | {x}
res |= cur
return len(res)
| class Solution:
def subarray_bitwise_o_rs(self, A):
"""
:type A: List[int]
:rtype: int
"""
(res, cur) = (set(), set())
for x in A:
cur = {x | y for y in cur} | {x}
res |= cur
return len(res) |
def merge_sort(sorting_list):
"""
Sorts a list in ascending order
Returns a new sorted list
Divide: Find the midpoint of the list and divide into sublist
Conquer: Recursively sort the sublist created in previous step
Combine: Merge the sorted sublist created in previous step
Takes... | def merge_sort(sorting_list):
"""
Sorts a list in ascending order
Returns a new sorted list
Divide: Find the midpoint of the list and divide into sublist
Conquer: Recursively sort the sublist created in previous step
Combine: Merge the sorted sublist created in previous step
Takes O(n log ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 11:21:27 2016
@author: ericgrimson
"""
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
print(mysum)
| """
Created on Wed Jun 8 11:21:27 2016
@author: ericgrimson
"""
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
print(mysum) |
# coding: utf-8
def test_default_value(printer):
assert printer._inverse is False
def test_changing_no_value(printer):
printer.inverse()
assert printer._inverse is False
def test_changing_state_on(printer):
printer.inverse(True)
assert printer._inverse is True
def test_changing_state_off(pri... | def test_default_value(printer):
assert printer._inverse is False
def test_changing_no_value(printer):
printer.inverse()
assert printer._inverse is False
def test_changing_state_on(printer):
printer.inverse(True)
assert printer._inverse is True
def test_changing_state_off(printer):
printer.in... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class RenameObjectParamProto(object):
"""Implementation of the 'RenameObjectParamProto' model.
Message to specify the prefix/suffix added to rename an object. At least
one
of prefix or suffix must be specified. Please note that both prefix and
... | class Renameobjectparamproto(object):
"""Implementation of the 'RenameObjectParamProto' model.
Message to specify the prefix/suffix added to rename an object. At least
one
of prefix or suffix must be specified. Please note that both prefix and
suffix can be specified.
Attributes:
prefi... |
# program to merge two linked list
class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def merge(L1,L2):
L3 = Node(None, None)
prev = L3
while L1 != None and L2 != None:
if L1.data <= L2.data:
prev.next = L2.data
... | class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def merge(L1, L2):
l3 = node(None, None)
prev = L3
while L1 != None and L2 != None:
if L1.data <= L2.data:
prev.next = L2.data
l1 = L1.next
else:
prev.data ... |
local_webserver = '/var/www/html'
ssh = dict(
host = '',
username = '',
password = '',
remote_path = ''
)
| local_webserver = '/var/www/html'
ssh = dict(host='', username='', password='', remote_path='') |
class FibIterator(object):
def __init__(self, n):
self.n = n
self.current = 0
self.num1 = 0
self.num2 = 1
def __next__(self):
if self.current < self.n:
item = self.num1
self.num1, self.num2 = self.num2, self.num1+self.num2
self.current... | class Fibiterator(object):
def __init__(self, n):
self.n = n
self.current = 0
self.num1 = 0
self.num2 = 1
def __next__(self):
if self.current < self.n:
item = self.num1
(self.num1, self.num2) = (self.num2, self.num1 + self.num2)
self.... |
cpgf._import(None, "builtin.debug");
cpgf._import(None, "builtin.core");
class SAppContext:
device = None,
counter = 0,
listbox = None
Context = SAppContext();
GUI_ID_QUIT_BUTTON = 101;
GUI_ID_NEW_WINDOW_BUTTON = 102;
GUI_ID_FILE_OPEN_BUTTON = 103;
GUI_ID_TRANSPARENCY_SCROLL_BAR = 104;
def makeM... | cpgf._import(None, 'builtin.debug')
cpgf._import(None, 'builtin.core')
class Sappcontext:
device = (None,)
counter = (0,)
listbox = None
context = s_app_context()
gui_id_quit_button = 101
gui_id_new_window_button = 102
gui_id_file_open_button = 103
gui_id_transparency_scroll_bar = 104
def make_my_event_re... |
"""
The api endpoint paths stored as constants
"""
PLACE_ORDER = 'PlaceOrder'
MODIFY_ORDER = 'ModifyOrder'
CANCEL_ORDER = 'CancelOrder'
EXIT_SNO_ORDER = 'ExitSNOOrder'
GET_ORDER_MARGIN = 'GetOrderMargin'
GET_BASKET_MARGIN = 'GetBasketMargin'
ORDER_BOOK = 'OrderBook'
MULTILEG_ORDER_BOOK = 'MultiLegOrderBook'
SINGLE_ORD... | """
The api endpoint paths stored as constants
"""
place_order = 'PlaceOrder'
modify_order = 'ModifyOrder'
cancel_order = 'CancelOrder'
exit_sno_order = 'ExitSNOOrder'
get_order_margin = 'GetOrderMargin'
get_basket_margin = 'GetBasketMargin'
order_book = 'OrderBook'
multileg_order_book = 'MultiLegOrderBook'
single_orde... |
class SoftplusParams:
__slots__ = ["beta"]
def __init__(self, beta=100):
self.beta = beta
class GeometricInitParams:
__slots__ = ["bias"]
def __init__(self, bias=0.6):
self.bias = bias
class IDRHyperParams:
def __init__(self, softplus=None, geometric_init=None):
self.so... | class Softplusparams:
__slots__ = ['beta']
def __init__(self, beta=100):
self.beta = beta
class Geometricinitparams:
__slots__ = ['bias']
def __init__(self, bias=0.6):
self.bias = bias
class Idrhyperparams:
def __init__(self, softplus=None, geometric_init=None):
self.sof... |
# Coin Change 8
class Solution:
def change(self, amount, coins):
# Classic DP problem?
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for am in range(1, amount + 1):
if am >= coin:
dp[am] += dp[am - coin]
return dp[amoun... | class Solution:
def change(self, amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for am in range(1, amount + 1):
if am >= coin:
dp[am] += dp[am - coin]
return dp[amount]
if __name__ == '__main__':
sol = solutio... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
if root is None or root.val < val:
node = TreeNode(val)
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def insert_into_max_tree(self, root: TreeNode, val: int) -> TreeNode:
if root is None or root.val < val:
node = tree_node(val)
node.left = root
... |
#-------------------------------------------------------------
# Name: Michael Dinh
# Date: 10/10/2018
# Reference: Pg. 169, Problem #6
# Title: Book Club Points
# Inputs: User inputs number of books bought from a store
# Processes: Determines point value based on number of books bought
# Outputs: Number of points user... | def get_books():
books = int(input("Welcome to the Serendipity Booksellers Book Club Awards Points Calculator! Please enter the number of books you've purchased today: "))
return books
def det_points(books):
if books < 1:
print("You've earned 0 points; buy at least one book to qualify!")
elif b... |
def arraypermute(collection, key):
return [ str(i) + str(j) for i in collection for j in key ]
class FilterModule(object):
def filters(self):
return {
'arraypermute': arraypermute
} | def arraypermute(collection, key):
return [str(i) + str(j) for i in collection for j in key]
class Filtermodule(object):
def filters(self):
return {'arraypermute': arraypermute} |
#
# PySNMP MIB module SNIA-SML-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNIA-SML-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if dic.get(target - nums[i]) is not None:
return [dic[target - nums[i]], i]
dic[nums[i]] = i
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if dic.get(target - nums[i]) is not None:
return [dic[target - nums[i]], i]
dic[nums[i]] = i |
"""
LeetCode #561:
https://leetcode.com/problems/array-partition-i/description/
"""
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])
| """
LeetCode #561:
https://leetcode.com/problems/array-partition-i/description/
"""
class Solution(object):
def array_pair_sum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2]) |
#!/usr/bin/env python3
ARP = [
{'mac_addr': '0062.ec29.70fe', 'ip_addr': '10.220.88.1', 'interface': 'gi0/0/0'},
{'mac_addr': 'c89c.1dea.0eb6', 'ip_addr': '10.220.88.20', 'interface': 'gi0/0/0'},
{'mac_addr': 'a093.5141.b780', 'ip_addr': '10.220.88.22', 'interface': 'gi0/0/0'},
{'mac_addr': '0001.00ff.0001', 'ip_addr... | arp = [{'mac_addr': '0062.ec29.70fe', 'ip_addr': '10.220.88.1', 'interface': 'gi0/0/0'}, {'mac_addr': 'c89c.1dea.0eb6', 'ip_addr': '10.220.88.20', 'interface': 'gi0/0/0'}, {'mac_addr': 'a093.5141.b780', 'ip_addr': '10.220.88.22', 'interface': 'gi0/0/0'}, {'mac_addr': '0001.00ff.0001', 'ip_addr': '10.220.88.37', 'interf... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "Script/FocusSlide.js", "southidc")
whatweb.recog_from_content(pluginname, "southidc")
whatweb.recog_from_file(pluginname,"Script/Html.js", "southidc")
| def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, 'Script/FocusSlide.js', 'southidc')
whatweb.recog_from_content(pluginname, 'southidc')
whatweb.recog_from_file(pluginname, 'Script/Html.js', 'southidc') |
'''
width search
Explore all of the neighbors nodes at the present depth '''
three_d_array = [[[i for k in range(4)] for j in range(4)] for i in range(4)]
sum = three_d_array[1][2][3] + three_d_array[2][3][1] + three_d_array[0][0][0]
print(sum) | """
width search
Explore all of the neighbors nodes at the present depth """
three_d_array = [[[i for k in range(4)] for j in range(4)] for i in range(4)]
sum = three_d_array[1][2][3] + three_d_array[2][3][1] + three_d_array[0][0][0]
print(sum) |
class MapperError(Exception):
"""Broken mapper configuration error."""
pass
| class Mappererror(Exception):
"""Broken mapper configuration error."""
pass |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
5
5
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
root = n = ListNode(0)
carry = 0
sum = 0
... | """
5
5
"""
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
root = n = list_node(0)
carry = 0
sum = 0
while l1 or l2 or carry > 0:
if l1:
sum += l1.val
l1 = l1.next
if l2:
... |
def txt_category_to_dict(category_str):
"""
Parameters
----------
category_str: str of nominal values from dataset meta information
Returns
-------
dict of the nominal values and their one letter encoding
Example
-------
"bell=b, convex=x" -> {"bell": "b", "convex":... | def txt_category_to_dict(category_str):
"""
Parameters
----------
category_str: str of nominal values from dataset meta information
Returns
-------
dict of the nominal values and their one letter encoding
Example
-------
"bell=b, convex=x" -> {"bell": "b", "convex": "x"}
""... |
"""
Web fragments.
"""
__version__ = '0.3.2'
default_app_config = 'web_fragments.apps.WebFragmentsConfig' # pylint: disable=invalid-name
| """
Web fragments.
"""
__version__ = '0.3.2'
default_app_config = 'web_fragments.apps.WebFragmentsConfig' |
def f(x):
print('a')
y = x
print('b')
while y > 0:
print('c')
y -= 1
print('d')
yield y
print('e')
print('f')
return None
for val in f(3):
print(val)
#gen = f(3)
#print(gen)
#print(gen.__next__())
#print(gen.__next__())
#print(gen.__next__())
#print(... | def f(x):
print('a')
y = x
print('b')
while y > 0:
print('c')
y -= 1
print('d')
yield y
print('e')
print('f')
return None
for val in f(3):
print(val)
print(repr(f(0))[0:17])
print('PASS') |
file = open("test/TopCompiler/"+input("filename: "), mode= "w")
sizeOfFunc = input("size of func: ")
lines = input("lines of code: ")
out = []
for i in range(int(int(lines) / int(sizeOfFunc)+2)):
out.append("def func"+str(i)+"() =\n")
for c in range(int(sizeOfFunc)):
out.append(' println "hello worl... | file = open('test/TopCompiler/' + input('filename: '), mode='w')
size_of_func = input('size of func: ')
lines = input('lines of code: ')
out = []
for i in range(int(int(lines) / int(sizeOfFunc) + 2)):
out.append('def func' + str(i) + '() =\n')
for c in range(int(sizeOfFunc)):
out.append(' println "he... |
#! /usr/bin/env python3
'''
Disjoint Set Class that provides basic functionality.
Implemented according the functionality provided here:
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
@author: Paul Miller (github.com/138paulmiller)
'''
class DisjointSet:
'''
Disjoint Set : Utility class that helps implem... | """
Disjoint Set Class that provides basic functionality.
Implemented according the functionality provided here:
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
@author: Paul Miller (github.com/138paulmiller)
"""
class Disjointset:
"""
Disjoint Set : Utility class that helps implement Kruskal MST algo... |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | """
:mod:`MDAnalysis.analysis` --- Analysis code based on MDAnalysis
================================================================
The :mod:`MDAnalysis.analysis` sub-package contains various recipes and
algorithms that can be used to analyze MD trajectories.
If you use them please check if the documentation mentio... |
#!/usr/bin/python
# https://code.google.com/codejam/contest/2933486/dashboard
# application of insertion sort
N = int(input().strip())
for i in range(N):
M = int(input().strip())
deck = []
count = 0
for j in range(M):
deck.append(input().strip())
p = 0
for k in range(len(deck)):
if k > 0 and deck[k]... | n = int(input().strip())
for i in range(N):
m = int(input().strip())
deck = []
count = 0
for j in range(M):
deck.append(input().strip())
p = 0
for k in range(len(deck)):
if k > 0 and deck[k] < deck[p]:
count += 1
else:
p = k
print(f'Case #{i + ... |
def sum(arr: list, start: int, end: int)->int:
if start > end:
return 0
elif start == end:
return arr[start]
else:
midpoint: int = int(start + (end - start) / 2)
return sum(arr, start, midpoint) + sum(arr, midpoint + 1, end)
numbers1: list = []
numbers2: list =... | def sum(arr: list, start: int, end: int) -> int:
if start > end:
return 0
elif start == end:
return arr[start]
else:
midpoint: int = int(start + (end - start) / 2)
return sum(arr, start, midpoint) + sum(arr, midpoint + 1, end)
numbers1: list = []
numbers2: list = [1]
numbers3... |
class Car:
def __init__(self, pMake, pModel, pColor, pPrice):
self.make = pMake
self.model = pModel
self.color = pColor
self.price = pPrice
def __str__(self):
return 'Make = %s, Model = %s, Color = %s, Price = %s' %(self.make, self.model, self.color, self.price)
... | class Car:
def __init__(self, pMake, pModel, pColor, pPrice):
self.make = pMake
self.model = pModel
self.color = pColor
self.price = pPrice
def __str__(self):
return 'Make = %s, Model = %s, Color = %s, Price = %s' % (self.make, self.model, self.color, self.price)
d... |
class SimpleTreeNode:
def __init__(self, val, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
class AdvanceTreeNode:
def __init__(self, val, parent=None, left=None, right=None) -> None:
self.val = val
self.parent: AdvanceTreeNode = par... | class Simpletreenode:
def __init__(self, val, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
class Advancetreenode:
def __init__(self, val, parent=None, left=None, right=None) -> None:
self.val = val
self.parent: AdvanceTreeNode = pa... |
#
# PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:08:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
name = 'Bob'
if name == 'Alice':
print('Hi Alice')
print('Done')
| name = 'Bob'
if name == 'Alice':
print('Hi Alice')
print('Done') |
def tup(name, len):
ret = '('
for i in range(len):
ret += f'{name}{i}, '
return ret + ')'
for i in range(10):
print(
f'impl_unzip!({tup("T",i)}, {tup("A",i)}, {tup("s",i)}, {tup("t",i)});')
| def tup(name, len):
ret = '('
for i in range(len):
ret += f'{name}{i}, '
return ret + ')'
for i in range(10):
print(f"impl_unzip!({tup('T', i)}, {tup('A', i)}, {tup('s', i)}, {tup('t', i)});") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.