content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def setData(field, value, path):
f = open(path, "r")
lines = f.readlines()
f.close()
f = open(path, "w+")
for line in lines:
if (line.find(field) != -1):
f.write(field + "=" + str(value) + "\n")
else:
f.write(line)
f.close()
return True
def getDat... | def set_data(field, value, path):
f = open(path, 'r')
lines = f.readlines()
f.close()
f = open(path, 'w+')
for line in lines:
if line.find(field) != -1:
f.write(field + '=' + str(value) + '\n')
else:
f.write(line)
f.close()
return True
def get_data(pa... |
class Event:
def __init__(self):
self.handlers = []
def call(self, *args, **kwargs):
for h in self.handlers:
h(*args, **kwargs)
def __call__(self, *args, **kwargs):
self.call(*args, **kwargs)
| class Event:
def __init__(self):
self.handlers = []
def call(self, *args, **kwargs):
for h in self.handlers:
h(*args, **kwargs)
def __call__(self, *args, **kwargs):
self.call(*args, **kwargs) |
class ExampleJob:
def __init__(self, id):
self.id = id
self.retry_count = 10
self.retry_pause_sec = 10
def run(self, runtime):
pass | class Examplejob:
def __init__(self, id):
self.id = id
self.retry_count = 10
self.retry_pause_sec = 10
def run(self, runtime):
pass |
#! /usr/bin/env python
__author__ = 'Tser'
__email__ = '807447312@qq.com'
__project__ = 'jicaiauto'
__script__ = '__version__.py'
__create_time__ = '2020/7/15 23:21'
VERSION = (0, 0, 2, 0)
__version__ = '.'.join(map(str, VERSION)) | __author__ = 'Tser'
__email__ = '807447312@qq.com'
__project__ = 'jicaiauto'
__script__ = '__version__.py'
__create_time__ = '2020/7/15 23:21'
version = (0, 0, 2, 0)
__version__ = '.'.join(map(str, VERSION)) |
_base_ = './pascal_voc12.py'
# dataset settings
data = dict(
samples_per_gpu=2,
train=dict(
ann_dir=['SegmentationClass', 'SegmentationClassAug'],
split=[
'ImageSets/Segmentation/train.txt',
'ImageSets/Segmentation/aug.txt'
]))
| _base_ = './pascal_voc12.py'
data = dict(samples_per_gpu=2, train=dict(ann_dir=['SegmentationClass', 'SegmentationClassAug'], split=['ImageSets/Segmentation/train.txt', 'ImageSets/Segmentation/aug.txt'])) |
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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 ... | user_search_all = '(objectClass=person)'
user_search_by_dn = '(&(objectClass=person)(distinguishedName={}))'
user_search_after_date = '(&(objectClass=person)(whenChanged>=%s))'
group_search_all = '(objectClass=group)'
group_search_by_dn = '(&(objectClass=group)(distinguishedName={}))'
group_search_after_date = '(&(obje... |
class StatusWirelessStaRemoteUnms:
status: int
timestamp: str
def __init__(self, data):
self.status = data.get("status")
self.timestamp = data.get("timestamp")
| class Statuswirelessstaremoteunms:
status: int
timestamp: str
def __init__(self, data):
self.status = data.get('status')
self.timestamp = data.get('timestamp') |
class Zone:
def __init__(self) -> None:
self._display_name = ""
self._offset = 0
def get_display_name(self) -> str:
return self._display_name
def get_offset(self) -> int:
return self._offset
| class Zone:
def __init__(self) -> None:
self._display_name = ''
self._offset = 0
def get_display_name(self) -> str:
return self._display_name
def get_offset(self) -> int:
return self._offset |
def is_prime(n):
for x in range(2, n):
if n % x == 0:
return False
return True
def get_prime_numbers(n):
for x in range(n, 1, -1):
if is_prime(x):
yield x
def get_two_sum(primes, number):
for i, q in enumerate(primes):
next_values = primes[i + 1:]
... | def is_prime(n):
for x in range(2, n):
if n % x == 0:
return False
return True
def get_prime_numbers(n):
for x in range(n, 1, -1):
if is_prime(x):
yield x
def get_two_sum(primes, number):
for (i, q) in enumerate(primes):
next_values = primes[i + 1:]
... |
opcodes = {
'STOP': [0x00, 0, 0, 0],
'ADD': [0x01, 2, 1, 3],
'MUL': [0x02, 2, 1, 5],
'SUB': [0x03, 2, 1, 3],
'DIV': [0x04, 2, 1, 5],
'SDIV': [0x05, 2, 1, 5],
'MOD': [0x06, 2, 1, 5],
'SMOD': [0x07, 2, 1, 5],
'ADDMOD': [0x08, 3, 1, 8],
'MULMOD': [0x09, 3, 1, 8],
'EXP': [0x0a, 2... | opcodes = {'STOP': [0, 0, 0, 0], 'ADD': [1, 2, 1, 3], 'MUL': [2, 2, 1, 5], 'SUB': [3, 2, 1, 3], 'DIV': [4, 2, 1, 5], 'SDIV': [5, 2, 1, 5], 'MOD': [6, 2, 1, 5], 'SMOD': [7, 2, 1, 5], 'ADDMOD': [8, 3, 1, 8], 'MULMOD': [9, 3, 1, 8], 'EXP': [10, 2, 1, 10], 'SIGNEXTEND': [11, 2, 1, 5], 'LT': [16, 2, 1, 3], 'GT': [17, 2, 1, ... |
singular_to_plural_dictionary = {
"1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"security-zone": "security-zones",
"time": "times",
"simple... | singular_to_plural_dictionary = {'1': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-cli... |
class Node:
def __init__(self, node_id, lon, lat, cluster_id_belongto: int):
self.node_id = int(node_id)
self.lon = lon
self.lat = lat
self.cluster_id_belongto = cluster_id_belongto | class Node:
def __init__(self, node_id, lon, lat, cluster_id_belongto: int):
self.node_id = int(node_id)
self.lon = lon
self.lat = lat
self.cluster_id_belongto = cluster_id_belongto |
# cook your dish here
t = int(input()) # Taking the Number of Test Cases
for i in range(t): # Looping over test cases
n = int(input()) # Taking the length of songs input
p = [int(i) for i in input().split()] # Taking the list of song... | t = int(input())
for i in range(t):
n = int(input())
p = [int(i) for i in input().split()]
k = int(input())
ele = p[k - 1]
for i in range(n):
j = 0
for j in range(0, n - i - 1):
if p[j] > p[j + 1]:
(p[j], p[j + 1]) = (p[j + 1], p[j])
ls = p.index(ele)
... |
print("Insert a string")
s = input()
print("Insert the number of times it will be repeated")
n = int(input())
res = ""
for i in range(n):
res = res + s
print(res)
| print('Insert a string')
s = input()
print('Insert the number of times it will be repeated')
n = int(input())
res = ''
for i in range(n):
res = res + s
print(res) |
#Twitter API Credentials
consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
access_token = 'accesstoken'
access_secret = 'accesssecret'
| consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
access_token = 'accesstoken'
access_secret = 'accesssecret' |
def findXorSum(arr, n):
Sum = 0
mul = 1
for i in range(30):
c_odd = 0
odd = 0
for j in range(n):
if ((arr[j] & (1 << i)) > 0):
odd = (~odd)
if (odd):
c_odd += 1
for j in range(n):
Sum += (mul * c_... | def find_xor_sum(arr, n):
sum = 0
mul = 1
for i in range(30):
c_odd = 0
odd = 0
for j in range(n):
if arr[j] & 1 << i > 0:
odd = ~odd
if odd:
c_odd += 1
for j in range(n):
sum += mul * c_odd % (10 ** 9 + 7)
... |
#
# PySNMP MIB module CISCOSB-TBI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TBI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
def pation(nums):
tmp = nums[0]
nums[0] = nums[1]
nums[1] = tmp
return 1
def main():
nums = [3,2,1]
p = pation(nums)
for n in nums:
print(n)
if __name__ == "__main__":
main()
| def pation(nums):
tmp = nums[0]
nums[0] = nums[1]
nums[1] = tmp
return 1
def main():
nums = [3, 2, 1]
p = pation(nums)
for n in nums:
print(n)
if __name__ == '__main__':
main() |
def create_grades_dict(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
no_return_list = []
for item in data:
no_return_list.append(item.strip('\n'))
no_spaces_list =[]
for item in no_return_list:
no_spaces_list.append(item.replace(' ',''))
list_of... | def create_grades_dict(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
no_return_list = []
for item in data:
no_return_list.append(item.strip('\n'))
no_spaces_list = []
for item in no_return_list:
no_spaces_list.append(item.replace(' ', ''))
li... |
#: docstring for CONSTANT1
CONSTANT1 = ""
CONSTANT2 = ""
| constant1 = ''
constant2 = '' |
l, r = map(int, input().split(" "))
if l == r:
print(l)
else:
print(2)
| (l, r) = map(int, input().split(' '))
if l == r:
print(l)
else:
print(2) |
class Session:
pass
class DB:
@staticmethod
def get_rds_host():
return '127.0.0.1'
def __init__(self, user, password, host, database) -> None:
pass
def getSession(self):
return Session
| class Session:
pass
class Db:
@staticmethod
def get_rds_host():
return '127.0.0.1'
def __init__(self, user, password, host, database) -> None:
pass
def get_session(self):
return Session |
CHAR_PLUS = ord(b'+')
CHAR_NEWLINE = ord(b'\n')
def buffered_blob(handle, bufsize):
backlog = b''
blob = b''
while True:
blob = handle.read(bufsize)
if blob == b'':
# Could be end of files
yield backlog
break
if backlog != b'':
blob ... | char_plus = ord(b'+')
char_newline = ord(b'\n')
def buffered_blob(handle, bufsize):
backlog = b''
blob = b''
while True:
blob = handle.read(bufsize)
if blob == b'':
yield backlog
break
if backlog != b'':
blob = backlog + blob
i = blob.rfin... |
# general I/O parameters
OUTPUT_TYPE = "images"
LABEL_MAPPING = "pascal"
VIDEO_FILE = "data/videos/Ylojarvi-gridiajo-two-guys-moving.mov"
OUT_RESOLUTION = None # (3840, 2024)
OUTPUT_PATH = "data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output"
FRAME_OFFSET = 600 # 1560
PROCESS_NUM_FRAMES = 300
COMPRESS_VIDEO =... | output_type = 'images'
label_mapping = 'pascal'
video_file = 'data/videos/Ylojarvi-gridiajo-two-guys-moving.mov'
out_resolution = None
output_path = 'data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output'
frame_offset = 600
process_num_frames = 300
compress_video = True
model = 'dauntless-sweep-2_resnet152_pasc... |
#!/usr/bin/env python
globaldecls = []
globalvars = {}
def add_new(decl):
if decl:
globaldecls.append(decl)
globalvars[decl.name] = decl
| globaldecls = []
globalvars = {}
def add_new(decl):
if decl:
globaldecls.append(decl)
globalvars[decl.name] = decl |
class BaseClass:
def __str__(self):
return self.__class__.__name__
def get_params(self, deep=True):
pass
def set_params(self, **params):
pass
class BaseTFWrapperSklearn(BaseClass):
def compile_graph(self, input_shapes):
pass
def get_tf_values(self,... | class Baseclass:
def __str__(self):
return self.__class__.__name__
def get_params(self, deep=True):
pass
def set_params(self, **params):
pass
class Basetfwrappersklearn(BaseClass):
def compile_graph(self, input_shapes):
pass
def get_tf_values(self, fetches, feed... |
# 289. Game of Life
class Solution:
def gameOfLife2(self, board) -> None:
rows, cols = len(board), len(board[0])
nextState = [row[:] for row in board]
dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1))
for i in range(rows):
for j in range(cols)... | class Solution:
def game_of_life2(self, board) -> None:
(rows, cols) = (len(board), len(board[0]))
next_state = [row[:] for row in board]
dirs = ((0, 1), (1, 0), (-1, 0), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1))
for i in range(rows):
for j in range(cols):
... |
'''https://leetcode.com/problems/merge-two-sorted-lists/'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Iterative Solution
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = ListNo... | """https://leetcode.com/problems/merge-two-sorted-lists/"""
class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = list_node(0)
while l1 is not None and l2 is not None... |
q = {
'get_page_id_from_frontier': "UPDATE crawldb.frontier \
SET occupied=True \
WHERE page_id=( \
SELECT page_id \
FROM crawldb.frontier as f \
... | q = {'get_page_id_from_frontier': 'UPDATE crawldb.frontier SET occupied=True WHERE page_id=( SELECT page_id FROM crawldb.frontier as f LEFT JOIN c... |
class NotarizerException(Exception):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
class NoSignatureFound(NotarizerException):
def __init__(self, error_message):
super().__init__(10, error_message)
class InvalidLabelSignat... | class Notarizerexception(Exception):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
class Nosignaturefound(NotarizerException):
def __init__(self, error_message):
super().__init__(10, error_message)
class Invalidlabelsignat... |
with open("input.txt", "r") as file:
numbers = list(map(int, file.readline().split(",")))
boards = []
line = file.readline() # throw away
while line:
board = []
for i in range(5):
line = file.readline()
board.append(list(map(int, filter(lambda x: len(x) > 0, line.... | with open('input.txt', 'r') as file:
numbers = list(map(int, file.readline().split(',')))
boards = []
line = file.readline()
while line:
board = []
for i in range(5):
line = file.readline()
board.append(list(map(int, filter(lambda x: len(x) > 0, line.strip().split... |
#
# PySNMP MIB module ELTEX-DOT3-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-DOT3-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:44 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')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) ... |
# operacoes matematica
x = 53
y = 42
# operacoes comuns
soma = x + y
mult = x * y
div = x / y
sub = x - y
# divisao inteira
div_int = x // y
# resto de Divisao
rest_div = x % y
# potencia
potencia = x ** y
print (soma)
print (mult)
print (div)
print (sub)
print ("Divisao inteira")
print (div_int)
print ("... | x = 53
y = 42
soma = x + y
mult = x * y
div = x / y
sub = x - y
div_int = x // y
rest_div = x % y
potencia = x ** y
print(soma)
print(mult)
print(div)
print(sub)
print('Divisao inteira')
print(div_int)
print('resto divisao')
print(rest_div)
print('potencia')
print(potencia) |
class Secret:
def __init__(self):
self._secret=99
self.__top_secret=100
x=Secret()
x._secret
x.__top_secret
x._Secret__top_secret | class Secret:
def __init__(self):
self._secret = 99
self.__top_secret = 100
x = secret()
x._secret
x.__top_secret
x._Secret__top_secret |
### ML SPECIFIC FUNCTIONS
### FOR FEATURE ENGINEERING
# ENCODE EVENT -- 1--event, 0--no event
def bin_event(x):
x=int(x)
if(x!=0):
return 1
else:
return 0
# YES OR NO
def bin_weather(x):
x=float(x)
if(x>0):
return 1
else:
return 0
# BIN PRECIPITATION TYPE
def bi... | def bin_event(x):
x = int(x)
if x != 0:
return 1
else:
return 0
def bin_weather(x):
x = float(x)
if x > 0:
return 1
else:
return 0
def bin_ptype(x):
if x == 1:
return 0
else:
return 0
d_bin = 10
def bin_delay(x):
x = float(x)
if ... |
class DependencyException(Exception):
def __init__(self, message, product):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.do_not_print = True
class SelfUpgradeException(Exception):
def __init__(self, message, parent_pid):
... | class Dependencyexception(Exception):
def __init__(self, message, product):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.do_not_print = True
class Selfupgradeexception(Exception):
def __init__(self, message, parent_pid):
s... |
for i in incorrect_idx:
print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i]))
# Plot two dimensions
_, ax = plt.subplots()
for n in np.unique(test_y):
idx = np.where(test_y == n)[0]
ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f"C{n}", label=f"Class {str(n)}")
for i, marker in zip(incor... | for i in incorrect_idx:
print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i]))
(_, ax) = plt.subplots()
for n in np.unique(test_y):
idx = np.where(test_y == n)[0]
ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f'C{n}', label=f'Class {str(n)}')
for (i, marker) in zip(incorrect_idx, ['x', 's', ... |
y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and np[0] >... | y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and (np[0] > ... |
# Software released under the MIT license (see project root for license file)
class Header():
def __init__(self):
self.version = 1
self.test_name = "not set"
# ------------------------------------------------------------------------------
class Base:
def __init__(self):
pa... | class Header:
def __init__(self):
self.version = 1
self.test_name = 'not set'
class Base:
def __init__(self):
pass
class Derived1(Base):
def __init__(self, i1=7, s2='Derived2'):
self.i1 = i1
self.s1 = s2
class Derived2(Base):
def __init__(self, i1=9, s2='De... |
# This is an example of staring two servo services
# and showing each servo in a separate tab in the browsee
# Start the servo services
s1 = Runtime.createAndStart("Servo1","Servo")
s2 = Runtime.createAndStart("Servo2","Servo")
# Start the webgui service without starting the browser
webgui = Runtime.create("WebGui","... | s1 = Runtime.createAndStart('Servo1', 'Servo')
s2 = Runtime.createAndStart('Servo2', 'Servo')
webgui = Runtime.create('WebGui', 'WebGui')
webgui.autoStartBrowser(False)
webgui.startService()
webgui.startBrowser('http://localhost:8888/#/service/Servo1')
sleep(1)
webgui.startBrowser('http://localhost:8888/#/service/Servo... |
# pylint: disable=missing-function-docstring, missing-module-docstring/
def compare_str_isnot() :
n = 'hello world'
a = 'hello world'
return n is not a
| def compare_str_isnot():
n = 'hello world'
a = 'hello world'
return n is not a |
def calcOccurrences(itemset: list) -> int:
return len(list(filter(lambda x: x == 1, itemset)))
def calcOccurrencesOfBoth(itemset1: list, itemset2: list) -> int:
count: int = 0
for i in range(len(itemset1)):
if itemset1[i] == 1 and itemset2[i] == 1:
count += 1
return count
def support(*itemsets) -> float:
... | def calc_occurrences(itemset: list) -> int:
return len(list(filter(lambda x: x == 1, itemset)))
def calc_occurrences_of_both(itemset1: list, itemset2: list) -> int:
count: int = 0
for i in range(len(itemset1)):
if itemset1[i] == 1 and itemset2[i] == 1:
count += 1
return count
def s... |
# names = ['LHL','YB','ZSH','LY','DYC']
# # print(str(x[0]) + str(x[1]) + str(x[2]) + str(x[3]) + str(x[4]));
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.low... | provinces = [['Kunming', 'Anning', 'Dali'], ['Beijing'], ['Shenzhen', 'GuangZhou', 'ZhuHai', 'Shantou']]
for province in provinces:
for city in province:
print(city) |
# Source : https://leetcode.com/problems/minimum-moves-to-convert-string/
# Author : foxfromworld
# Date : 10/12/2021
# First attempt
class Solution:
def minimumMoves(self, s: str) -> int:
index = 0
ret = 0
while index < len(s):
if s[index] == 'X':
ret += 1
... | class Solution:
def minimum_moves(self, s: str) -> int:
index = 0
ret = 0
while index < len(s):
if s[index] == 'X':
ret += 1
index += 3
else:
index += 1
return ret |
def fact(n):
return 1 if n == 0 else n*fact(n-1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n-x))
def b(x, n, p):
return comb(n, x) * p**x * (1-p)**(n-x)
l, r = list(map(float, input().split(" ")))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))
| def fact(n):
return 1 if n == 0 else n * fact(n - 1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n - x))
def b(x, n, p):
return comb(n, x) * p ** x * (1 - p) ** (n - x)
(l, r) = list(map(float, input().split(' ')))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3)) |
n, m = map(int, input().split())
for _ in range(n):
if input().find('LOVE') != -1:
print('YES')
exit()
print('NO')
| (n, m) = map(int, input().split())
for _ in range(n):
if input().find('LOVE') != -1:
print('YES')
exit()
print('NO') |
# base path to YOLO directory
MODEL_PATH = "yolo-coco"
# initialize minimum probability to filter weak detections along with
# the threshold when applying non-maxima suppression
MIN_CONF = 0.3
NMS_THRESH = 0.3
# boolean indicating if NVIDIA CUDA GPU should be used
USE_GPU = True
# define the minimum safe distance (in p... | model_path = 'yolo-coco'
min_conf = 0.3
nms_thresh = 0.3
use_gpu = True
min_distance = 50
flowmap_distance = 25
flowmap_size = 1000
flowmap_batch = 100
blocksize_x = 30
blocksize_y = BLOCKSIZE_X
output_x = 960
output_y = 540 |
# server.py flask configuration
# To use this file first export this path as SERVER_SETTINGS, before running
# the flask server. i.e. export SERVER_SETTINGS=config.py
LIRC_PATH = "/dev/lirc0"
SAVE_STATE_PATH = "/tmp/heatpump.state" | lirc_path = '/dev/lirc0'
save_state_path = '/tmp/heatpump.state' |
cx = 0
cy = 0
fsize = 0
counter = 0
class FunnyRect():
def setCenter(self, x,y):
self.cx = x
self.cy = y
def setSize(self, size):
self.size = size
def render(self):
rect(self.cx, self.cy, self.size, self.size)
funnyRect0b = FunnyRect()
funnyRect0b1 = FunnyRect()
def setu... | cx = 0
cy = 0
fsize = 0
counter = 0
class Funnyrect:
def set_center(self, x, y):
self.cx = x
self.cy = y
def set_size(self, size):
self.size = size
def render(self):
rect(self.cx, self.cy, self.size, self.size)
funny_rect0b = funny_rect()
funny_rect0b1 = funny_rect()
def... |
#
# PySNMP MIB module DVMRP-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:17:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
class Solution(object):
def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.a... | class Solution(object):
def combination_sum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combination_sum_recu(self, candidates, result, start, intermediate, target):
if target == 0:
resu... |
_EVT_INIT = 'INITIALIZE'
EVT_START = 'START'
EVT_READY = 'READY'
EVT_CLOSE = 'CLOSE'
EVT_STOP = 'STOP'
EVT_APP_LOAD = 'APP_LOAD'
EVT_APP_UNLOAD = 'APP_UNLOAD'
EVT_INTENT_SUBSCRIBE = 'INTENT_SUBSCRIBE'
EVT_INTENT_START = 'INTENT_START'
EVT_INTENT_END = 'INTENT_END'
EVT_ANY = '*'
_META_EVENTS = (
_EVT_INIT, EVT_... | _evt_init = 'INITIALIZE'
evt_start = 'START'
evt_ready = 'READY'
evt_close = 'CLOSE'
evt_stop = 'STOP'
evt_app_load = 'APP_LOAD'
evt_app_unload = 'APP_UNLOAD'
evt_intent_subscribe = 'INTENT_SUBSCRIBE'
evt_intent_start = 'INTENT_START'
evt_intent_end = 'INTENT_END'
evt_any = '*'
_meta_events = (_EVT_INIT, EVT_APP_LOAD, ... |
#
# PySNMP MIB module ADTRAN-AOS-DESKTOP-AUDITING (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-DESKTOP-AUDITING
# Produced by pysmi-0.3.4 at Wed May 1 11:13:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (ad_gen_aos_conformance, ad_gen_aos_switch) = mibBuilder.importSymbols('ADTRAN-AOS', 'adGenAOSConformance', 'adGenAOSSwitch')
(ad_identity,) = mibBuilder.importSymbols('ADTRAN-MIB', 'adIdentity')
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
... |
try:
raise ValueError("invalid!")
except ValueError as error:
print(str(error) + " input")
finally:
print("Finishd")
| try:
raise value_error('invalid!')
except ValueError as error:
print(str(error) + ' input')
finally:
print('Finishd') |
if __name__ == "__main__":
a = [1,2,3]
i = -1
print(a[-1])
for i in range(-1,-4,-1):
print(a[i]) | if __name__ == '__main__':
a = [1, 2, 3]
i = -1
print(a[-1])
for i in range(-1, -4, -1):
print(a[i]) |
N, W = map(int, input().split())
vw = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * W for _ in range(N)]
for i in range(N):
for w in range(W):
if w >= vw[i][1]:
dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w])
| (n, w) = map(int, input().split())
vw = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * W for _ in range(N)]
for i in range(N):
for w in range(W):
if w >= vw[i][1]:
dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w]) |
valor = int(input("Informe um valor: "))
triplo = valor * 3
contador = 0
while contador<5:
print(triplo)
contador = contador + 1
print("Acabou!")
| valor = int(input('Informe um valor: '))
triplo = valor * 3
contador = 0
while contador < 5:
print(triplo)
contador = contador + 1
print('Acabou!') |
__author__ = 'alse'
def content_length_test(train_metas, test_examples):
max_length = 0.0
min_length = 1000.0
for metadata in train_metas:
if max_length < metadata.length * 1.0 / metadata.size:
max_length = metadata.length * 1.0 / metadata.size
if min_length > metadata.length ... | __author__ = 'alse'
def content_length_test(train_metas, test_examples):
max_length = 0.0
min_length = 1000.0
for metadata in train_metas:
if max_length < metadata.length * 1.0 / metadata.size:
max_length = metadata.length * 1.0 / metadata.size
if min_length > metadata.length * ... |
while True:
op = input("Digite o Operador: ")
result = 0
if (op != '+') and (op != '-') and (op != '*') and (op != '/') and (op != '#'):
print("Operador invalido!")
else:
if op == '#':
print("Encerrando!")
break
n1 = float(input("Digite o valor 1: "))
... | while True:
op = input('Digite o Operador: ')
result = 0
if op != '+' and op != '-' and (op != '*') and (op != '/') and (op != '#'):
print('Operador invalido!')
else:
if op == '#':
print('Encerrando!')
break
n1 = float(input('Digite o valor 1: '))
... |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums_copy = nums.copy()
ret = []
count = 0
for i in range(len(nums)):
nums.pop(i)
nums.insert(0, nums_copy[i])
count = 0
j = 1
while j < len(... | class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
nums_copy = nums.copy()
ret = []
count = 0
for i in range(len(nums)):
nums.pop(i)
nums.insert(0, nums_copy[i])
count = 0
j = 1
while j < ... |
#############################################################
# rename or copy this file to config.py if you make changes #
#############################################################
# change this to your fully-qualified domain name to run a
# remote server. The default value of localhost will
# only allow connect... | config = {'cache': {'engine': 'diskcache', 'params': {'size_limit': int(4 * 2 ** 30)}}, 'data_sources': [{'name': 'local', 'url': 'file:///', 'start_path': ''}, {'name': 'ncnr', 'url': 'http://ncnr.nist.gov/pub/', 'start_path': 'ncnrdata', 'file_helper_url': 'https://ncnr.nist.gov/ncnrdata/listftpfiles_json.php'}, {'na... |
# Kernel config
c.IPKernelApp.pylab = 'inline' # if you want plotting support always in your notebook
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = u''
c.notebookApp.open_browser = True | c.IPKernelApp.pylab = 'inline'
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = u''
c.notebookApp.open_browser = True |
def check_parity(a: int, b: int, c: int) -> bool:
return a%2 == b%2 == c%2
def print_result(result: bool) -> None:
if result:
print("WIN")
else:
print("FAIL")
a, b, c = map(int, input().strip().split())
print_result(check_parity(a, b, c))
| def check_parity(a: int, b: int, c: int) -> bool:
return a % 2 == b % 2 == c % 2
def print_result(result: bool) -> None:
if result:
print('WIN')
else:
print('FAIL')
(a, b, c) = map(int, input().strip().split())
print_result(check_parity(a, b, c)) |
class employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' +last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
#instance variables contain data that is ... | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp1 = employee('corey', 'schafer', 50000)
emp2 = emp... |
# Copyright (c) 2013, Tomohiro Kusumi
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and... | major = 0
minor1 = 7
minor2 = 106
release = 1
def get_version():
return (MAJOR, MINOR1, MINOR2)
def get_release():
return (MAJOR, MINOR1, MINOR2, RELEASE)
def get_version_string():
return '{0}.{1}.{2}'.format(*get_version())
def get_release_string():
return '{0}.{1}.{2}-{3}'.format(*get_release())
... |
def file_name_for_format(file_format):
names = {
'json': 'data',
'xlsx': 'catalog'
}
file_name = names[file_format]
return file_name
| def file_name_for_format(file_format):
names = {'json': 'data', 'xlsx': 'catalog'}
file_name = names[file_format]
return file_name |
def main(request, response):
location = request.GET.first(b"location")
if request.method == u"OPTIONS":
if b"redirect_preflight" in request.GET:
response.status = 302
response.headers.set(b"Location", location)
else:
response.status = 200
response.hea... | def main(request, response):
location = request.GET.first(b'location')
if request.method == u'OPTIONS':
if b'redirect_preflight' in request.GET:
response.status = 302
response.headers.set(b'Location', location)
else:
response.status = 200
response.head... |
# set random number generator
np.random.seed(2020)
# initialize step_end, t_range, v and syn
step_end = int(t_max / dt)
t_range = np.linspace(0, t_max, num=step_end)
v = el * np.ones(step_end)
syn = i_mean * (1 + 0.1 * (t_max/dt) ** (0.5) * (2 * np.random.random(step_end) - 1))
# loop for step_end - 1 steps
for step... | np.random.seed(2020)
step_end = int(t_max / dt)
t_range = np.linspace(0, t_max, num=step_end)
v = el * np.ones(step_end)
syn = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random(step_end) - 1))
for step in range(1, step_end):
v[step] = v[step - 1] + dt / tau * (el - v[step - 1] + r * syn[step])
with pl... |
##Patterns: E0107
def test():
a = 1
##Err: E0107
++a
##Err: E0107
--a | def test():
a = 1
++a
--a |
#
# PySNMP MIB module BIANCA-BRICK-OSPF-ERR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-OSPF-ERR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:21:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
def deep_index(lst, w):
return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub]
class variable():
def __init__(self, name, val):
self.name = name
self.val = val
class variableHandler():
def __init__(self):
self.varList = []
def create(self, varName, varVal):
... | def deep_index(lst, w):
return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub]
class Variable:
def __init__(self, name, val):
self.name = name
self.val = val
class Variablehandler:
def __init__(self):
self.varList = []
def create(self, varName, varVal):
... |
#!/usr/bin/python3
# code for AdventOfCode day 1 http://adventofcode.com/2017/day/1
# get user input WITHOUT validation
# the code will fail when repeating non numeric chars
input_seq = input()
# append first algarism to the end of a new 'extended'
# that way we can use a single 'for' loop for everything
input_seq_... | input_seq = input()
input_seq_extended = str(input_seq) + str(input_seq[0])
total_output = 0
for i in range(0, len(input_seq)):
if input_seq_extended[i] == input_seq_extended[i + 1]:
print('Match! ' + str(i) + ' Total output: ' + str(total_output))
total_output += int(input_seq_extended[i])
print('O... |
class Player:
next_id = 1
def __init__(self, name, corp_id=None, runner_id=None):
self.id = Player.next_id
Player.next_id += 1
self.name = name
self.corp_id = corp_id
self.runner_id = runner_id
self.score = 0
self.sos = 0
self.esos = 0
se... | class Player:
next_id = 1
def __init__(self, name, corp_id=None, runner_id=None):
self.id = Player.next_id
Player.next_id += 1
self.name = name
self.corp_id = corp_id
self.runner_id = runner_id
self.score = 0
self.sos = 0
self.esos = 0
sel... |
word = input('Enter a word')
letter = input('Enter a letter')
def count(word, letter):
counter = 0
for character in word:
if character == letter:
counter = counter + 1
print(counter)
count(word, letter)
| word = input('Enter a word')
letter = input('Enter a letter')
def count(word, letter):
counter = 0
for character in word:
if character == letter:
counter = counter + 1
print(counter)
count(word, letter) |
'''
Implement a function which takes as input a string s
and returns true if s is a palindromic string.
'''
def is_palindrome(s): # Time: O(n)
# i moves forward, and j moves backward.
i, j = 0, len(s) - 1
while i < j:
# i and j both skip non-alphanumeric characters.
while not s[i].isalnum... | """
Implement a function which takes as input a string s
and returns true if s is a palindromic string.
"""
def is_palindrome(s):
(i, j) = (0, len(s) - 1)
while i < j:
while not s[i].isalnum() and i < j:
i += 1
while not s[j].isalnum() and i < j:
j -= 1
if s[i].l... |
def game(player1, player2):
history = []
while len(player1) != 0 and len(player2) != 0:
state = {'player1': player1.copy(), 'player2': player2.copy()}
if state in history:
return True, player1 + player2
history.append(state)
num1 = player1.pop(0)
num2 = player... | def game(player1, player2):
history = []
while len(player1) != 0 and len(player2) != 0:
state = {'player1': player1.copy(), 'player2': player2.copy()}
if state in history:
return (True, player1 + player2)
history.append(state)
num1 = player1.pop(0)
num2 = play... |
#!/usr/bin/env python3
######################################################################################
# #
# Program purpose: Creates a string made of the first 2 and the last 2 chars #
# from a gi... | def get_user_string(mess: str):
is_valid = False
data = ''
while is_valid is False:
try:
data = input(mess)
if len(data) == 0:
raise value_error('Please provide a string')
is_valid = True
except ValueError as ve:
print(f'[ERROR]... |
# Program to implement Affine Cipher for encryption and decryption
#returns gcd of two numbers
def gcd(num1, num2):
if num2 == 0:
return num1
return gcd(num2, num1 % num2)
#returns the inverse of a number if it exists, else '-1', under mod
def inverse(number, mod):
if gcd(number, mod) != 1:
... | def gcd(num1, num2):
if num2 == 0:
return num1
return gcd(num2, num1 % num2)
def inverse(number, mod):
if gcd(number, mod) != 1:
return None
t1 = 0
t2 = 1
while number != 0:
quotient = mod // number
remainder = mod % number
t = t1 - quotient * t2
... |
# coding=utf-8
# autogenerated using ms_props_generator.py
PROPS_ID_MAP = {
"0x0001": {"data_type": "0x0102", "name": "TemplateData"},
"0x0002": {"data_type": "0x000B", "name": "AlternateRecipientAllowed"},
"0x0004": {"data_type": "0x0102", "name": "ScriptData"},
"0x0005": {"data_type": "0x000B", "name"... | props_id_map = {'0x0001': {'data_type': '0x0102', 'name': 'TemplateData'}, '0x0002': {'data_type': '0x000B', 'name': 'AlternateRecipientAllowed'}, '0x0004': {'data_type': '0x0102', 'name': 'ScriptData'}, '0x0005': {'data_type': '0x000B', 'name': 'AutoForwarded'}, '0x000F': {'data_type': '0x0040', 'name': 'DeferredDeliv... |
try:
with open("input.txt", "r") as fileContent:
segments = [[segment.split(" -> ")]
for segment in fileContent.readlines()]
segments = [tuple([int(axis) for axis in coordinate.strip().split(",")])
for segment in segments for coordinates in segment for coordin... | try:
with open('input.txt', 'r') as file_content:
segments = [[segment.split(' -> ')] for segment in fileContent.readlines()]
segments = [tuple([int(axis) for axis in coordinate.strip().split(',')]) for segment in segments for coordinates in segment for coordinate in coordinates]
segments = ... |
def return_rate_limit(github):
rate_limit = github.get_rate_limit()
rate = rate_limit.rate
return rate.remaining
| def return_rate_limit(github):
rate_limit = github.get_rate_limit()
rate = rate_limit.rate
return rate.remaining |
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def __str__(self):
return str(self.key)
def print_path(path):
s = ""
for p in path:
s += str(p) + " "
print(f"{s}\n---")
def paths_with_sum(ro... | class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def __str__(self):
return str(self.key)
def print_path(path):
s = ''
for p in path:
s += str(p) + ' '
print(f'{s}\n---')
def paths_with_sum(root,... |
a = 35
b = 7
print("a % b =", a % b)
| a = 35
b = 7
print('a % b =', a % b) |
def valid_parentheses(s):
if not s:
return True
elif len(s) == 1:
return False
d = {"(": ")", "{": "}", "[": "]"}
stack = []
for bracket in s:
if bracket in d:
stack.append(bracket)
elif d[stack.pop()] != bracket:
return False
return len... | def valid_parentheses(s):
if not s:
return True
elif len(s) == 1:
return False
d = {'(': ')', '{': '}', '[': ']'}
stack = []
for bracket in s:
if bracket in d:
stack.append(bracket)
elif d[stack.pop()] != bracket:
return False
return len(st... |
#!/usr/bin/env python3
#
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
DOH_URI = '/.well-known/dns-query'
DOH_MEDIA_TYPE = 'application/dns-udpwireformat'
DOH_CONT... | doh_uri = '/.well-known/dns-query'
doh_media_type = 'application/dns-udpwireformat'
doh_content_type_param = 'ct'
doh_body_param = 'body'
doh_h2_npn_protocols = ['h2'] |
load("//ruby/private:constants.bzl", "RULES_RUBY_WORKSPACE_NAME")
load("//ruby/private:providers.bzl", "RubyRuntimeContext")
DEFAULT_BUNDLER_VERSION = "2.1.2"
BUNDLE_BIN_PATH = "bin"
BUNDLE_PATH = "lib"
SCRIPT_INSTALL_BUNDLER = "download_bundler.rb"
SCRIPT_ACTIVATE_GEMS = "activate_gems.rb"
SCRIPT_BUILD_FILE_GENERATO... | load('//ruby/private:constants.bzl', 'RULES_RUBY_WORKSPACE_NAME')
load('//ruby/private:providers.bzl', 'RubyRuntimeContext')
default_bundler_version = '2.1.2'
bundle_bin_path = 'bin'
bundle_path = 'lib'
script_install_bundler = 'download_bundler.rb'
script_activate_gems = 'activate_gems.rb'
script_build_file_generator ... |
# Designing window for login
def login():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Login")
login_screen.geometry("300x250")
Label(login_screen, text="Please enter details below to login").pack()
Label(login_screen, text="").pack()
global username_verify... | def login():
global login_screen
login_screen = toplevel(main_screen)
login_screen.title('Login')
login_screen.geometry('300x250')
label(login_screen, text='Please enter details below to login').pack()
label(login_screen, text='').pack()
global username_verify
global password_verify
... |
def solution(n, times):
leftLim = 1; rightLim = max(times) * n; answer = max(times) * n
while leftLim <= rightLim:
# print(leftLim, rightLim)
lim = (leftLim + rightLim)//2; check = sum([lim//time for time in times])
if check >= n:
answer = min(answer, lim)
rightLim... | def solution(n, times):
left_lim = 1
right_lim = max(times) * n
answer = max(times) * n
while leftLim <= rightLim:
lim = (leftLim + rightLim) // 2
check = sum([lim // time for time in times])
if check >= n:
answer = min(answer, lim)
right_lim = lim - 1
... |
def resta(num_1, num_2):
print('Restando:', num_1, '-', num_2)
resta_total = num_1 - num_2
print('El resultado es:',resta_total)
return resta_total
def app_resta():
inp_1 = None # Can be used 'None' instead of 0 too
inp_2 = None
while inp_1 == None:
try:
inp_1 = int(inp... | def resta(num_1, num_2):
print('Restando:', num_1, '-', num_2)
resta_total = num_1 - num_2
print('El resultado es:', resta_total)
return resta_total
def app_resta():
inp_1 = None
inp_2 = None
while inp_1 == None:
try:
inp_1 = int(input('Numero 1?: '))
except Valu... |
def cycleSort(array, *args):
for cycle_start in range(0, len(array) - 1):
item = array[cycle_start]
pos = cycle_start
for i in range(cycle_start + 1, len(array)):
if array[i] < item:
pos += 1
if pos == cycle_start:
continue
w... | def cycle_sort(array, *args):
for cycle_start in range(0, len(array) - 1):
item = array[cycle_start]
pos = cycle_start
for i in range(cycle_start + 1, len(array)):
if array[i] < item:
pos += 1
if pos == cycle_start:
continue
while array... |
aI, aO, aT, aJ, aL, aS, aZ = map(int, input().split())
ans = aO
p = [aI, aJ, aL]
for i in range(3):
if p[i] >= 2:
if p[i] % 2 == 0:
ans += (p[i] - 2) // 2 * 2
p[i] = 2
else:
ans += p[i] // 2 * 2
p[i] = 1
p.sort()
if sum(p) >= 5:
ans += sum(p) // 2 ... | (a_i, a_o, a_t, a_j, a_l, a_s, a_z) = map(int, input().split())
ans = aO
p = [aI, aJ, aL]
for i in range(3):
if p[i] >= 2:
if p[i] % 2 == 0:
ans += (p[i] - 2) // 2 * 2
p[i] = 2
else:
ans += p[i] // 2 * 2
p[i] = 1
p.sort()
if sum(p) >= 5:
ans += sum... |
class Solution:
def twoSum(self, nums , target) :
# a python dictionary(hash)
# key is number
# value is index of list: nums
number_dictionary = dict()
for index, number in enumerate(nums):
# put every number into dictionary... | class Solution:
def two_sum(self, nums, target):
number_dictionary = dict()
for (index, number) in enumerate(nums):
number_dictionary[number] = index
solution = list()
for i in range(len(nums)):
value = nums[i]
dual = target - value
in... |
n = int(input("Enter the number : "))
fact = 1
for i in range(1,n + 1):
fact = fact * i
print("Factorial of {} is {}".format(n,fact)) | n = int(input('Enter the number : '))
fact = 1
for i in range(1, n + 1):
fact = fact * i
print('Factorial of {} is {}'.format(n, fact)) |
pkgname = "lua5.4-zlib"
pkgver = "1.2"
pkgrel = 0
build_style = "makefile"
make_build_target = "linux"
hostmakedepends = ["pkgconf"]
makedepends = ["lua5.4-devel", "zlib-devel"]
pkgdesc = "Zlib streaming interface for Lua (5.4)"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "https://github.com/brimwo... | pkgname = 'lua5.4-zlib'
pkgver = '1.2'
pkgrel = 0
build_style = 'makefile'
make_build_target = 'linux'
hostmakedepends = ['pkgconf']
makedepends = ['lua5.4-devel', 'zlib-devel']
pkgdesc = 'Zlib streaming interface for Lua (5.4)'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT'
url = 'https://github.com/brimwo... |
# TempConv.py
# Celcius to Fahreinheit
def Fahreinheit(temp):
temp = float(temp)
temp = (temp*9/5)+32
return temp
# Fahreinheit to Celcius
def Celcius(temp):
temp = float(temp)
temp = (temp-32)*5/9
return temp
| def fahreinheit(temp):
temp = float(temp)
temp = temp * 9 / 5 + 32
return temp
def celcius(temp):
temp = float(temp)
temp = (temp - 32) * 5 / 9
return temp |
friends = ["Sam","Samantha","Saurab"]
start_with_s = [x for x in friends if x.startswith("S")]
#compare list friends and start_with_s, bot are same value but result should be false.
#Because two are different list
print(friends is start_with_s)
print("friends : ", id(friends)," start_with_s : ",id(start_with_s))
#if... | friends = ['Sam', 'Samantha', 'Saurab']
start_with_s = [x for x in friends if x.startswith('S')]
print(friends is start_with_s)
print('friends : ', id(friends), ' start_with_s : ', id(start_with_s))
print(friends[0] is start_with_s[0]) |
## Given a position, write a function to
## find if that position is within 5 points of a monster:
a_treasure_map = {
"45,46": "sea monster",
"55,38": "air monster",
"33,78": "lava monster",
"22,23": "shining castle",
"64,97": "shield of truth",
"97,3": "sword of power",
}
def near_monster(position, a_trea... | a_treasure_map = {'45,46': 'sea monster', '55,38': 'air monster', '33,78': 'lava monster', '22,23': 'shining castle', '64,97': 'shield of truth', '97,3': 'sword of power'}
def near_monster(position, a_treasure_map):
(x, y) = position.split(',')
player_x = int(x)
player_y = int(y)
for (key, value) in a_... |
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
... | def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
... |
def cuberoot2(x0):
x = x0
i = 0
while True:
nextIt = (1/3)*(2*x+2/(x**2))
if (abs(nextIt - x) <= 10**-7):
break
else:
i += 1
x = nextIt
print("The sequence starting at", x0, "converges to", x,"in", i, "iterations.")
cuberoot2(20)
def nesty(x):
f = (x - 1) ** 5
g = x ** 5 - 5 ... | def cuberoot2(x0):
x = x0
i = 0
while True:
next_it = 1 / 3 * (2 * x + 2 / x ** 2)
if abs(nextIt - x) <= 10 ** (-7):
break
else:
i += 1
x = nextIt
print('The sequence starting at', x0, 'converges to', x, 'in', i, 'iterations.')
cuberoot2(20)
d... |
# add a key to a dicitonary
# Sample dictionary: {0:10,1:20}
# Expected Result: {0:10,1:20,2:30}
a={0:10,1:20}
a[2]=30
print(a) | a = {0: 10, 1: 20}
a[2] = 30
print(a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.