content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
{
"targets" : [
{
'include_dirs': [
"<!(node -e \"require('nan')\")"
],
'cflags': [
'-std=c++0x',
'-Wall',
'-pthread',
'-pedantic',
'-g',
'-zdefs'
'-Werror'
],
'ldflags': [
'-g'
],
'link_settings': {
... | {'targets': [{'include_dirs': ['<!(node -e "require(\'nan\')")'], 'cflags': ['-std=c++0x', '-Wall', '-pthread', '-pedantic', '-g', '-zdefs-Werror'], 'ldflags': ['-g'], 'link_settings': {'libraries': ['-lpthread', '-lgrpc', '-lgpr']}, 'conditions': [['OS == "mac"', {'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.9',... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
out_list = ListNode(0)
out_run = out_list
cf = 0
while True:
n1... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
out_list = list_node(0)
out_run = out_list
cf = 0
while True:
n1 = l1.val if l1 is not None else ... |
# -*- coding: UTF-8 -*-
#$ header procedure incr(double) results(double)
def incr(x):
y = x + 1
return y
#$ header procedure decr(double) results(double)
def decr(x):
y = x - 1
return y
| def incr(x):
y = x + 1
return y
def decr(x):
y = x - 1
return y |
# this holds hardware info based on raspberry pi SSN
def getHostSerialNumber():
ssn = None
a=check_output(["cat", '/proc/cpuinfo'])
for s in a.split('\n'):
if s.find('Serial') > -1:
ssn = s.split()[2]
return ssn
ssn = getHostSerialNumber()
if ssn == '00000000f4e2702a': # real R2D2
arduino_port = '/dev/se... | def get_host_serial_number():
ssn = None
a = check_output(['cat', '/proc/cpuinfo'])
for s in a.split('\n'):
if s.find('Serial') > -1:
ssn = s.split()[2]
return ssn
ssn = get_host_serial_number()
if ssn == '00000000f4e2702a':
arduino_port = '/dev/serial/by-id/usb-Arduino__www.ardu... |
def sayHello():#Function to print Hello World
print("Hello world !")
sayHello()#Calling the function
| def say_hello():
print('Hello world !')
say_hello() |
str1=input("Enter the string :")
list1=str1.split()
list2=set(list1)
list3=list(list2)
print(list1)
print(list2)
print(list3)
list4=[]
list5=[]
counter=0
for i in range(len(list3)):
counter=0
for j in range(len(list1)):
if list3[i]==list1[j]:
counter+=1
list4=list3[i],counter
list5.append(list4)
print(list5... | str1 = input('Enter the string :')
list1 = str1.split()
list2 = set(list1)
list3 = list(list2)
print(list1)
print(list2)
print(list3)
list4 = []
list5 = []
counter = 0
for i in range(len(list3)):
counter = 0
for j in range(len(list1)):
if list3[i] == list1[j]:
counter += 1
list4 = (list3... |
def maximo (x, y):
if x > y:
return(x)
else:
return(y)
| def maximo(x, y):
if x > y:
return x
else:
return y |
img_size = 84
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
test_pipeline = [
dict(type='LoadImageFromBytes'),
dict(type='Resize', size=(int(img_size * 1.15), -1)),
dict(type='CenterCrop', crop_size=img_size),
dict(type='Normalize', **img_norm_cfg),
... | img_size = 84
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
test_pipeline = [dict(type='LoadImageFromBytes'), dict(type='Resize', size=(int(img_size * 1.15), -1)), dict(type='CenterCrop', crop_size=img_size), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTenso... |
# Implement your function below.
def non_repeating(given_string):
char_count = {}
for c in given_string:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
for c in given_string:
if char_count[c] == 1:
return c
return None
# NOTE: ... | def non_repeating(given_string):
char_count = {}
for c in given_string:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
for c in given_string:
if char_count[c] == 1:
return c
return None
non_repeating('abcab')
non_repeating('abab... |
# Project Euler
# problem - 16
def sumt(s):
ss = 0
str1 = str(s)
for i in str1:
ss += int(i)
return ss
t = 2**1000
print(sumt(t))
| def sumt(s):
ss = 0
str1 = str(s)
for i in str1:
ss += int(i)
return ss
t = 2 ** 1000
print(sumt(t)) |
#====================================================================
# Motor class that remembers parameters for sizing
#====================================================================
class motors:
def __init__(self, data={}, nseg=0):
self.ngroups = 0
self.groups = {}
ngrp ... | class Motors:
def __init__(self, data={}, nseg=0):
self.ngroups = 0
self.groups = {}
ngrp = 0
if bool(data):
for key in sorted(data):
self.groups[ngrp] = motor_group(data[key], key, nseg)
ngrp = ngrp + 1
self.ngroups = ngrp
... |
#!/usr/bin/env python
# coding: utf-8 -*-
#
# GNU General Public License v3.0+
#
# Copyright 2019 Arista Networks AS-EMEA
#
# 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.ap... | cv_images_payloads = [{'name': '0 image, 1 bundle', 'images': {'total': 0, 'data': []}, 'image_bundles': {'data': [{'key': 'imagebundle_1643897984608204097', 'name': 'EOS-4.26.1F', 'note': '', 'user': 'tgrimonet', 'isCertifiedImageBundle': 'true', 'updatedDateInLongFormat': 1643897984608, 'imageIds': ['EOS-4.26.1F.swi'... |
# coding=utf-8
# Author: Jianghan Li
# Question: 202.Happy_Number
# Date: 06/03/2017
# Space: O(1)
class Solution(object):
def isHappy(self, n):
n = sum(int(x) ** 2 for x in str(n))
return n in set([1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130,... | class Solution(object):
def is_happy(self, n):
n = sum((int(x) ** 2 for x in str(n)))
return n in set([1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 29... |
s=input();f=True
try:
while s!="":
if s[0]=="p":
t=s[:2]
if t=="pi":
s=s[2:]
else:
f=False; break
elif s[0]=="k":
t=s[:2]
if t=="ka":
s=s[2:]
else:
f=False; break
... | s = input()
f = True
try:
while s != '':
if s[0] == 'p':
t = s[:2]
if t == 'pi':
s = s[2:]
else:
f = False
break
elif s[0] == 'k':
t = s[:2]
if t == 'ka':
s = s[2:]
... |
def logger_util(t_sol, x_sol, u_sol, tinit, xinit, uinit):
x_labels = ["r: ", "alpha: ", "beta: ",
"Vx: ", "Vy: ", "Vz: ",
"m: ", "phi: ", "psi: "]
u_labels = ["T: ", "w_phi: ", "w_psi: "]
with open("save_solution_variables.txt", mode='w') as F:
F.write("LOGGING S... | def logger_util(t_sol, x_sol, u_sol, tinit, xinit, uinit):
x_labels = ['r: ', 'alpha: ', 'beta: ', 'Vx: ', 'Vy: ', 'Vz: ', 'm: ', 'phi: ', 'psi: ']
u_labels = ['T: ', 'w_phi: ', 'w_psi: ']
with open('save_solution_variables.txt', mode='w') as f:
F.write('LOGGING SOLUTIONS... \n')
F.write('t_... |
def maximum_consecutive(lst, n):
count = 0
result = 0
for i in range(0, n):
if (lst[i] == 0):
count = 0
else:
count+= 1
result = max(result, count)
return result
lst=[0,0,0,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1]
n=len(lst... | def maximum_consecutive(lst, n):
count = 0
result = 0
for i in range(0, n):
if lst[i] == 0:
count = 0
else:
count += 1
result = max(result, count)
return result
lst = [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]
n = len(lst)
print(maxim... |
# Copyright (c) 2011, Hua Huang and Robert D. Cameron.
# Licensed under the Academic Free License 3.0.
def GetResult(fw, sh, data):
arg1 = data[0]
(i, sz, ans) = (0, len(arg1), "")
blockNum = int(sz/fw)
while i<blockNum:
ans += arg1[(i+sh)*fw:(i+sh+1)*fw] if (i+sh)<blockNum else "0"*fw
i += 1
return ans... | def get_result(fw, sh, data):
arg1 = data[0]
(i, sz, ans) = (0, len(arg1), '')
block_num = int(sz / fw)
while i < blockNum:
ans += arg1[(i + sh) * fw:(i + sh + 1) * fw] if i + sh < blockNum else '0' * fw
i += 1
return ans |
numerator = input("Enter the numerator: ")
denominator = input("Enter the denominator: ")
try:
# try = try then catch the error, if something fail during execution of the code indented with try, it executes the code indented with except.
numerator = int(numerator)
denominator = int(denominator)
except:
... | numerator = input('Enter the numerator: ')
denominator = input('Enter the denominator: ')
try:
numerator = int(numerator)
denominator = int(denominator)
except:
print('Error while converting values.')
try:
print(numerator / denominator)
except NameError:
print('One or more variable is not defined')
... |
BLUE = "#1017e6"
GREEN = "#31e319"
CYAN = "#03fccf"
RED = "#fc0335"
YELLOW = "#f2f205"
| blue = '#1017e6'
green = '#31e319'
cyan = '#03fccf'
red = '#fc0335'
yellow = '#f2f205' |
print(" +",*"+"*6,sep="---")
print("",*"Python", sep=" | ",end=" |\n")
print(" +",*"+"*6,sep="---")
print(" 0",*"123456",sep=" ")
print("-6",*"54321",sep=" -") | print(' +', *'+' * 6, sep='---')
print('', *'Python', sep=' | ', end=' |\n')
print(' +', *'+' * 6, sep='---')
print(' 0', *'123456', sep=' ')
print('-6', *'54321', sep=' -') |
class Solution:
def totalMoney(self, n: int) -> int:
weeks = n // 7
firstweek = sum([i for i in range(1,8)])
s = sum([i for i in range(1,weeks)]) * 7 + firstweek * (weeks)
remains = n % 7
s += sum([i for i in range(1,remains+1)]) + remains * weeks
ret... | class Solution:
def total_money(self, n: int) -> int:
weeks = n // 7
firstweek = sum([i for i in range(1, 8)])
s = sum([i for i in range(1, weeks)]) * 7 + firstweek * weeks
remains = n % 7
s += sum([i for i in range(1, remains + 1)]) + remains * weeks
return s |
#window measurements
# HEIGHT = 700
WIDTH, HEIGHT = 600, 700
#BOARD
BOARD_POS = (50,150)
CELL = 55
BOARD_W, BOARD_H = 9*CELL,9*CELL
NUM_FONT = 34
#COLORS
RED = (160,0,0)
WHITE = (255,255,255)
BLACK = (0,0,0)
GRAY = (10,10,10)
LGRAY = (180,180,180)
BLUE = (44,97,202)
TEAL = (128, 203, 164)
YELLOW =... | (width, height) = (600, 700)
board_pos = (50, 150)
cell = 55
(board_w, board_h) = (9 * CELL, 9 * CELL)
num_font = 34
red = (160, 0, 0)
white = (255, 255, 255)
black = (0, 0, 0)
gray = (10, 10, 10)
lgray = (180, 180, 180)
blue = (44, 97, 202)
teal = (128, 203, 164)
yellow = (231, 177, 0)
lyellow = tuple((min(T + 40, 255... |
# Copyright (c) 2015-2017 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
def qemuMonitorCommand(domain, cmd, flags):
retval = '{"return":[{"current":true,"CPU":0,"pc":-2130513274,' \
'"halted":true,"thread_id":86064},' \
'{"current":false,"CPU":1,"pc":-2130513274,' \
... | def qemu_monitor_command(domain, cmd, flags):
retval = '{"return":[{"current":true,"CPU":0,"pc":-2130513274,"halted":true,"thread_id":86064},{"current":false,"CPU":1,"pc":-2130513274,"halted":true,"thread_id":86065},{"current":false,"CPU":2,"pc":-2130513274,"halted":true,"thread_id":86066},{"current":false,"CPU":3,... |
class FairyChessException(Exception):
def __init__(self, status: int, message: str):
self.status_code = status
self.message = message
| class Fairychessexception(Exception):
def __init__(self, status: int, message: str):
self.status_code = status
self.message = message |
# statistical channel data]
sta_ch1_avg = [2506, 2]
sta_ch1_sd = [2508, 2]
sta_ch1_max = [2510, 2]
sta_ch1_min = [2512, 2]
sta_ch1_gust = [2514, 2]
sta_ch2_avg = [2516, 2]
sta_ch2_sd = [2518, 2]
sta_ch2_max = [2520, 2]
sta_ch2_min = [2522, 2]
sta_ch2_gust = [2524, 2]
sta_ch3_avg = [2526, 2]
sta_ch3_sd = [2528, 2]
sta_c... | sta_ch1_avg = [2506, 2]
sta_ch1_sd = [2508, 2]
sta_ch1_max = [2510, 2]
sta_ch1_min = [2512, 2]
sta_ch1_gust = [2514, 2]
sta_ch2_avg = [2516, 2]
sta_ch2_sd = [2518, 2]
sta_ch2_max = [2520, 2]
sta_ch2_min = [2522, 2]
sta_ch2_gust = [2524, 2]
sta_ch3_avg = [2526, 2]
sta_ch3_sd = [2528, 2]
sta_ch3_max = [2530, 2]
sta_ch3_m... |
all_parties = [{
"party_id": 1000,
"party_name": "taken_party",
"party_headquarters_address": "taken_hq",
"party_logo_url": "present_party_logo.png"
},{
"party_id": 100,
"party_name": "d-present_party2",
"party_headquarters_address": "d-present_party_headquarters2",
"party_logo_url": "d-... | all_parties = [{'party_id': 1000, 'party_name': 'taken_party', 'party_headquarters_address': 'taken_hq', 'party_logo_url': 'present_party_logo.png'}, {'party_id': 100, 'party_name': 'd-present_party2', 'party_headquarters_address': 'd-present_party_headquarters2', 'party_logo_url': 'd-present_party_logo.png'}]
class P... |
s = str(input())
def fun(m):
if len(m) == 1:
return m[0]
else:
return (m[len(m) - 1] + fun(m[:(len(m) - 1)]))
if len(s) > 5:
print("Out of range")
else:
print("{0} items, reversed {1}".format(len(s), fun(s)))
| s = str(input())
def fun(m):
if len(m) == 1:
return m[0]
else:
return m[len(m) - 1] + fun(m[:len(m) - 1])
if len(s) > 5:
print('Out of range')
else:
print('{0} items, reversed {1}'.format(len(s), fun(s))) |
# App path
APP_PATH = '/home/ubuntu/application'
# APP_PATH = '/mnt/c/Users/chung/Documents/04-Insight/nextpick/NextPick-app'
# image preprocessing
RESIZE = (256, 256)
CROP = 224
# database
DATA_FOLDER = "%s/NextPick/data" %APP_PATH
BATCH = 100
# annoy index
ANNOY_PATH = '%s/NextPick/NextPick/annoy_idx_2.annoy' % AP... | app_path = '/home/ubuntu/application'
resize = (256, 256)
crop = 224
data_folder = '%s/NextPick/data' % APP_PATH
batch = 100
annoy_path = '%s/NextPick/NextPick/annoy_idx_2.annoy' % APP_PATH
annoy_metric = 'angular'
annoy_tree = 132
resnet18_feat = 512
numclass = 365
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
to... |
#
# PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-1
# Produced by pysmi-0.3.4 at Wed May 1 13:19:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint, constraints_union) ... |
def expand(s,Left,Right):
L,R=Left,Right
while L>=0 and R<len(s) and s[L]==s[R]:
L=L-1
R=R+1
return R-L-1
s=input()
if len(s)<1:
print("''")
a,b=0,0
for i in range(0,len(s)):
l1=expand(s,i,i)
l2=expand(s,i,i+1)
l=max(l1,l2)
if l>b-a:
a=i-((l-1)//2)
b=i+(l/... | def expand(s, Left, Right):
(l, r) = (Left, Right)
while L >= 0 and R < len(s) and (s[L] == s[R]):
l = L - 1
r = R + 1
return R - L - 1
s = input()
if len(s) < 1:
print("''")
(a, b) = (0, 0)
for i in range(0, len(s)):
l1 = expand(s, i, i)
l2 = expand(s, i, i + 1)
l = max(l1, ... |
HTTP2_MESSAGE_TYPES = {
0: 'DATA',
1: 'HEADERS',
2: 'PRIORITY',
3: 'RST_STREAM',
4: 'SETTINGS',
5: 'PUSH_PROMISE',
6: 'PING',
7: 'GOAWAY',
8: 'WINDOW_UPDATE',
9: 'CONTINUATION',
}
HTTP2_SETTINGS_TYPES = {
1: 'HEADER_TABLE_SIZE',
2: 'ENABLE_PUSH',
3: 'MAX_CONCURRENT_... | http2_message_types = {0: 'DATA', 1: 'HEADERS', 2: 'PRIORITY', 3: 'RST_STREAM', 4: 'SETTINGS', 5: 'PUSH_PROMISE', 6: 'PING', 7: 'GOAWAY', 8: 'WINDOW_UPDATE', 9: 'CONTINUATION'}
http2_settings_types = {1: 'HEADER_TABLE_SIZE', 2: 'ENABLE_PUSH', 3: 'MAX_CONCURRENT_STREAMS', 4: 'INITIAL_WINDOW_SIZE', 5: 'MAX_FRAME_SIZE', 6... |
# 09/14/2020
# Practice Questions
# Palindrome Checking Solution
'''
- Removing spaces/non-alpha characters
- Flipping the text backwards
- Make everything lowercased
- Front & back at the same time
- Output if it is a palindrome or not
'''
def cleaner(word):
'''
cleaner() helps us remove non al... | """
- Removing spaces/non-alpha characters
- Flipping the text backwards
- Make everything lowercased
- Front & back at the same time
- Output if it is a palindrome or not
"""
def cleaner(word):
"""
cleaner() helps us remove non alpha characters and makes everything lowercased
arguments
-- word : stri... |
_SDES = dict()
def register(fn):
global _SDES
_SDES[fn.__name__] = fn
return fn
def get_sde(args=None, device=None):
if args.sde is None:
return _SDES
return _SDES[args.sde](args, device)
| _sdes = dict()
def register(fn):
global _SDES
_SDES[fn.__name__] = fn
return fn
def get_sde(args=None, device=None):
if args.sde is None:
return _SDES
return _SDES[args.sde](args, device) |
#
# @lc app=leetcode.cn id=1690 lang=python3
#
# [1690] maximum-length-of-subarray-with-positive-product
#
None
# @lc code=end | None |
def phoneCall(min1, min2_10, min11, s):
if s < min1:
return 0
if s == min1:
return 1
if s <= min1 + (min2_10 * 9):
s -= min1
return (s // min2_10) + 1
s -= min1
s -= min2_10 * 9
return (s // min11) + 10
| def phone_call(min1, min2_10, min11, s):
if s < min1:
return 0
if s == min1:
return 1
if s <= min1 + min2_10 * 9:
s -= min1
return s // min2_10 + 1
s -= min1
s -= min2_10 * 9
return s // min11 + 10 |
#!/usr/bin/env python
##
# @package cwfs
# @file cwfsImage.py
##
# @authors: Bo Xin & Chuck Claver
# @ Large Synoptic Survey Telescope
class nonSquareImageError(Exception):
def __init__(self):
pass
class imageDiffSizeError(Exception):
def __init__(self):
pass
class unknownUnitError... | class Nonsquareimageerror(Exception):
def __init__(self):
pass
class Imagediffsizeerror(Exception):
def __init__(self):
pass
class Unknownuniterror(Exception):
def __init__(self):
pass
class Oddnumpixerror(Exception):
def __init__(self):
pass |
def popcount(x):
x = x - ((x >> 1) & 0x5555555555555555)
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
x = x + (x >> 32)
return x & 0x0000007f
def popcount2(x):
return bin(x).count("1")
def main... | def popcount(x):
x = x - (x >> 1 & 6148914691236517205)
x = (x & 3689348814741910323) + (x >> 2 & 3689348814741910323)
x = x + (x >> 4) & 1085102592571150095
x = x + (x >> 8)
x = x + (x >> 16)
x = x + (x >> 32)
return x & 127
def popcount2(x):
return bin(x).count('1')
def main():
p... |
#This program determines whether a number is prime or not
#Checking if the integer entered is prime
def is_prime(integer):
prime_division = 0
if integer <= 1:
return False
for current_integer in range(1,integer + 1):
if integer % current_integer == 0:
prime_division += 1
... | def is_prime(integer):
prime_division = 0
if integer <= 1:
return False
for current_integer in range(1, integer + 1):
if integer % current_integer == 0:
prime_division += 1
if prime_division > 2:
return False
else:
return True
def main():
... |
# Copyright 2015 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.
{
'targets': [
{
'target_name': 'haha_java',
'type': 'none',
'variables': {
'jar_path': 'haha-2.0.2.jar',
},
'inc... | {'targets': [{'target_name': 'haha_java', 'type': 'none', 'variables': {'jar_path': 'haha-2.0.2.jar'}, 'includes': ['../../build/java_prebuilt.gypi']}]} |
# We analyze the logic of the program ran with regi = [1, 0, 0, 0, 0, 0] :
# - it increments reg1 until 10551288
# - if reg1 * reg4 divides 10551288, it adds reg4 to reg0
# - if reg1 == 10551288, it increments reg4 and sets reg1 back to 1
# - if reg4 == 10551288, halts
# This means that reg0 contains the sum of th... | nb = 10551288
res = 0
for i in range(1, nb + 1):
if nb % i == 0:
res += i
print('Value of reg0 when program halts = ', res) |
#
# PySNMP MIB module CISCO-OSCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OSCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:52:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
my_str = input("Enter a string: ")
words = [word.lower() for word in my_str.split()]
words.sort()
print("The sorted words are:")
for word in words:
print(word)
| my_str = input('Enter a string: ')
words = [word.lower() for word in my_str.split()]
words.sort()
print('The sorted words are:')
for word in words:
print(word) |
dias = int(input(""))
anos = dias // 365
dias = dias % 365
meses = dias // 30
dias = dias % 30
print("{} ano(s)\n"
"{} mes(es)\n"
"{} dia(s)".format(anos, meses, dias)) | dias = int(input(''))
anos = dias // 365
dias = dias % 365
meses = dias // 30
dias = dias % 30
print('{} ano(s)\n{} mes(es)\n{} dia(s)'.format(anos, meses, dias)) |
artist_info = {
"The Beatles": {
"image": "TheBeatles.jpg",
"spotify_link": "3WrFJ7ztbogyGnTHbHJFl2"
},
"ABBA": {
"image": "ABBA.jpg",
"spotify_link": "0LcJLqbBmaGUft1e9Mm8HV"
},
"Saint Motel": {
"image": "SaintMotel.jpg",
"spotify_link": "1dWEYMPtNmvSVaDNLgB6NV"
},
"Cardi B": {
"image": "Ca... | artist_info = {'The Beatles': {'image': 'TheBeatles.jpg', 'spotify_link': '3WrFJ7ztbogyGnTHbHJFl2'}, 'ABBA': {'image': 'ABBA.jpg', 'spotify_link': '0LcJLqbBmaGUft1e9Mm8HV'}, 'Saint Motel': {'image': 'SaintMotel.jpg', 'spotify_link': '1dWEYMPtNmvSVaDNLgB6NV'}, 'Cardi B': {'image': 'CardiB.jpg', 'spotify_link': '4kYSro6n... |
n = 333113322244444444444444444444444
n = list(str(n))
db = {}
print(n)
for digit in n:
if digit in db:
db[digit] = db[digit]+1
else:
db[digit] = 1
key = list(db.keys())
val = list(db.values())
m = max(val)
#print(m)
pos = 0
for k in key:
if m == db[k]:
print(key[pos])
else:
... | n = 333113322244444444444444444444444
n = list(str(n))
db = {}
print(n)
for digit in n:
if digit in db:
db[digit] = db[digit] + 1
else:
db[digit] = 1
key = list(db.keys())
val = list(db.values())
m = max(val)
pos = 0
for k in key:
if m == db[k]:
print(key[pos])
else:
pos ... |
# 451. Sort Characters By Frequency
# Runtime: 60 ms, faster than 42.47% of Python3 online submissions for Sort Characters By Frequency.
# Memory Usage: 16.9 MB, less than 16.64% of Python3 online submissions for Sort Characters By Frequency.
class Solution:
def frequencySort(self, s: str) -> str:
if no... | class Solution:
def frequency_sort(self, s: str) -> str:
if not s:
return s
s = list(s)
s.sort()
all_strings = []
cur_sb = [s[0]]
for c in s[1:]:
if cur_sb[-1] != c:
all_strings.append(''.join(cur_sb))
cur_sb = ... |
'''
Venn diagram plotting routines.
Tests. Meant to be used via py.test.
Copyright 2012, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
'''
| """
Venn diagram plotting routines.
Tests. Meant to be used via py.test.
Copyright 2012, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
""" |
# Advent of Code Solutions: Day 5, part 2
# https://github.com/emddudley/advent-of-code-solutions
def is_nice(naughty_or_nice):
repeating_pair = False
for i in range(0, len(naughty_or_nice) - 2):
first_pair = naughty_or_nice[i:(i + 2)]
for j in range(i + 2, len(naughty_or_nice) - 2):
... | def is_nice(naughty_or_nice):
repeating_pair = False
for i in range(0, len(naughty_or_nice) - 2):
first_pair = naughty_or_nice[i:i + 2]
for j in range(i + 2, len(naughty_or_nice) - 2):
second_pair = naughty_or_nice[j:j + 2]
if second_pair == first_pair:
re... |
s = set([1,2,3])
t = set([3,4,5])
s.union(t) # set([1,2,3,4,5])
s.intersection(t) # set([3])
s.difference(t) # set([4,5]) | s = set([1, 2, 3])
t = set([3, 4, 5])
s.union(t)
s.intersection(t)
s.difference(t) |
#Add a c key with a value of 3 to the dictionary and print out the updated dictinary
d = {"a": 1, "b": 2}
d["c"] = 3
print(d)
| d = {'a': 1, 'b': 2}
d['c'] = 3
print(d) |
# Write your code below this line
print("Hello world!\nHello world!\nHello World!")
# Day 1 - Exercise 1 - Printing
print('Day 1 - Python Print Function')
print("The function is declared like this:")
print("print('what to print')")
print("Hello" + " " + "Mahtab")
# Day 1 - Exercise 2 - Debugging
# Fix the code ... | print('Hello world!\nHello world!\nHello World!')
print('Day 1 - Python Print Function')
print('The function is declared like this:')
print("print('what to print')")
print('Hello' + ' ' + 'Mahtab')
print('Day 1 - String Manipulation')
print('String Concatenation is done with the' + ' "+" ' + 'sign.')
print('e.g. print(... |
BriefRevisionTemplate = {
'fields': [':pk', 'object_id'],
'allow_missing': True,
}
| brief_revision_template = {'fields': [':pk', 'object_id'], 'allow_missing': True} |
{
# Ports for the left-side motors
"leftMotorPorts": [0, 1],
# Ports for the right-side motors
"rightMotorPorts": [2, 3],
# NOTE: Inversions of the slaves (i.e. any motor *after* the first on
# each side of the drive) are *with respect to their master*. This is
# different from the other po... | {'leftMotorPorts': [0, 1], 'rightMotorPorts': [2, 3], 'leftMotorsInverted': [False, False], 'rightMotorsInverted': [False, False], 'encoderPPR': 512, 'leftEncoderInverted': False, 'rightEncoderInverted': False, 'gearing': 1, 'wheelDiameter': 0.333, 'turn': False} |
class VolumeAllocatedSize(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_lun_size_allocated(idx_name)
class VolumeAllocatedSizeColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_luns()
| class Volumeallocatedsize(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_lun_size_allocated(idx_name)
class Volumeallocatedsizecolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_luns() |
@schema.resolver("Query.hero")
def resolve_hero(_root, ctx, _info):
return ctx["db"][2000] # R2-D2
@schema.resolver("Query.characters")
def resolve_characters(_root, ctx, _info):
return ctx["db"].items()
@schema.resolver("Query.character")
def resolve_character(_root, ctx, _info, *, id):
return ctx["db... | @schema.resolver('Query.hero')
def resolve_hero(_root, ctx, _info):
return ctx['db'][2000]
@schema.resolver('Query.characters')
def resolve_characters(_root, ctx, _info):
return ctx['db'].items()
@schema.resolver('Query.character')
def resolve_character(_root, ctx, _info, *, id):
return ctx['db'].get(id, ... |
def year_of_daily_effort(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
habit_and_time = args
total_yearly = int(habit_and_time[1])*365
print('At the end of the year you will practice ' + str(habit_and_time[0])+' a total of '+str(total_yearly)+' minutes!')
return wrap... | def year_of_daily_effort(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
habit_and_time = args
total_yearly = int(habit_and_time[1]) * 365
print('At the end of the year you will practice ' + str(habit_and_time[0]) + ' a total of ' + str(total_yearly) + ' minutes!')
re... |
def addOne(a):
return a+1
def subOne(a):
return a-1
a = 0
b = subOne(addOne(a))
| def add_one(a):
return a + 1
def sub_one(a):
return a - 1
a = 0
b = sub_one(add_one(a)) |
# iterative version of greatest common divisor
def gcdIter(a, b):
gcd = min(a, b)
while gcd > 0:
if a % gcd == 0 and b % gcd == 0:
return gcd
gcd -= 1
| def gcd_iter(a, b):
gcd = min(a, b)
while gcd > 0:
if a % gcd == 0 and b % gcd == 0:
return gcd
gcd -= 1 |
def selection_sort(L):
suffixSt = 0
while suffixSt != len(L):
for i in range(suffixSt, len(L)):
if L[I] < L[suffixSt]:
L[suffixSt], L[i] = L[i], L[suffixSt]
suffixSt += 1
| def selection_sort(L):
suffix_st = 0
while suffixSt != len(L):
for i in range(suffixSt, len(L)):
if L[I] < L[suffixSt]:
(L[suffixSt], L[i]) = (L[i], L[suffixSt])
suffix_st += 1 |
class DeprecatedWrapper(ImportError):
pass
class Deprecated:
def __init__(self, wrapper_name, orig_version, new_version):
self.name = wrapper_name
self.old_version, self.new_version = orig_version, new_version
def __call__(self, env, *args, **kwargs):
raise DeprecatedWrapper(f"{se... | class Deprecatedwrapper(ImportError):
pass
class Deprecated:
def __init__(self, wrapper_name, orig_version, new_version):
self.name = wrapper_name
(self.old_version, self.new_version) = (orig_version, new_version)
def __call__(self, env, *args, **kwargs):
raise deprecated_wrapper(... |
alg.aggregation (
[ "n_name" ],
[ ( Reduction.SUM, "revenue", "sum_rev" ) ],
alg.map (
"revenue",
scal.MulExpr (
scal.AttrExpr ( "l_extendedprice" ),
scal.SubExpr (
scal.ConstExpr ( "1.0f", Type.FLOAT ),
scal.AttrExpr ( "l_discount" ... | alg.aggregation(['n_name'], [(Reduction.SUM, 'revenue', 'sum_rev')], alg.map('revenue', scal.MulExpr(scal.AttrExpr('l_extendedprice'), scal.SubExpr(scal.ConstExpr('1.0f', Type.FLOAT), scal.AttrExpr('l_discount'))), alg.join([('l_suppkey', 's_suppkey'), ('s_nationkey', 'n_nationkey')], alg.scan('supplier'), alg.join(('l... |
#
# PySNMP MIB module PDN-DOMAIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-DOMAIN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:38:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ... |
#
# PySNMP MIB module DATALINK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DATALINK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21:37 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, single_value_constraint, value_size_constraint) ... |
phones = {"guna":"23456432","rakulan":"3435643","mike":"324532","tim":"3456434","flo":"324565323","david":"4543245"}
while True:
user_data = input("Enter the name: ")
phone_number = phones[user_data]
print(f"{user_data} : {phone_number}") | phones = {'guna': '23456432', 'rakulan': '3435643', 'mike': '324532', 'tim': '3456434', 'flo': '324565323', 'david': '4543245'}
while True:
user_data = input('Enter the name: ')
phone_number = phones[user_data]
print(f'{user_data} : {phone_number}') |
def assignmentOne():
age = input("Enter Your Age: ")
age = int(age)
yearsLeft = 100 - age
return print(f"You Have {yearsLeft} years until you turn 100!")
def assignmentTwo():
first = input("Enter the number of tea cups you want to buy from shop 1: ")
second = input("Enter the number of tea cups you want ... | def assignment_one():
age = input('Enter Your Age: ')
age = int(age)
years_left = 100 - age
return print(f'You Have {yearsLeft} years until you turn 100!')
def assignment_two():
first = input('Enter the number of tea cups you want to buy from shop 1: ')
second = input('Enter the number of tea c... |
class Solution:
def calculateTime(self, keyboard: str, word: str) -> int:
# create hash table to record the index of characters
tb = {char:i for i,char in enumerate(keyboard)}
# print(tb)
time = 0
for j in range(len(word)):
if j == 0:
time... | class Solution:
def calculate_time(self, keyboard: str, word: str) -> int:
tb = {char: i for (i, char) in enumerate(keyboard)}
time = 0
for j in range(len(word)):
if j == 0:
time += tb[word[j]]
else:
time += abs(tb[word[j]] - tb[word[j... |
k=int(input())
x=0;
for i in range(1,k+1):
x=x+i
print(x)
| k = int(input())
x = 0
for i in range(1, k + 1):
x = x + i
print(x) |
name = "S - Origami Triangles"
description = "Randomly-placed, chained triangles"
knob1 = "X Position"
knob2 = "Y Position"
knob3 = "Size"
knob4 = "Color"
released = "March 21 2017"
| name = 'S - Origami Triangles'
description = 'Randomly-placed, chained triangles'
knob1 = 'X Position'
knob2 = 'Y Position'
knob3 = 'Size'
knob4 = 'Color'
released = 'March 21 2017' |
#python exceptions let you deal
#with unexpected results
try:
print(a) #this will throw an exception because a is not defined
except:
print("a is not defined!")
#there are specific errors
try:
print(a) #will throw an exception
except NameError:
print("a is still not defined!")
except:
print("Some... | try:
print(a)
except:
print('a is not defined!')
try:
print(a)
except NameError:
print('a is still not defined!')
except:
print('Something else went wrong')
print(a) |
def getAllPossibleMoves():
moves = set()
rows = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
columns = ['1', '2', '3', '4', '5', '6', '7', '8']
def horizontal(row, column):
return [row + column + row + col for col in columns if col != column]
def vertical(row, col):
return [row + col... | def get_all_possible_moves():
moves = set()
rows = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
columns = ['1', '2', '3', '4', '5', '6', '7', '8']
def horizontal(row, column):
return [row + column + row + col for col in columns if col != column]
def vertical(row, col):
return [row + co... |
# Clases base
class Subnet:
def __init__(self, id, name, cidr, network):
self.id = id
self.name = name
self.cidr = unicode(cidr)
self.network = network
def create_nic(self, private_ip, name=None):
raise NotImplementedError('create_nic not implemented for this driver')... | class Subnet:
def __init__(self, id, name, cidr, network):
self.id = id
self.name = name
self.cidr = unicode(cidr)
self.network = network
def create_nic(self, private_ip, name=None):
raise not_implemented_error('create_nic not implemented for this driver')
def list... |
class Validator:
def isEven(self, num):
if num % 2 == 0:
return True
else:
return False
def isInt(self, num):
if type(num) == int:
return True
else:
return False
def isStr(self, num):
if type(num) == str:
... | class Validator:
def is_even(self, num):
if num % 2 == 0:
return True
else:
return False
def is_int(self, num):
if type(num) == int:
return True
else:
return False
def is_str(self, num):
if type(num) == str:
... |
with open('output.out', 'w') as output:
with open('B-large-practice.in') as fp:
next(fp)
for idx, line in enumerate(fp):
output.write("Case #%d: %s" % (idx+1, ' '.join(line.split()[::-1])))
output.write("\n")
output.close()
| with open('output.out', 'w') as output:
with open('B-large-practice.in') as fp:
next(fp)
for (idx, line) in enumerate(fp):
output.write('Case #%d: %s' % (idx + 1, ' '.join(line.split()[::-1])))
output.write('\n')
output.close() |
def buffer(xs):
for i in range(20):
yield xs + ['', []]
def scale(xs):
for i in range(len(xs)):
yield xs + [[i]]
yield xs + [[]]
def timsort(xs):
yield from buffer(xs)
# https://en.wikipedia.org/wiki/Timsort
# https://github.com/python/cpython/blob/master/Objects/listsort.tx... | def buffer(xs):
for i in range(20):
yield (xs + ['', []])
def scale(xs):
for i in range(len(xs)):
yield (xs + [[i]])
yield (xs + [[]])
def timsort(xs):
yield from buffer(xs)
def binary_search(xs, target_i, start, end, dispatch):
yield (xs + [dispatch, [start, end]])
... |
nums = [3,41,12,9,74,15]
print((len(nums)))
print(max(nums))
print(min(nums))
print(sum(nums))
newsum = sum(nums)/len(nums)
print("{:.4f}".format(newsum)) | nums = [3, 41, 12, 9, 74, 15]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
newsum = sum(nums) / len(nums)
print('{:.4f}'.format(newsum)) |
#!/usr/bin/env python3
n = 3
# Task 2.1: Real score S = 3.914193, normalized total score is 0.740268
# Task 2.2: Real score S = 12.509336, normalized total score is 0.948987
# Task 2.3: Real score S = 61.396589, normalized total score is 0.994458
# Task 2.4: Requires optimization
fi = open('../task2/input_'+str(n)+... | n = 3
fi = open('../task2/input_' + str(n) + '.txt')
fo = open('../task2/task2.' + str(n) + '.test.txt', 'w')
t = int(fi.readline())
marks = []
for line in fi:
marks.append(list(line.strip()))
fi.close()
df = pd.DataFrame(marks).T
perbasestates = pd.DataFrame(df.apply(''.join, axis=1))[0].tolist()
perbasestatecnts ... |
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
p = list(range(1, m + 1))
r = []
for i in queries:
idx = p.index(i)
r.append(idx)
del p[idx]
p.insert(0, i)
return r
| class Solution:
def process_queries(self, queries: List[int], m: int) -> List[int]:
p = list(range(1, m + 1))
r = []
for i in queries:
idx = p.index(i)
r.append(idx)
del p[idx]
p.insert(0, i)
return r |
# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200(both included).
# The numbers obtained should be printed in a comma seperated sequence on a single line
# Hints: Consider use range(#begin, #end) method
print("Numbers between 2000 and 3200, ... | print('Numbers between 2000 and 3200, 2000 and 3200 included, that are multiples of 7 but not 5')
for num in range(2000, 3200 + 1):
if num % 7 == 0 and num % 5 != 0:
print(num, end=',') |
# from trend import trend
# import requests
#print(trend("AAPL"))
#### check for the previous trend ####
#### Upward trend required for this pattern ####
##*****#####**** hanging man not as accurate in predicting as the hammer ****####****####
def hanging_man(arg):
c = arg['close']
... | def hanging_man(arg):
c = arg['close']
h = arg['high']
l = arg['low']
o = arg['open']
if c > o:
if c - o <= 2 * (o - l) and c - o <= 0.075 * ((c + o) / 2):
return 1
elif o - c <= 2 * (c - l) and o - c <= 0.075 * ((c + o) / 2):
return 1
return 0 |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Age, obj[4]: Education, obj[5]: Occupation, obj[6]: Bar, obj[7]: Coffeehouse, obj[8]: Restaurant20to50, obj[9]: Direction_same, obj[10]: Distance
# {"feature": "Time", "instances": 23, "metric_value": 0.9877, "depth": 1}
if obj[1]>0:
#... | def find_decision(obj):
if obj[1] > 0:
if obj[8] > 0.0:
if obj[10] <= 2:
if obj[9] <= 0:
if obj[2] > 0:
return 'True'
elif obj[2] <= 0:
if obj[4] <= 2:
return 'Fals... |
class Player:
wincount = 0
losecount = 0
gamecount = 0
def __init__(self, name, strategy):
self.name = name
self.strategy = strategy
def nextHand(self):
return self.strategy.nextHand()
def win(self):
self.strategy.study(True)
self.wincount += 1
... | class Player:
wincount = 0
losecount = 0
gamecount = 0
def __init__(self, name, strategy):
self.name = name
self.strategy = strategy
def next_hand(self):
return self.strategy.nextHand()
def win(self):
self.strategy.study(True)
self.wincount += 1
... |
#Conor O'Riordan
#Return total amount of times a letter
#occurs in a text
#open file from directory
#this file on my desktop
#book name is The Catcher in the Rye
with open('checker.txt','r') as f:
#reads out the full text
readfile = f.read()
#variable splits white space between words in text
wor... | with open('checker.txt', 'r') as f:
readfile = f.read()
words = readfile.split()
letter = [list(line.strip()) for line in words]
print(len(words))
print(len(letter))
u = input('enter uppercase letter: ')
ll = input('enter lower case letter ')
upperletter = u
lowerletter = ll
freq = {}
for line in letter:
... |
# with open("aaaa.txt", "r") as f:
# print(f.read())
try:
with open("aaaa.txt", "r") as f:
print(f.read())
except FileNotFoundError as e:
print(e)
with open("aaaa.txt", "w") as f:
f.write("I'm no_file.txt")
print("new file 'no_file.txt' has been written")
d = {"name": "f1", "ag... | try:
with open('aaaa.txt', 'r') as f:
print(f.read())
except FileNotFoundError as e:
print(e)
with open('aaaa.txt', 'w') as f:
f.write("I'm no_file.txt")
print("new file 'no_file.txt' has been written")
d = {'name': 'f1', 'age': 2}
l = [1, 2, 3]
try:
v = d['gender']
l[3] = 4
... |
users_number = int(input('Please, enter your value: '))
fibonacci = [0, 1]
while fibonacci[-1] < users_number:
if fibonacci[-1] + fibonacci[-2] > users_number:
break
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print('Your fibonacci sequence is: {}'.format(fibonacci)) | users_number = int(input('Please, enter your value: '))
fibonacci = [0, 1]
while fibonacci[-1] < users_number:
if fibonacci[-1] + fibonacci[-2] > users_number:
break
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print('Your fibonacci sequence is: {}'.format(fibonacci)) |
plt.figure(figsize=(10, 10))
axis = plt.gca()
np.set_printoptions(suppress=True)
infinitif = ['manger', 'lancer', 'jouer', 'cuisiner', 'sortir']
conjugaison = ['mange', 'lance', 'joue', 'cuisine', 'sors']
x = [word_emb_tsne[w2idx[w], 0] for w in infinitif] + [word_emb_tsne[w2idx[w], 0] for w in conjugaison]
y = [word... | plt.figure(figsize=(10, 10))
axis = plt.gca()
np.set_printoptions(suppress=True)
infinitif = ['manger', 'lancer', 'jouer', 'cuisiner', 'sortir']
conjugaison = ['mange', 'lance', 'joue', 'cuisine', 'sors']
x = [word_emb_tsne[w2idx[w], 0] for w in infinitif] + [word_emb_tsne[w2idx[w], 0] for w in conjugaison]
y = [word_e... |
# def pruneList(l1,l2):
# for value1 in l1:
# for value2 in l2:
# if value2 in l1:
# l1.remove(value2)
# elif value1 in l2:
# l1.remove(value1)
# return l1
def pruneList(l1, l2):
return [x for x in l1 if x not in l2]
if __name__ == "__main__":
print(pruneList([1, 2], [1]))... | def prune_list(l1, l2):
return [x for x in l1 if x not in l2]
if __name__ == '__main__':
print(prune_list([1, 2], [1]))
print(prune_list([1, 2], [1]))
print(prune_list([1, 2, 2], []))
print(prune_list([], [1, 2])) |
def get(table) -> list:
with open(rf"database/data/{table}.csv", 'r') as file:
return file.readlines()
def get_by_id(table, id):
with open(rf"database/data/{table}.csv", 'r') as file:
lines = file.readlines()
for line in lines[1:]:
line_formatted = line.split(',$')
if lin... | def get(table) -> list:
with open(f'database/data/{table}.csv', 'r') as file:
return file.readlines()
def get_by_id(table, id):
with open(f'database/data/{table}.csv', 'r') as file:
lines = file.readlines()
for line in lines[1:]:
line_formatted = line.split(',$')
if line_for... |
vars_namespace = 2 # yet, only logic variables used ==> only one namespace, if variables from multiply ns used ==> change in src-code
# Variable-symbol-path, namespace (ns=2;Application.GVLpython.rABC) ==>
# [Application.GVLpython.rABC, 2]
startEmulation = ["Application.GVLpython.bAutomatic", 2]
initDone = False
PosMo... | vars_namespace = 2
start_emulation = ['Application.GVLpython.bAutomatic', 2]
init_done = False
pos_mode__ack__rot__tor = ['Application.GVLpython.bPosModeAck_Rot_Tor', 2]
pos_mode__ack__rot__verteidiung = ['Application.GVLpython.bPosModeAck_Rot_Verteidigung', 2]
pos_mode__ack__rot__mittelfeld = ['Application.GVLpython.b... |
s = input()
ns = []
ups = True
for i in range(len(s)):
if ups == True or (s[i].lower() == 'i' and (i == 0 or s[i-1].isalpha() == False) and (i == len(s)-1 or s[i+1].isalpha() == False)):
ns.append(s[i].upper())
elif s[i].isalpha():
ns.append(s[i].lower())
else:
ns.append(s[i])
if... | s = input()
ns = []
ups = True
for i in range(len(s)):
if ups == True or (s[i].lower() == 'i' and (i == 0 or s[i - 1].isalpha() == False) and (i == len(s) - 1 or s[i + 1].isalpha() == False)):
ns.append(s[i].upper())
elif s[i].isalpha():
ns.append(s[i].lower())
else:
ns.append(s[i])
... |
class QueueInformationPacket:
def __init__(self):
self.type = "QUEUEINFORMATION"
self.curPos = -1
self.maxPos = -1
def read(self, reader):
self.curPos = reader.readUnsignedShort()
self.maxPos = reader.readUnsignedShort()
| class Queueinformationpacket:
def __init__(self):
self.type = 'QUEUEINFORMATION'
self.curPos = -1
self.maxPos = -1
def read(self, reader):
self.curPos = reader.readUnsignedShort()
self.maxPos = reader.readUnsignedShort() |
# 921160700 - Escape! - PQ
if sm.hasMobsInField():
sm.chat("Eliminate the boss before continuing")
else:
sm.teleportToPortal(6)
sm.dispose()
| if sm.hasMobsInField():
sm.chat('Eliminate the boss before continuing')
else:
sm.teleportToPortal(6)
sm.dispose() |
def sumZero(n: int) -> list[int]:
half = n // 2
pos = list(range(1, half + 1))
neg = [-x for x in pos]
if n % 2 != 0:
return pos + neg + [0]
else:
return pos + neg | def sum_zero(n: int) -> list[int]:
half = n // 2
pos = list(range(1, half + 1))
neg = [-x for x in pos]
if n % 2 != 0:
return pos + neg + [0]
else:
return pos + neg |
print('Hello World!')
file_object = open('thefile.txt')
try:
list_of_all_the_lines = file_object.readlines()
for line in list_of_all_the_lines:
print(">>>>>" + line);
finally:
file_object.close()
output = open('output.txt', 'w')
output.write("h1\n")
output.write("h2\n")
output.close() | print('Hello World!')
file_object = open('thefile.txt')
try:
list_of_all_the_lines = file_object.readlines()
for line in list_of_all_the_lines:
print('>>>>>' + line)
finally:
file_object.close()
output = open('output.txt', 'w')
output.write('h1\n')
output.write('h2\n')
output.close() |
{
"make_global_settings": [
["CC", "/usr/bin/clang"],
["LINK", "/usr/bin/clang"]
],
"targets": [
{
"target_name": "test",
"type": "executable",
"sources": [
"lib/jamlib/tests/cachetest.c",
"lib/jamlib/simplelist.c",
"lib/jamlib/nvoid.c"
],
'link_se... | {'make_global_settings': [['CC', '/usr/bin/clang'], ['LINK', '/usr/bin/clang']], 'targets': [{'target_name': 'test', 'type': 'executable', 'sources': ['lib/jamlib/tests/cachetest.c', 'lib/jamlib/simplelist.c', 'lib/jamlib/nvoid.c'], 'link_settings': {'libraries': ['-lm', '-lbsd', '-lpthread', '-lcbor', '-lnanomsg', '-l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def ordered_union(S, T):
return S + [t for t in T if t not in S]
def ordered_intersect(S, T):
return [s for s in S if s in T]
def ordered_setminus(S, T):
return [s for s in S if s not in T]
def ordered_symmdiff(S, T):
S1 = [s for s in S if s not in T... | def ordered_union(S, T):
return S + [t for t in T if t not in S]
def ordered_intersect(S, T):
return [s for s in S if s in T]
def ordered_setminus(S, T):
return [s for s in S if s not in T]
def ordered_symmdiff(S, T):
s1 = [s for s in S if s not in T]
t1 = [t for t in T if t not in S]
return ... |
# This is just one possible solution, there are
# several ways to do this using `delayed`
sums = []
counts = []
for fn in filenames:
# Read in file
df = delayed(pd.read_csv)(fn)
# Groupby origin airport
by_origin = df.groupby('Origin')
# Sum of all departure delays by origin
total = by_origin... | sums = []
counts = []
for fn in filenames:
df = delayed(pd.read_csv)(fn)
by_origin = df.groupby('Origin')
total = by_origin.DepDelay.sum()
count = by_origin.DepDelay.count()
sums.append(total)
counts.append(count)
(sums, counts) = compute(sums, counts)
total_delays = sum(sums)
n_flights = sum(co... |
def main():
print ('Extract join result')
f = open('../data/join_results/sj.12_30.log')
output_f = open('../data/join_results/sj.12_30.log.csv', 'w')
algorithms = ['bnlj', 'pbsm', 'dj', 'repj']
header = 'dataset1,dataset2,'
for algo in algorithms:
header += '{}_result_size,'.format(algo)... | def main():
print('Extract join result')
f = open('../data/join_results/sj.12_30.log')
output_f = open('../data/join_results/sj.12_30.log.csv', 'w')
algorithms = ['bnlj', 'pbsm', 'dj', 'repj']
header = 'dataset1,dataset2,'
for algo in algorithms:
header += '{}_result_size,'.format(algo)
... |
def convert(time):
TIM = int(f"{time:04d}"[:2])*60 + int(f"{time:04d}"[2:])
times = {
"in Ottawa": TIM,
"in Victoria": TIM-180,
"in Edmonton": TIM-120,
"in Winnipeg": TIM-60,
"in Toronto": TIM,
"in Halifax": TIM+60,
"in St. John's": TIM+90
}
for ... | def convert(time):
tim = int(f'{time:04d}'[:2]) * 60 + int(f'{time:04d}'[2:])
times = {'in Ottawa': TIM, 'in Victoria': TIM - 180, 'in Edmonton': TIM - 120, 'in Winnipeg': TIM - 60, 'in Toronto': TIM, 'in Halifax': TIM + 60, "in St. John's": TIM + 90}
for i in times:
if times[i] <= 0:
ti... |
{
'targets':
[
{
'target_name': 'jsoncpp',
'type': 'static_library',
'sources':
[
'jsoncpp/bundled/jsoncpp.cpp'
],
'direct_dependent_settings':
{
'include_dirs':
[
'jsoncpp/bundled'
]
},
'conditions':
[
... | {'targets': [{'target_name': 'jsoncpp', 'type': 'static_library', 'sources': ['jsoncpp/bundled/jsoncpp.cpp'], 'direct_dependent_settings': {'include_dirs': ['jsoncpp/bundled']}, 'conditions': [['OS != "win"', {'cflags': ['-std=c++11', '-Wall', '-Wextra', '-Wno-unused-parameter']}], ['OS == "mac"', {'xcode_settings': {'... |
fruit_list = ["apple", "banana", "orange"]
# let user add their own fruit
user_fruit = input("Please name a fruit: ")
fruit_list.append(user_fruit)
# print each fruit in a line
for fruit in fruit_list:
print("This is a cool fruit: " + fruit)
# print explicitly the fruit that was entered by the user
last_fruit_in... | fruit_list = ['apple', 'banana', 'orange']
user_fruit = input('Please name a fruit: ')
fruit_list.append(user_fruit)
for fruit in fruit_list:
print('This is a cool fruit: ' + fruit)
last_fruit_index = len(fruit_list) - 1
print('You especially like: {}'.format(fruit_list[last_fruit_index])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.