content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def swap(array,i,j): #this simply swaps the values
array[i],array[j]=array[j],array[i]
'''HeapifyMax function, our root node is at index i. We will first assume that
the value at index 'i' is the largest. Then we will find index of left and right child.
Then we will check if left and right child exist or not.Now... | def swap(array, i, j):
(array[i], array[j]) = (array[j], array[i])
'HeapifyMax function, our root node is at index i. We will first assume that \nthe value at index \'i\' is the largest. Then we will find index of left and right child.\nThen we will check if left and right child exist or not.Now, we will compare ou... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def maxSumDivThree(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0, 0, 0]
for num in nums:
for i in [num+x for x in dp]:
dp[i%3] = max(dp[i%3], i)
return dp[0]
| class Solution(object):
def max_sum_div_three(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0, 0, 0]
for num in nums:
for i in [num + x for x in dp]:
dp[i % 3] = max(dp[i % 3], i)
return dp[0] |
# https://app.codesignal.com/arcade/intro/level-5/g6dc9KJyxmFjB98dL
def areEquallyStrong(your_left, your_right, friends_left, friends_right):
# Two arms are equally strong if the heaviest weights they each are
# able to lift are equal. Two people are equally strong if their
# strongest arms are equally stro... | def are_equally_strong(your_left, your_right, friends_left, friends_right):
my_max = max(your_left, your_right)
my_min = min(your_left, your_right)
fr_max = max(friends_left, friends_right)
fr_min = min(friends_left, friends_right)
return my_max == fr_max and my_min == fr_min |
# Source : https://leetcode.com/problems/4sum/
# Author : YipingPan
# Date : 2020-08-16
#####################################################################################################
#
# Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums
# such that a + b + c ... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
dic = collections.defaultdict(list)
for i in range(len(nums)):
for j in range(len(nums)):
if i < j:
dic[nums[i] + nums[j]].append([i, j])
res = set()
... |
dict_rhythms = {
"E(2,3)" : "A common Afro-Cuban drum pattern when started on the second onset as in [101]. For example, it is the conga rhythm of the (6/8)-time Swing Tumbao. It is common in Latin American music, as for example in the Cueca, and the coros de clave. It is common in Arabic music, as for example in the... | dict_rhythms = {'E(2,3)': 'A common Afro-Cuban drum pattern when started on the second onset as in [101]. For example, it is the conga rhythm of the (6/8)-time Swing Tumbao. It is common in Latin American music, as for example in the Cueca, and the coros de clave. It is common in Arabic music, as for example in the Al ... |
def fun(a, b):
return 1
fun(1, 2)
| def fun(a, b):
return 1
fun(1, 2) |
# Create a program to check if an integer is a perfect square.
# 4, 9, 25 any ideas? Use Square Root
# input
num = int(input('Enter a value: '))
# processing & output
if (num ** 0.5) % 1 != 0:
print(num, 'is not a perfect square.')
else:
print(num, 'is a perfect square.') | num = int(input('Enter a value: '))
if num ** 0.5 % 1 != 0:
print(num, 'is not a perfect square.')
else:
print(num, 'is a perfect square.') |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright 2018 The AnPyLar Team. All Rights Reserved.
# Use of this source code is governed by an MIT-style license that
# can be found in the LICENSE file at http://anpyla... | styles_css = '\n/* Master Styles */\nh1 {\n color: #369;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 250%;\n}\nh2, h3 {\n color: #444;\n font-family: Arial, Helvetica, sans-serif;\n font-weight: lighter;\n}\nbody {\n margin: 2em;\n}\nbody, input[text], button {\n color: #888;\n font-family: Cambr... |
def Insertion_Sort(lst):
l = len(lst)
for i in range(1,l):
temp = lst[i]
j = i-1
while j>=0:
if temp[0]<lst[j][0]:
lst[j+1] = lst[j]
lst[j] = temp
j = j-1
return lst
lst = []
lst = ['Tininha', 'Dudinha','Carlinhos','Marquinhos','Joaozinho','Bruninha','Fernandinha','Rafinha','Pedrinho','Aninh... | def insertion__sort(lst):
l = len(lst)
for i in range(1, l):
temp = lst[i]
j = i - 1
while j >= 0:
if temp[0] < lst[j][0]:
lst[j + 1] = lst[j]
lst[j] = temp
j = j - 1
return lst
lst = []
lst = ['Tininha', 'Dudinha', 'Carlinhos',... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = 'D\xccZ\x0b=\xf2\xd6\x89\x1e\xeb\xa3n\xa2z\xd6n'
_lr_action_items = {'PEEK':([179,250,251,256,296,303,325,346,351,358,361,372,374,375,376,378,381,382,],[244,244,-98,-82,-81,-88,-97,-95,-89,... | _tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = 'DÌZ\x0b=òÖ\x89\x1eë£n¢zÖn'
_lr_action_items = {'PEEK': ([179, 250, 251, 256, 296, 303, 325, 346, 351, 358, 361, 372, 374, 375, 376, 378, 381, 382], [244, 244, -98, -82, -81, -88, -97, -95, -89, -94, -99, -90, -92, -100, -101, -93, -91, -96]), 'TRANS': ([0, 1, 2, ... |
def hoopCount(n):
if n > 9:
return "Great, now move on to tricks"
else:
return "Keep at it until you get it" | def hoop_count(n):
if n > 9:
return 'Great, now move on to tricks'
else:
return 'Keep at it until you get it' |
#
# PySNMP MIB module Dell-LAN-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-LAN-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:56:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
class DummyClass:
dummy_var = 'original'
def __init__(self, init_param=0):
pass
def __call__(self, call_param=0):
return 'not_mocked_call'
def some_method(self):
# def some_method(self, some_method_param):
return 'not_mocked_some_method'
def some_other_method(self, so... | class Dummyclass:
dummy_var = 'original'
def __init__(self, init_param=0):
pass
def __call__(self, call_param=0):
return 'not_mocked_call'
def some_method(self):
return 'not_mocked_some_method'
def some_other_method(self, some_other_method_param):
return 'not_mock... |
def for_p():
"""printing small 'p' using for loop"""
for row in range(7):
for col in range(4):
if col==0 or col==3 and row in(2,3) or row==1 and col in(1,2) or row==4 and col in(1,2):
print("*",end=" ")
else:
print(" ",end=" ")
prin... | def for_p():
"""printing small 'p' using for loop"""
for row in range(7):
for col in range(4):
if col == 0 or (col == 3 and row in (2, 3)) or (row == 1 and col in (1, 2)) or (row == 4 and col in (1, 2)):
print('*', end=' ')
else:
print(' ', end=' '... |
H, W, A, B = map(int, input().split())
board = [[0] * W for _ in range(H)]
for i in range(B):
for j in range(A):
board[i][j] = 1
for i in range(B, H):
for j in range(A, W):
board[i][j] = 1
assert all(sum(row) in [A, W-A] for row in board)
assert all(sum(board[i][j] for i in range(H)) in [B, H-B... | (h, w, a, b) = map(int, input().split())
board = [[0] * W for _ in range(H)]
for i in range(B):
for j in range(A):
board[i][j] = 1
for i in range(B, H):
for j in range(A, W):
board[i][j] = 1
assert all((sum(row) in [A, W - A] for row in board))
assert all((sum((board[i][j] for i in range(H))) in... |
def genSubsets(L):
'''
L: list
Returns: all subsets of L
'''
# base case
if len(L) == 0:
return [[]]
# recursive block
# all the subsets of smaller + all the subsets of smaller combined with extra = all subsets of L
extra = L[0:1]
smaller = genSubsets(L[1:])
combine ... | def gen_subsets(L):
"""
L: list
Returns: all subsets of L
"""
if len(L) == 0:
return [[]]
extra = L[0:1]
smaller = gen_subsets(L[1:])
combine = []
for i in smaller:
combine.append(extra + i)
return smaller + combine |
class Solution(object):
def isUgly(self, num):
if not num:
return False
for factor in (2, 3, 5):
while num % factor == 0:
num /= factor
return num == 1
| class Solution(object):
def is_ugly(self, num):
if not num:
return False
for factor in (2, 3, 5):
while num % factor == 0:
num /= factor
return num == 1 |
# Please change this appropriately
TRAIN_DATA = "../input/train.csv"
TEST_DATA = "../input/test.csv"
HTML_DATA = "../input/html_data.csv"
CLEAN_TRAIN_DATA = "../input2/train_v2.csv"
CLEAN_TEST_DATA = "../input2/test_v2.csv"
TRAIN_TEXT_MODEL_PATH = "../input2/train_text_preds.csv"
TEST_TEXT_MODEL_PATH = "../input2/tes... | train_data = '../input/train.csv'
test_data = '../input/test.csv'
html_data = '../input/html_data.csv'
clean_train_data = '../input2/train_v2.csv'
clean_test_data = '../input2/test_v2.csv'
train_text_model_path = '../input2/train_text_preds.csv'
test_text_model_path = '../input2/test_text_preds.csv'
submission_path = '... |
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = [root]
BST_vals = []
while stack:
curr = stack.pop()
BST_vals.append(curr.val)
... | class Solution(object):
def kth_smallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = [root]
bst_vals = []
while stack:
curr = stack.pop()
BST_vals.append(curr.val)
if curr.left != N... |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
oldToCopy = {None: N... | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copy_random_list(self, head: 'Optional[Node]') -> 'Optional[Node]':
old_to_copy = {No... |
_day_bands = ['n2_lbh'
, 'n2_vk'
, 'n2_1pg'
, 'n2_2pg'
, 'n2p_1ng'
, 'n2p_mnl'
, 'no_bands'
]
_night_bands = ['o2_nglow','o2_atm']
_bands = _day_bands + _night_bands
_band_cmd = {'n2_lbh':'syn_lbh'
, 'n2_vk':'syn_vk'
, 'n2_1pg':'sy... | _day_bands = ['n2_lbh', 'n2_vk', 'n2_1pg', 'n2_2pg', 'n2p_1ng', 'n2p_mnl', 'no_bands']
_night_bands = ['o2_nglow', 'o2_atm']
_bands = _day_bands + _night_bands
_band_cmd = {'n2_lbh': 'syn_lbh', 'n2_vk': 'syn_vk', 'n2_1pg': 'syn_1pg', 'n2_2pg': 'syn_2pg', 'n2p_1ng': 'syn_1ng', 'n2p_mnl': 'syn_mnl', 'no_bands': 'syn_no',... |
class BaseGordonException(Exception):
code = 1
hint = u"Something went't wrong"
def get_hint(self):
return self.hint.format(*self.args)
class ResourceSettingRequiredError(BaseGordonException):
code = 2
hint = u"Resource {} requires you to define '{}' in it's settings."
class InvalidStr... | class Basegordonexception(Exception):
code = 1
hint = u"Something went't wrong"
def get_hint(self):
return self.hint.format(*self.args)
class Resourcesettingrequirederror(BaseGordonException):
code = 2
hint = u"Resource {} requires you to define '{}' in it's settings."
class Invalidstream... |
# Aaron Donnelly
# This program will count the number of re-occurences of the letter 'e' in a txt file selected by the user.
f= open(input("Insert a .txt filename "), "r")
x= f.read().count('e')
print("There are",x, "e's in this text")
| f = open(input('Insert a .txt filename '), 'r')
x = f.read().count('e')
print('There are', x, "e's in this text") |
#
# PySNMP MIB module WWP-COMMUNITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-COMMUNITY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:30:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (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, value_size_constraint, constraints_intersection) ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class ChessPiece(object):
""" This is a super class for chess pieces """
def __init__(self, letter, value, x, y):
self.letter = letter
self.color = self.getColor()
self.value = value
self.x = x
self.y = y
def __str__... | class Chesspiece(object):
""" This is a super class for chess pieces """
def __init__(self, letter, value, x, y):
self.letter = letter
self.color = self.getColor()
self.value = value
self.x = x
self.y = y
def __str__(self):
return self.letter
def __repr... |
"""
File: hailstone.py
Name: Jade Yeh
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
# This constant controls wh... | """
File: hailstone.py
Name: Jade Yeh
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
exit = 1
def main():
""... |
#!/usr/bin/env python
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
def find(input_string, substring, s... | """ Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Susan Sim'
__email__ = 'ses@drsusansim.org'
__copyright__ = '2015 Susan Sim'
__license__ = 'MIT License'
def find(input_string, substring, start, end):
"""
D... |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
return [[n] + sub for i, n in enumerate(nums) for sub in self.XXX(nums[:i] + nums[i+1:])] or [nums]
| class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
return [[n] + sub for (i, n) in enumerate(nums) for sub in self.XXX(nums[:i] + nums[i + 1:])] or [nums] |
# A RouteTrie will store our routes and their associated handlers
class RouteTrie:
def __init__(self):
# Initialize the trie with an root node and a handler, this is the root path or home page node
self.root = RouteTrieNode()
def insert(self, path):
paths = split_path(path)
# Si... | class Routetrie:
def __init__(self):
self.root = route_trie_node()
def insert(self, path):
paths = split_path(path)
c_node = self.root
for p in paths:
if p not in c_node.items:
c_node.insert(p)
c_node = c_node.items[p]
def find(self,... |
'''
Created on Nov 6, 2013
@author: agreen
This module is used by the cubing_tests module as a data store.
'''
enabled = True
class DAR:
xfibre_pos = False
yfibre_pos = False
| """
Created on Nov 6, 2013
@author: agreen
This module is used by the cubing_tests module as a data store.
"""
enabled = True
class Dar:
xfibre_pos = False
yfibre_pos = False |
class Field(object):
def __init__(self, name=None, default=None, data_type=None):
self.name = name
self.default = default
self.required = self.default is None
self.type = data_type
def build(self):
result = {key: value for key, value in self.__dict__.items() if value is... | class Field(object):
def __init__(self, name=None, default=None, data_type=None):
self.name = name
self.default = default
self.required = self.default is None
self.type = data_type
def build(self):
result = {key: value for (key, value) in self.__dict__.items() if value ... |
COLORS = dict([
('CLEANUP', '\033[94m'),
('CREATE', '\033[92m'),
('INSTALL', '\033[92m'),
('SKIP', '\033[93m'),
('FAIL', '\033[31m'),
('DEFAULT', '\033[39m'),
('UNDEFINED', '\033[37m'),
('STATUS', '\033[36m')
])
def typed_message(message, message_type=None):
color = COLORS.setdefaul... | colors = dict([('CLEANUP', '\x1b[94m'), ('CREATE', '\x1b[92m'), ('INSTALL', '\x1b[92m'), ('SKIP', '\x1b[93m'), ('FAIL', '\x1b[31m'), ('DEFAULT', '\x1b[39m'), ('UNDEFINED', '\x1b[37m'), ('STATUS', '\x1b[36m')])
def typed_message(message, message_type=None):
color = COLORS.setdefault(message_type, COLORS['UNDEFINED'... |
#
# MIT License
#
# Copyright (c) 2018-2020 Franck Nijhof
# Copyright (c) 2020 Andrey "Limych" Khrolenok
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | """
Community Hass.io Add-ons Repository Updater.
Reads remote add-on repositories, determines versions and generates
changelogs to update the add-on repository fully automated.
Mainly used by the Community Home Assistant Add-ons project.
Please note, this program cannot be used with the general documented
Home Assi... |
class Solution:
def reverse(self, x: int) -> int:
rev = 0
y = abs(x)
while y:
rev = rev*10 + y % 10
y //= 10
sign = -1 if x < 0 else 1
if(rev > 0x7fffffff):
return 0
return sign * rev
| class Solution:
def reverse(self, x: int) -> int:
rev = 0
y = abs(x)
while y:
rev = rev * 10 + y % 10
y //= 10
sign = -1 if x < 0 else 1
if rev > 2147483647:
return 0
return sign * rev |
"""Unit tests configuration."""
pytest_plugins = [
"tests.fixtures.aws",
"tests.fixtures.click"
]
| """Unit tests configuration."""
pytest_plugins = ['tests.fixtures.aws', 'tests.fixtures.click'] |
# device present global variables
DS3231_Present = False
BMP280_Present = False
AM2315_Present = False
ADS1015_Present = False
ADS1115_Present = False
| ds3231__present = False
bmp280__present = False
am2315__present = False
ads1015__present = False
ads1115__present = False |
ObjectId = int
class Object:
def __init__(self, id_):
self.id: ObjectId = id_
self.count = 1
self.neighbors = {self}
@property
def neighbor_count(self):
return sum([neighbor.count for neighbor in self.neighbors])
def __repr__(self):
return f'{self.id}_'
| object_id = int
class Object:
def __init__(self, id_):
self.id: ObjectId = id_
self.count = 1
self.neighbors = {self}
@property
def neighbor_count(self):
return sum([neighbor.count for neighbor in self.neighbors])
def __repr__(self):
return f'{self.id}_' |
# Linear search algorithm
# @ra1ski
def linear_search(item, _list):
index = None
for idx, val in enumerate(_list):
if val == item:
index = idx
break
return index
if __name__ == '__main__':
_list = ['chrome', 'firefox', 'opera', 'ie', 'netscape']
item = input('Ty... | def linear_search(item, _list):
index = None
for (idx, val) in enumerate(_list):
if val == item:
index = idx
break
return index
if __name__ == '__main__':
_list = ['chrome', 'firefox', 'opera', 'ie', 'netscape']
item = input('Type browser name:')
found_index = lin... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 16:33:43 2019
@author: Steve Bremer
"""
STATE = 0
HISTORY = 1
SCORE = 2
class ConvolutionalCode():
def __init__(self, gen_poly):
if len(gen_poly) > 0:
poly_len = len(gen_poly[0])
else:
# Raise an error?
poly_len... | """
Created on Tue Dec 24 16:33:43 2019
@author: Steve Bremer
"""
state = 0
history = 1
score = 2
class Convolutionalcode:
def __init__(self, gen_poly):
if len(gen_poly) > 0:
poly_len = len(gen_poly[0])
else:
poly_len = 0
for poly in gen_poly:
if poly_l... |
city = input("Enter the name of the city: ")
sales = float(input("Enter the percentage of sales: "))
commission = 0
if 0 <= sales <= 500:
if city == "Sofia":
commission = 0.05
elif city == "Varna":
commission == 0.045
elif city == "Plovdiv":
commission == 0.055
elif 500 < sales <= 1... | city = input('Enter the name of the city: ')
sales = float(input('Enter the percentage of sales: '))
commission = 0
if 0 <= sales <= 500:
if city == 'Sofia':
commission = 0.05
elif city == 'Varna':
commission == 0.045
elif city == 'Plovdiv':
commission == 0.055
elif 500 < sales <= 10... |
def get_dotted_mask_split(ip_address_mask_cidr):
p = int(ip_address_mask_cidr)
ip_address_mask_dotted_split = []
for i in range(4):
if p >= 0:
if p - 8 >= 0:
ip_address_mask_dotted_split.append('255')
p -= 8
else:
b... | def get_dotted_mask_split(ip_address_mask_cidr):
p = int(ip_address_mask_cidr)
ip_address_mask_dotted_split = []
for i in range(4):
if p >= 0:
if p - 8 >= 0:
ip_address_mask_dotted_split.append('255')
p -= 8
else:
byte = 256 - p... |
#!/usr/bin/python
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class Tree:
def __init__(self):
self.root = None
@property
def root_node(self):
return self.root
def add(self, value):
if self.root is ... | class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class Tree:
def __init__(self):
self.root = None
@property
def root_node(self):
return self.root
def add(self, value):
if self.root is None:
s... |
#Conor O'Riordan
# Write a program that asks the user to input any positive integer and outputs the successive values of the following calculation.
# At each step calculate the next value by taking the current value and
# if it is even, divide it by two, but if it is odd, multiply it by three and add one.
# Have the pr... | pos_int = int(input('Please enter a positive integer:'))
while pos_int > 1:
if pos_int % 2 == 0:
print(round(pos_int), 'is even so divide by two. This gives:', round(pos_int / 2))
pos_int = pos_int / 2
else:
print(round(pos_int), 'is odd so multiply by three and add one. This gives:', ro... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1
def getLevelDiff(root):
h = {0: 0, 1: 0}
level = 0
populateDiff(root, level, h)
return h[0]-h[1]
def populateDiff(root, level, h):
if root == None:
return
l = level%2
h[l] += root.... | def get_level_diff(root):
h = {0: 0, 1: 0}
level = 0
populate_diff(root, level, h)
return h[0] - h[1]
def populate_diff(root, level, h):
if root == None:
return
l = level % 2
h[l] += root.data
populate_diff(root.left, level + 1, h)
populate_diff(root.right, level + 1, h) |
def BenchmarkNan(df):
"""Replace NaN by Benchmark."""
# Compute the inverse of the distance
distance_inv_df = (1. / df.filter(regex='^distance*', axis=1)).values
# Extract the value at the nearest station
values_df = df.filter(regex='value_*', axis=1)
# Compute the benchmark
numer_df = (d... | def benchmark_nan(df):
"""Replace NaN by Benchmark."""
distance_inv_df = (1.0 / df.filter(regex='^distance*', axis=1)).values
values_df = df.filter(regex='value_*', axis=1)
numer_df = (distance_inv_df * values_df).sum(axis=1)
denom_df = (distance_inv_df * (values_df != 0)).sum(axis=1)
benchmark_... |
#
# PySNMP MIB module Vsm-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Vsm-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:35:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 15:20:24 2018
@author: Charles Yang
"""
| """
Created on Sat Sep 8 15:20:24 2018
@author: Charles Yang
""" |
"""
A module with with two list functions.
These functions have been fully implemented.
Author: Walker M. White
Date: April 15, 2019
"""
def sum(lst):
"""
Returns: the sum of all elements in the list
Example: sum([1,2,3]) returns 6
sum([5]) returns 5
Parameter lst: the list to sum
... | """
A module with with two list functions.
These functions have been fully implemented.
Author: Walker M. White
Date: April 15, 2019
"""
def sum(lst):
"""
Returns: the sum of all elements in the list
Example: sum([1,2,3]) returns 6
sum([5]) returns 5
Parameter lst: the list to sum
... |
def camelcase(sentence):
""" Convert sentence to camelCase, for example,
"Display all books"
is converted to "displayAllBooks" """
title_case = sentence.title() # Uppercase first letter of each word
upper_camel_cased = title_case.replace(' ', '') # remove spaces
# Lowercase first letter, join with rest of... | def camelcase(sentence):
""" Convert sentence to camelCase, for example,
"Display all books"
is converted to "displayAllBooks" """
title_case = sentence.title()
upper_camel_cased = title_case.replace(' ', '')
return upper_camel_cased[0:1].lower() + upper_camel_cased[1:]
def display_banner():
... |
'''1. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.'''
def lcm(x, y):
if x > y:
z = x
else:
z = y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
pr... | """1. Write a Python program to compute the greatest common divisor (GCD) of two positive integers."""
def lcm(x, y):
if x > y:
z = x
else:
z = y
while True:
if z % x == 0 and z % y == 0:
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(... |
for t in range(int(input())):
n = int(input())
L = list(map(int,input().split()))
L.sort()
d = dict()
for i in L:
d[i] = 1
cnt = 0
for i in range(n):
for j in range(i+1,n):
try:
if d[L[i] - (L[j]-L[i])] == 1:
cnt+=1
... | for t in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
L.sort()
d = dict()
for i in L:
d[i] = 1
cnt = 0
for i in range(n):
for j in range(i + 1, n):
try:
if d[L[i] - (L[j] - L[i])] == 1:
cnt += 1
... |
'''
Remove Smallest
'''
t = int(input())
for ll in range(t):
n = int(input())
integers = set(map(int, input().split(' ')))
integers = list(integers)
integers.sort()
for i in range(1,len(integers)):
if abs(integers[i]-integers[i-1]) > 1:
print('NO')
break
else:
... | """
Remove Smallest
"""
t = int(input())
for ll in range(t):
n = int(input())
integers = set(map(int, input().split(' ')))
integers = list(integers)
integers.sort()
for i in range(1, len(integers)):
if abs(integers[i] - integers[i - 1]) > 1:
print('NO')
break
els... |
{
"targets": [
{
"target_name": "test_constructor",
"sources": [ "test_constructor.c" ]
},
{
"target_name": "test_constructor_name",
"sources": [ "test_constructor_name.c" ]
}
]
}
| {'targets': [{'target_name': 'test_constructor', 'sources': ['test_constructor.c']}, {'target_name': 'test_constructor_name', 'sources': ['test_constructor_name.c']}]} |
"""
True and True -> True otro caso -> False
Con or minimo un True da true
Negacion not(True) -> False
not (False) -> True
1. Not
2. And
3. Or ... | """
True and True -> True otro caso -> False
Con or minimo un True da true
Negacion not(True) -> False
not (False) -> True
1. Not
2. And
3. Or ... |
class Logger:
def __init__(self, filepath):
self.filepath = filepath
def write(self, msg):
with open(self.filepath, "a") as logfile:
logfile.write("{}\n".format(msg))
| class Logger:
def __init__(self, filepath):
self.filepath = filepath
def write(self, msg):
with open(self.filepath, 'a') as logfile:
logfile.write('{}\n'.format(msg)) |
'''
contains functions that convenient math stuff, usually involving operations that are not
defined in normal mathematics but could be useful
@author: Klint
'''
# matrix stuff, collapse matrix in interesting ways
def collapse_matrix_cols(matrix: [list])-> list:
'''flatten a matrix by m by n into a array of size... | """
contains functions that convenient math stuff, usually involving operations that are not
defined in normal mathematics but could be useful
@author: Klint
"""
def collapse_matrix_cols(matrix: [list]) -> list:
"""flatten a matrix by m by n into a array of size m by adding columns together
ie
| a_00 ... |
def write (name, stream):
stream.write("#include <unico.h>\n")
stream.write("#include <stddef.h>\n")
stream.write("extern int %s (size_t, size_t, unicos*);\n" % name)
| def write(name, stream):
stream.write('#include <unico.h>\n')
stream.write('#include <stddef.h>\n')
stream.write('extern int %s (size_t, size_t, unicos*);\n' % name) |
#! /usr/bin/env python3
# coding: utf-8
# Thanks to imbadatreading, should have through about LCM
def add_step_size(buses):
buses_with_step = list()
for num in range(len(buses)):
if buses[num] != 'x':
buses_with_step.append((int(buses[num]), num))
return buses_with_step
def find_aweso... | def add_step_size(buses):
buses_with_step = list()
for num in range(len(buses)):
if buses[num] != 'x':
buses_with_step.append((int(buses[num]), num))
return buses_with_step
def find_awesome_timestamp(buses):
current_time = 0
lcm = 1
for order_bus in range(len(buses) - 1):
... |
#!/usr/bin/env python3
f = open("input.txt", "r").read().splitlines()
REGISTERS_MAP = {"w": 0, "x": 1, "y": 2, "z": 3}
def checker(number):
num_str = str(number)
if "0" in num_str:
return False
if len(num_str) != 14:
return False
# Registers are in form [w,x,y,z]
counter = 0
... | f = open('input.txt', 'r').read().splitlines()
registers_map = {'w': 0, 'x': 1, 'y': 2, 'z': 3}
def checker(number):
num_str = str(number)
if '0' in num_str:
return False
if len(num_str) != 14:
return False
counter = 0
registers = [0] * 4
for line in f:
instr_arr = line.... |
"""This module loads the monkeypatch from gevent and applies it.
Nothing fancy, but it's useful and more readable to put this in a separate
module and give and explicit name to it.
"""
# Re-add sslwrap to Python 2.7.9
# import socket
# __getaddrinfo = socket.getaddrinfo
#
# # kudos to http://stackoverflow.com/a/1... | """This module loads the monkeypatch from gevent and applies it.
Nothing fancy, but it's useful and more readable to put this in a separate
module and give and explicit name to it.
""" |
# bunch of color constants
class Color:
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 128, 255)
GREEN = (0, 153, 0)
YELLOW = (255, 255, 0)
BROWN = (204, 102, 0)
PINK = (255, 102, 178)
PURPLE = (153, 51, 255)
GREY = (128, 128, 128)
colors = {
... | class Color:
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 128, 255)
green = (0, 153, 0)
yellow = (255, 255, 0)
brown = (204, 102, 0)
pink = (255, 102, 178)
purple = (153, 51, 255)
grey = (128, 128, 128)
colors = {1: WHITE, 2: YELLOW, 3: RED, 4: BLUE,... |
VERSION = "0.2"
if __name__ == '__main__':
print(VERSION)
| version = '0.2'
if __name__ == '__main__':
print(VERSION) |
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
if not matrix:
return
self.presum = [[0] * (1 + len(matrix[0])) for _ in range(1 + len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
self.presum[i + 1][j + 1] =... | class Nummatrix:
def __init__(self, matrix: List[List[int]]):
if not matrix:
return
self.presum = [[0] * (1 + len(matrix[0])) for _ in range(1 + len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
self.presum[i + 1][j + 1] = sel... |
class Crc8():
"""
Implements the 1-wire CRC8 checksum.
(The polynomial should be X^8 + X^5 + X^4 + X^0)
"""
R1 = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83,
0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41]
R2 = [0x00, 0x9d, 0x23, 0xbe, 0x46, 0xdb, 0x65, 0xf8,
... | class Crc8:
"""
Implements the 1-wire CRC8 checksum.
(The polynomial should be X^8 + X^5 + X^4 + X^0)
"""
r1 = [0, 94, 188, 226, 97, 63, 221, 131, 194, 156, 126, 32, 163, 253, 31, 65]
r2 = [0, 157, 35, 190, 70, 219, 101, 248, 140, 17, 175, 50, 202, 87, 233, 116]
def __init__(self, ... |
DEFAULT: int = 2
MINIMUM: int = 0
MAXIMUM: int = 9
| default: int = 2
minimum: int = 0
maximum: int = 9 |
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
def print_one(arg1):
print(f"arg1: {arg1}")
def print_none():
print("I got nothing.")
print_two("Kody", "Wilson")
print_two_again("Kody", "Wilson")
print_one("... | def print_two(*args):
(arg1, arg2) = args
print(f'arg1: {arg1}, arg2: {arg2}')
def print_two_again(arg1, arg2):
print(f'arg1: {arg1}, arg2: {arg2}')
def print_one(arg1):
print(f'arg1: {arg1}')
def print_none():
print('I got nothing.')
print_two('Kody', 'Wilson')
print_two_again('Kody', 'Wilson')
... |
# Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | class Slicingtestcases(object):
"""Test cases for pyfora slicing"""
def test_custom_slicing_1(self):
class Listwrapper_1:
def __init__(self, m):
self.m = m
def __getitem__(self, maybeSlice):
if isinstance(maybeSlice, slice):
... |
#
# PySNMP MIB module PDN-PPP-LCP-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-PPP-LCP-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:39:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, single_value_constraint, constraints_intersection) ... |
# Parse header file to generate Python wrapper around the rszvb DLL for the Rohde&Scwarz ZVA 40 Network Anlyzer
fout = open("rszvb_v2.py",'w')
# First load the DLL
print >>fout , """import numpy as numpy
from ctypes import *
# Prerequisition: installed rszvb driver 32-bit
# Reference to rszvb dll
rszvbDL... | fout = open('rszvb_v2.py', 'w')
(print >> fout, 'import numpy as numpy\nfrom ctypes import *\n\n# Prerequisition: installed rszvb driver 32-bit\n\n# Reference to rszvb dll\nrszvbDLL = windll.rszvb_32\n\nclass ZVBDLLERROR(Exception):\n\tpass\n \niStringBufferLen = 1024\nsStringBuffer = create_string_buffer(iStrin... |
{
'sr1_replace' : None,
'search_replace' : '[]',
'sr2_search' : None,
'sr2_replace' : None,
'sr1_search' : None,
'sr3_search' : None,
'sr3_replace' : None,
} | {'sr1_replace': None, 'search_replace': '[]', 'sr2_search': None, 'sr2_replace': None, 'sr1_search': None, 'sr3_search': None, 'sr3_replace': None} |
# coding=utf-8
"""This module, pre_process_constant.py, provides an abstraction for JS constants to pre-process."""
class PreProcessConstant(object):
"""Represents a constant to pre-process."""
def __init__(self, raw_line):
self._raw = raw_line
self._variable = None
self._value = None
self._initia... | """This module, pre_process_constant.py, provides an abstraction for JS constants to pre-process."""
class Preprocessconstant(object):
"""Represents a constant to pre-process."""
def __init__(self, raw_line):
self._raw = raw_line
self._variable = None
self._value = None
self._i... |
# -*- coding: utf-8 -*-
"""
stashcli.errors
~~~~~~~~~~~~~~~~
stashcli exception definitions
"""
class DuplicatePullRequest(Exception):
def __init__(self, msg):
super(DuplicatePullRequest, self).__init__(msg)
class EmptyPullRequest(Exception):
def __init__(self, msg):
super(EmptyPullRequest, ... | """
stashcli.errors
~~~~~~~~~~~~~~~~
stashcli exception definitions
"""
class Duplicatepullrequest(Exception):
def __init__(self, msg):
super(DuplicatePullRequest, self).__init__(msg)
class Emptypullrequest(Exception):
def __init__(self, msg):
super(EmptyPullRequest, self).__init__(msg) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.arb=None
class Solution:
def cloneList(self, head):
clone_head = clone_last = None
current_node = head
while current_node:
if clone_head == None:
clone_head... | class Node:
def __init__(self, data):
self.data = data
self.next = None
self.arb = None
class Solution:
def clone_list(self, head):
clone_head = clone_last = None
current_node = head
while current_node:
if clone_head == None:
clone_h... |
x = int(input())
y = int(input())
soma = 0
if y < 0:
for c in range(x, y, -1):
if c % 2 != 0:
soma += c
print(soma)
elif x > y:
for c in range(y, x):
if c % 2 != 0:
soma += c
print(soma)
else:
print('0')
| x = int(input())
y = int(input())
soma = 0
if y < 0:
for c in range(x, y, -1):
if c % 2 != 0:
soma += c
print(soma)
elif x > y:
for c in range(y, x):
if c % 2 != 0:
soma += c
print(soma)
else:
print('0') |
class AtomClass:
def __init__(self, Velocity, Element = 'C', Mass = 12.0):
self.Velocity = Velocity
self.Element = Element
self.Mass = Mass
def Momentum(self):
return self.Velocity * self.Mass
| class Atomclass:
def __init__(self, Velocity, Element='C', Mass=12.0):
self.Velocity = Velocity
self.Element = Element
self.Mass = Mass
def momentum(self):
return self.Velocity * self.Mass |
N = int(input())
check = False
for i in range(1, N):
nums = list(map(int, str(i)))
sum1 = i + sum(nums)
if sum1 == N:
print(i)
check = True
break
if not check:
print(0)
| n = int(input())
check = False
for i in range(1, N):
nums = list(map(int, str(i)))
sum1 = i + sum(nums)
if sum1 == N:
print(i)
check = True
break
if not check:
print(0) |
expected_output = {
"interface": {
"Loopback0": {
"interface_status": "Up",
"ip_address": "200.0.7.1",
"protocol_status": "Up"
},
"MgmtEth0/RSP0/CPU0/0": {
"interface_status": "Up",
"ip_address": "5.25.27.1",
"protocol_s... | expected_output = {'interface': {'Loopback0': {'interface_status': 'Up', 'ip_address': '200.0.7.1', 'protocol_status': 'Up'}, 'MgmtEth0/RSP0/CPU0/0': {'interface_status': 'Up', 'ip_address': '5.25.27.1', 'protocol_status': 'Up'}, 'MgmtEth0/RSP0/CPU0/1': {'interface_status': 'Shutdown', 'ip_address': 'unassigned', 'prot... |
# Chino (2210013) | Colossus Road : Chino's Lift: The Road Up & Down
sm.setPlayerAsSpeaker()
sm.sendNext("Hey..")
sm.setSpeakerID(parentID)
sm.sendSayOkay("No.") | sm.setPlayerAsSpeaker()
sm.sendNext('Hey..')
sm.setSpeakerID(parentID)
sm.sendSayOkay('No.') |
class FancyPrint(object):
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def echo(stuff_to_print, style):
bash_color = getattr(FancyPrint, style, None)
if no... | class Fancyprint(object):
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
def echo(stuff_to_print, style):
bash_color = getattr(FancyPrint, style, None)
if not... |
class ImageGroupData:
def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset):
self.start_y = start_y
self.start_x = start_x
self.y_gear_offset = y_gear_offset
self.x_gear_offset = x_gear_offset
class ImageTypeData:
def __init__(self, size, rel_start_offset, rows=None, columns=None, p... | class Imagegroupdata:
def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset):
self.start_y = start_y
self.start_x = start_x
self.y_gear_offset = y_gear_offset
self.x_gear_offset = x_gear_offset
class Imagetypedata:
def __init__(self, size, rel_start_offset, rows=No... |
text = input()
save = []
for letter in text:
o = ord(letter) + 3
ch = chr(o)
save.append(ch)
print("".join(save))
| text = input()
save = []
for letter in text:
o = ord(letter) + 3
ch = chr(o)
save.append(ch)
print(''.join(save)) |
'''
URL: https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution(object):
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sorted_lst = []
self.sort_vals(root... | """
URL: https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/
Time complexity: O(n)
Space complexity: O(n)
"""
class Solution(object):
def min_diff_in_bst(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sorted_lst = []
self.sort_vals(r... |
#
# PySNMP MIB module AISYSCFGTEMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AISYSCFGTEMP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:01:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
cur_hedons = 0
cur_health = 0
last_hedons = 0
last_health = 0
cur_star = None
cur_star_activity = None
last_star_time = 0
bored_with_stars = False
last_activity = None
last_activity_duration = 0
cur_time = 0
last_finished = -1000
def initialize():
'''Initializes the global variables needed... | cur_hedons = 0
cur_health = 0
last_hedons = 0
last_health = 0
cur_star = None
cur_star_activity = None
last_star_time = 0
bored_with_stars = False
last_activity = None
last_activity_duration = 0
cur_time = 0
last_finished = -1000
def initialize():
"""Initializes the global variables needed for the simulation. Inco... |
def get_cycle(n):
results = []
remainders = [1]
val = 1
while True:
result = (val*10)//n
remainder = (val*10)%n
results.append(result)
if remainder == 0 or remainder in remainders:
break
remainders.append(remainder)
val = remainder
return (... | def get_cycle(n):
results = []
remainders = [1]
val = 1
while True:
result = val * 10 // n
remainder = val * 10 % n
results.append(result)
if remainder == 0 or remainder in remainders:
break
remainders.append(remainder)
val = remainder
retu... |
# Databricks notebook source
LWILIOBCIMDGCHFASADRRGZCLIILUWO
RAZOIMPPJWANJOYLINMNWZBNP
ZGJJDFPYWBFLTPDCBSYJNCJLHEJLZASADWKGDWRMJCBBBOCJBPWLLGBPKTLMNQTFQKMHEEICHICAMKGNLTSAYULKKXJFNPLKAALUFPSLDWIHHUGNWKEMGMXWBDG
GSTFBJXBKRCGZHILZPJRUOFWRVWWKVAIDTEK
NIKIMPVFKIFHNJSLWLJZOHICCULWGGJJSWLHQFHQQUCDPJRBGAS
OBARCRYIKLKKEZ
LTMF... | LWILIOBCIMDGCHFASADRRGZCLIILUWO
RAZOIMPPJWANJOYLINMNWZBNP
ZGJJDFPYWBFLTPDCBSYJNCJLHEJLZASADWKGDWRMJCBBBOCJBPWLLGBPKTLMNQTFQKMHEEICHICAMKGNLTSAYULKKXJFNPLKAALUFPSLDWIHHUGNWKEMGMXWBDG
GSTFBJXBKRCGZHILZPJRUOFWRVWWKVAIDTEK
NIKIMPVFKIFHNJSLWLJZOHICCULWGGJJSWLHQFHQQUCDPJRBGAS
OBARCRYIKLKKEZ
LTMFPWWTMPGTWYZSZGNJRTDSPGBIGXISXJ... |
def palindromo(palabra):
palabra =palabra.replace(' ','')
palabra=palabra.lower()
palabra_invertida = palabra[::-1]
if palabra==palabra_invertida:
return True
else:
return False
def run():
palabra = input("Escribir una palabra: ")
es_palindromo=palindromo(palabra)
if e... | def palindromo(palabra):
palabra = palabra.replace(' ', '')
palabra = palabra.lower()
palabra_invertida = palabra[::-1]
if palabra == palabra_invertida:
return True
else:
return False
def run():
palabra = input('Escribir una palabra: ')
es_palindromo = palindromo(palabra)
... |
#
# PySNMP MIB module CISCO-IETF-SCTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-SCTP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ... |
supported_types = {
'removed',
'added',
'updated',
'nested',
'unchanged'
}
def stringify(value):
if isinstance(value, dict):
return '[complex value]'
if isinstance(value, bool):
return str(value).lower()
if value is None:
return 'null'
if isinstance(value, s... | supported_types = {'removed', 'added', 'updated', 'nested', 'unchanged'}
def stringify(value):
if isinstance(value, dict):
return '[complex value]'
if isinstance(value, bool):
return str(value).lower()
if value is None:
return 'null'
if isinstance(value, str):
return f"'... |
obj = pd.Series(np.arange(5.), index=list('abcde'))
obj
obj.drop(['c'])
obj.drop(list('dc'))
data = pd.DataFrame(np.arange(16).reshape((4,4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])
data
data.drop(['Colorado', 'Ohio'])
data.drop('two', axis=1)
data.drop('two', axis='col... | obj = pd.Series(np.arange(5.0), index=list('abcde'))
obj
obj.drop(['c'])
obj.drop(list('dc'))
data = pd.DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])
data
data.drop(['Colorado', 'Ohio'])
data.drop('two', axis=1)
data.drop('two', axis='c... |
def chooseLargest(a, b):
list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b)))
l1 = [1, 2, 3, 4, 5]
l2 = [2, 2, 9, 0, 9]
return list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b))) | def choose_largest(a, b):
list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b)))
l1 = [1, 2, 3, 4, 5]
l2 = [2, 2, 9, 0, 9]
return list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b))) |
# https://www.hackerrank.com/challenges/string-validators/problem
string = input()
print(any(c.isalnum() for c in string))
print(any(c.isalpha() for c in string))
print(any(c.isdigit() for c in string))
print(any(c.islower() for c in string))
print(any(c.isupper() for c in string))
| string = input()
print(any((c.isalnum() for c in string)))
print(any((c.isalpha() for c in string)))
print(any((c.isdigit() for c in string)))
print(any((c.islower() for c in string)))
print(any((c.isupper() for c in string))) |
#
# PySNMP MIB module Nortel-Magellan-Passport-VnetMcdnSigMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-VnetMcdnSigMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ... |
# Localizable strings extracted by LocalizationDemo.tscn
tr("Space")
tr("Exclam")
tr("QuoteDbl")
tr("NumberSign")
tr("Dollar")
tr("Percent")
tr("Ampersand")
tr("Apostrophe")
tr("ParenLeft")
tr("ParenRight")
tr("Asterisk")
tr("Plus")
tr("Comma")
tr("Minus")
tr("Period")
tr("Slash")
tr("Colon")
tr("Semicolon")
tr("Less")... | tr('Space')
tr('Exclam')
tr('QuoteDbl')
tr('NumberSign')
tr('Dollar')
tr('Percent')
tr('Ampersand')
tr('Apostrophe')
tr('ParenLeft')
tr('ParenRight')
tr('Asterisk')
tr('Plus')
tr('Comma')
tr('Minus')
tr('Period')
tr('Slash')
tr('Colon')
tr('Semicolon')
tr('Less')
tr('Equal')
tr('Greater')
tr('Question')
tr('At')
tr('Br... |
"""
This file stores API headers used by the samples. The samples call
the dictionary in this script to retrieve them. You can store multiple
header dictionaries here and call the one you want to use in your script.
IN PRODUCTION:
You may not want to store your keys in plaintext in a source code file.
You can just re... | """
This file stores API headers used by the samples. The samples call
the dictionary in this script to retrieve them. You can store multiple
header dictionaries here and call the one you want to use in your script.
IN PRODUCTION:
You may not want to store your keys in plaintext in a source code file.
You can just re... |
class FormataTexto(object):
def __init__(self, texto, formatacao='Titulo'):
self.__texto = texto
self.__formatacao = formatacao
def __str__(self):
return self.__getFormatar()
def __getFormatar(self):
if self.__formatacao == 'Titulo':
return self.__texto.... | class Formatatexto(object):
def __init__(self, texto, formatacao='Titulo'):
self.__texto = texto
self.__formatacao = formatacao
def __str__(self):
return self.__getFormatar()
def __get_formatar(self):
if self.__formatacao == 'Titulo':
return self.__texto.title(... |
__title__ = 'app'
__description__ = 'A Flask based microblog.'
__url__ = 'https://github.com/Napchat/microblog'
__version__ = '1.0'
__author__ = 'Shang Nan'
__author_email__ = 'shangnan543@163.com'
__license__ = 'MIT License'
__copyright__ = 'Copyright 2017 Shang Nan'
| __title__ = 'app'
__description__ = 'A Flask based microblog.'
__url__ = 'https://github.com/Napchat/microblog'
__version__ = '1.0'
__author__ = 'Shang Nan'
__author_email__ = 'shangnan543@163.com'
__license__ = 'MIT License'
__copyright__ = 'Copyright 2017 Shang Nan' |
info_modes = {'login': 'inurl:login | inurl:signin | intitle:Login | intitle:"sign in" | inurl:auth',
'signup': 'inurl:signup | inurl:register | intitle:Signup',
'phpinfo': 'ext:php intitle:phpinfo "published by the PHP Group"'}
for info in info_modes:
print(info_modes[info]) | info_modes = {'login': 'inurl:login | inurl:signin | intitle:Login | intitle:"sign in" | inurl:auth', 'signup': 'inurl:signup | inurl:register | intitle:Signup', 'phpinfo': 'ext:php intitle:phpinfo "published by the PHP Group"'}
for info in info_modes:
print(info_modes[info]) |
N1 = int(input("Digite o primeiro numero: "))
N2 = int(input("Digite o segundo numero:"))
print(N1+N2)
| n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero:'))
print(N1 + N2) |
OPEN_MS_SRC="/home/uschmitt/Release1.10pyopenms"
OPEN_MS_BUILD_DIR="/home/uschmitt/Release1.10pyopenms"
OPEN_MS_CONTRIB_BUILD_DIRS="/home/uschmitt/Release1.10pyopenms/contrib;/opt/local;/usr/local;"
QT_HEADERS_DIR="/usr/include/qt4"
QT_LIBRARY_DIR="/usr/lib/x86_64-linux-gnu"
QT_QTCORE_INCLUDE_DIR="/usr/include/qt4/QtCo... | open_ms_src = '/home/uschmitt/Release1.10pyopenms'
open_ms_build_dir = '/home/uschmitt/Release1.10pyopenms'
open_ms_contrib_build_dirs = '/home/uschmitt/Release1.10pyopenms/contrib;/opt/local;/usr/local;'
qt_headers_dir = '/usr/include/qt4'
qt_library_dir = '/usr/lib/x86_64-linux-gnu'
qt_qtcore_include_dir = '/usr/incl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.