content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
content = '''
<script>
function createimagemodal(path,cap) {
var html = '<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static">\
<span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span>\
... | content = '\n <script>\n function createimagemodal(path,cap) {\n var html = \'<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static"> <span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span> ... |
a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if (b - c) < a < (b + c) and (a - c) < b < (a + c) and (a - b) < c < (a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo') | a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if b - c < a < b + c and a - c < b < a + c and (a - b < c < a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo') |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RunNowPhysicalParameters(object):
"""Implementation of the 'RunNowPhysicalParameters' model.
Attributes:
metadata_file_path (string): Specifies metadata file path during
run-now requests for physical file based backups for some... | class Runnowphysicalparameters(object):
"""Implementation of the 'RunNowPhysicalParameters' model.
Attributes:
metadata_file_path (string): Specifies metadata file path during
run-now requests for physical file based backups for some specific
host entity. If specified, it will o... |
SECTION_OFFSET_START = 0x0
SECTION_ADDRESS_START = 0x48
SECTION_SIZE_START = 0x90
BSS_START = 0xD8
BSS_SIZE = 0xDC
TEXT_SECTION_COUNT = 7
DATA_SECTION_COUNT = 11
SECTION_COUNT = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
PATCH_SECTION = 3
ORIGINAL_DOL_END = 0x804DEC00
def word(data, offset):
retur... | section_offset_start = 0
section_address_start = 72
section_size_start = 144
bss_start = 216
bss_size = 220
text_section_count = 7
data_section_count = 11
section_count = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
patch_section = 3
original_dol_end = 2152590336
def word(data, offset):
return sum((data[offset + i] << ... |
class MetaSingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance ... | class Metasingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance ... |
"""Top-level package for baseline."""
__author__ = """Leon Kozlowski"""
__email__ = "leonkozlowski@gmail.com"
| """Top-level package for baseline."""
__author__ = 'Leon Kozlowski'
__email__ = 'leonkozlowski@gmail.com' |
#
# This file contains the Python code from Program 15.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_10.txt
#
class HeapSorter(... | class Heapsorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolate_down(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] > self._array[j]:
j = j + 1
if self._array[i] >= self.... |
#!/usr/bin/python3
# coding=utf-8
# Copyright 2019 getcarrier.io
#
# 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 req... | """
Constants
"""
jira_field_do_not_use_value = '!remove'
jira_field_use_default_value = '!default'
jira_severities = {'Trivial': 4, 'Minor': 3, 'Medium': 2, 'Major': 1, 'Critical': 0, 'Blocker': 0}
jira_alternatives = {'Trivial': ['Low', 'Minor'], 'Minor': ['Low', 'Medium'], 'Medium': ['Major'], 'Major': ['High', ... |
"""
Draw discontinu form
"""
| """
Draw discontinu form
""" |
'''
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
'''
def insertTopStreams(dbConnection, cursor, time, topStreams):
# m... | """
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
"""
def insert_top_streams(dbConnection, cursor, time, topStreams):
... |
class BinaryIndexedTree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
# add low bit
i += (i & -i)
def prefix_sum(self, i):
ret = 0
while i:
... | class Binaryindexedtree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
i += i & -i
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i... |
#stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner.
#In stack, a new element is added at one end and an element is removed from that end only.
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.app... | stack = []
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack) |
# ------------------------------
# 223. Rectangle Area
#
# Description:
# Find the total area covered by two rectilinear rectangles in a 2D plane.
# Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
#
# Example:
# Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9,... | class Solution(object):
def compute_area(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
left = max(A, E)
... |
"""
Goal:
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment
required by the credit card company each month.
For each month, calculate statements on the monthly payment and remaining balance.
At the end of 12 months, print out the remaining balance.
Be... | """
Goal:
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment
required by the credit card company each month.
For each month, calculate statements on the monthly payment and remaining balance.
At the end of 12 months, print out the remaining balance.
Be... |
student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not... | student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not i... |
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, "already_selfrole", _emote="WARN"))
if role.position >= ctx.guild.me.top_role.position:
... | async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, 'already_selfrole', _emote='WARN'))
if role.position >= ctx.guild.me.top_role.position:
re... |
code = """/* Disabled External File Drag */
window.addEventListener("dragover",function(e){
if (e.target.type != "file") {
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
window.addEventListener("dragenter",function(e){
if (e.target.type != "f... | code = '/* Disabled External File Drag */\nwindow.addEventListener("dragover",function(e){\n if (e.target.type != "file") {\n e.preventDefault();\n e.dataTransfer.effectAllowed = "none";\n e.dataTransfer.dropEffect = "none";\n }\n},false);\nwindow.addEventListener("dragenter",function(e){\n if (e.target.typ... |
'''
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
'''
print("Hello World!")
| """
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
"""
print('Hello World!') |
"""implements required text elements for the app"""
APP_NAME = "OSCAR"
WELCOME = "Welcome to " + APP_NAME
CREATE_PROJECT = {
'main': "Create ...",
'sub': "New " + APP_NAME + " project"
}
OPEN_PROJECT = {
'main': "Open ...",
'sub': "Existing " + APP_NAME + " project"
}
SECTIONS = {
'over': "Overvi... | """implements required text elements for the app"""
app_name = 'OSCAR'
welcome = 'Welcome to ' + APP_NAME
create_project = {'main': 'Create ...', 'sub': 'New ' + APP_NAME + ' project'}
open_project = {'main': 'Open ...', 'sub': 'Existing ' + APP_NAME + ' project'}
sections = {'over': 'Overview', 'energy': 'Energy', 'wa... |
"""
Useful functions
"""
def singleton(cls):
"""turn a class into a singleton class"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance | """
Useful functions
"""
def singleton(cls):
"""turn a class into a singleton class"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance |
hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate *no_weeks
print(monthly_pay)
| hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate * no_weeks
print(monthly_pay) |
def is_leap(year):
leap = False
# Write your logic here
# thought process
#if year%4==0:
# return True
#elif year%100==0:
# return False
#elif year%400==0:
# return True
# Optimized, Python 3
return ((year%4==0)and(year%100!=0)or(year%400==0))
| def is_leap(year):
leap = False
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 |
"""Constants for the Ziggo Mediabox Next integration."""
ZIGGO_API = "ziggo_api"
CONF_COUNTRY_CODE = "country_code"
RECORD = "record"
REWIND = "rewind"
FAST_FORWARD = "fast_forward" | """Constants for the Ziggo Mediabox Next integration."""
ziggo_api = 'ziggo_api'
conf_country_code = 'country_code'
record = 'record'
rewind = 'rewind'
fast_forward = 'fast_forward' |
'''
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output :... | """
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output :... |
def main():
for i in range(10):
print(f"The square of {i} is {square(i)}")
return
def square(n):
return n**2
if __name__ == '__main__':
main()
| def main():
for i in range(10):
print(f'The square of {i} is {square(i)}')
return
def square(n):
return n ** 2
if __name__ == '__main__':
main() |
'''
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case ... | """
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case ... |
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
sort_nums = nums.copy()
sort_nums.sort()
nums_order = [nums[i]==sort_nums[i] for i in range(n)]
if all(nums_order):
return... | class Solution:
def find_unsorted_subarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
sort_nums = nums.copy()
sort_nums.sort()
nums_order = [nums[i] == sort_nums[i] for i in range(n)]
if all(nums_order):
r... |
game = {
'leds': (
# GPIO05 - Pin 29
5,
# GPIO12 - Pin 32
12,
# GPIO17 - Pin 11
17,
# GPIO22 - Pin 15
22,
# GPIO25 - Pin 22
25
),
'switches': (
# GPIO06 - Pin 31
6,
# GPIO13 - Pin 33
13,
#... | game = {'leds': (5, 12, 17, 22, 25), 'switches': (6, 13, 19, 23, 24), 'countdown': 5, 'game_time': 60, 'score_increment': 1} |
"""See navigate.__doc__."""
room = [
"Crypt Entrance", "Math Room", "English Room", "NCEA Headquaters",
"Fancy Wall"
]
N = [2, 4, 4, 4]
S = [4, 4, 0, 4]
E = [3, 0, 4, 4]
W = [1, 4, 4, 0]
desc = [
"A dull enclosed space with three doors",
"A dull enclosed space with one door",
"A dull enclosed ... | """See navigate.__doc__."""
room = ['Crypt Entrance', 'Math Room', 'English Room', 'NCEA Headquaters', 'Fancy Wall']
n = [2, 4, 4, 4]
s = [4, 4, 0, 4]
e = [3, 0, 4, 4]
w = [1, 4, 4, 0]
desc = ['A dull enclosed space with three doors', 'A dull enclosed space with one door', 'A dull enclosed space with one door', 'A dull... |
# Databricks notebook source
# MAGIC %run ./_utility-methods $lesson="3.1"
# COMMAND ----------
DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f"{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv", f"{DA.paths.working_dir}/flights/departuredel... | DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f'{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv', f'{DA.paths.working_dir}/flights/departuredelays.csv', 'csv', 'flights')
DA.conclude_setup() |
class CNConfig:
interp_factor = 0.075
sigma = 0.2
lambda_= 0.01
output_sigma_factor=1./16
padding=1
cn_type = 'pyECO'
| class Cnconfig:
interp_factor = 0.075
sigma = 0.2
lambda_ = 0.01
output_sigma_factor = 1.0 / 16
padding = 1
cn_type = 'pyECO' |
def sumLoad(mirror):
"""Returns system sums of active PSLF load as [Pload, Qload]"""
sysPload = 0.0
sysQload = 0.0
# for each area
for area in mirror.Area:
# reset current sums
area.cv['P'] = 0.0
area.cv['Q'] = 0.0
# sum each active load P and Q to area agent
... | def sum_load(mirror):
"""Returns system sums of active PSLF load as [Pload, Qload]"""
sys_pload = 0.0
sys_qload = 0.0
for area in mirror.Area:
area.cv['P'] = 0.0
area.cv['Q'] = 0.0
for load in area.Load:
if load.cv['St'] == 1:
area.cv['P'] += load.cv['... |
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
sum_subarr = 0
l = len(arr)
odd_arr_len = 1 # to be increased by 2 after every iteration until equal to or less than l
while(odd_arr_len <= l):
... | class Solution(object):
def sum_odd_length_subarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
sum_subarr = 0
l = len(arr)
odd_arr_len = 1
while odd_arr_len <= l:
i = 0
while i + odd_arr_len < l + 1:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jared
"""
#DB Config File
host='localhost'
port=27017
dummy=True
saveFeatures = True
featureDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/featureDB2/'
crystalDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/crystalDB2/'
saveFeaturesFile='junk.c... | """
@author: Jared
"""
host = 'localhost'
port = 27017
dummy = True
save_features = True
feature_db_folder = '/Users/Jared/Dropbox/Master Thesis/Data/featureDB2/'
crystal_db_folder = '/Users/Jared/Dropbox/Master Thesis/Data/crystalDB2/'
save_features_file = 'junk.csv'
save_features_path = './data/features/' |
sortname = {
'bubblesort': f'Bubble Sort O(n\N{SUPERSCRIPT TWO})', 'insertionsort': f'Insertion Sort O(n\N{SUPERSCRIPT TWO})',
'selectionsort': f'Selection Sort O(n\N{SUPERSCRIPT TWO})', 'mergesort': 'Merge Sort O(n log n)',
'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'
} | sortname = {'bubblesort': f'Bubble Sort O(n²)', 'insertionsort': f'Insertion Sort O(n²)', 'selectionsort': f'Selection Sort O(n²)', 'mergesort': 'Merge Sort O(n log n)', 'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'} |
class Cons():
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
Nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return Cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt
| class Cons:
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt |
"""Default inputs used in the absence of user making a choice. \n
For information on the physical meaning of each of the constants see scientific background.
Variables:
number_of_models: number of models to compare (int) \n
model_1_inputs: input information for model 1 (dict) \n
model_2_inputs: input infor... | """Default inputs used in the absence of user making a choice.
For information on the physical meaning of each of the constants see scientific background.
Variables:
number_of_models: number of models to compare (int)
model_1_inputs: input information for model 1 (dict)
model_2_inputs: input informat... |
"""
Entradas
lote de naranjas compradas-->int-->X
Precio de naranjas por docena-->float-->Y
Dinero obtenido por la venta de las naranjas-->float-->K
Salidas
Porcentaje de ganancias-->float-->porcentaje
"""
#Entradas
X=int(input("Digite el lote de naranjas compradas: "))
Y=float(input("Digite el precio por docena de las... | """
Entradas
lote de naranjas compradas-->int-->X
Precio de naranjas por docena-->float-->Y
Dinero obtenido por la venta de las naranjas-->float-->K
Salidas
Porcentaje de ganancias-->float-->porcentaje
"""
x = int(input('Digite el lote de naranjas compradas: '))
y = float(input('Digite el precio por docena de las naran... |
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
# prints from third to end
print(names[2:4])
# prints third to fourth, does not include last one
names[0] = 'Jon'
# Find largest number in list
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_numb... | names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
print(names[2:4])
names[0] = 'Jon'
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f'The largest number is {max... |
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print("All numbers should be positive between 0 and 100 000!")
n = int(input("n: "))
a = int(input("a: "))
... | n = int(input('n: '))
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print('All numbers should be positive between 0 and 100 000!')
n = int(input('n: '))
a = int(input('a: '))
... |
def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker = ''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
re... | def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker=''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result =... |
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev... | def good_segement1(badList, l, r):
sorted_bad_list = sorted(badList)
current = sortedBadList[0]
max_val = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
max_index = i + 1
if i == 0 and l <= current <= r:
val = current - l
prev = l
... |
l, r = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * ... | (l, r) = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 *... |
def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i+1])
if a == b:
total += a
return total
# print(sum_doubles()) # 1341
def sum_halfway(numbers):
... | def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i + 1])
if a == b:
total += a
return total
def sum_halfway(numbers):
total = 0
delta = int... |
def reader():
...
| def reader():
... |
"""
Entradas
a-->int-->Cantidad de billetes de 50000
b-->int-->Cantidad de billetes de 20000
c-->int-->Cantidad de billetes de 10000
d-->int-->Cantidad de billetes de 5000
e-->int-->Cantidad de billetes de 2000
f-->int-->Cantidad de billetes de 1000
g-->int-->Cantidad de billetes de 500
h-->int-->Cantidad de billetes d... | """
Entradas
a-->int-->Cantidad de billetes de 50000
b-->int-->Cantidad de billetes de 20000
c-->int-->Cantidad de billetes de 10000
d-->int-->Cantidad de billetes de 5000
e-->int-->Cantidad de billetes de 2000
f-->int-->Cantidad de billetes de 1000
g-->int-->Cantidad de billetes de 500
h-->int-->Cantidad de billetes d... |
def C(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = "ATATATTAG" if not x else x
x += "$"
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def BWT(x, suffix):
x = "ATATATTAG" if not x else x
x += "$"
return ''.join([x[i - 2] for i in suffix])
def suffix_ar... | def c(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = 'ATATATTAG' if not x else x
x += '$'
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def bwt(x, suffix):
x = 'ATATATTAG' if not x else x
x += '$'
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x... |
CONTEXT = {'cell_line': 'Cell Line',
'cellline': 'Cell Line',
'cell_type': 'Cell Type',
'celltype': 'Cell Type',
'tissue': 'Tissue',
'interactome': 'Interactome'
}
HIDDEN_FOLDER = '.contnext'
ZENODO_URL = 'https://zenodo.org/record/5831786/files/data.zip?download=1' | context = {'cell_line': 'Cell Line', 'cellline': 'Cell Line', 'cell_type': 'Cell Type', 'celltype': 'Cell Type', 'tissue': 'Tissue', 'interactome': 'Interactome'}
hidden_folder = '.contnext'
zenodo_url = 'https://zenodo.org/record/5831786/files/data.zip?download=1' |
def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag
| def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag |
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = [
'standard', 'sampletable',
]
sysconfig = dict(
datasinks = ['caresssink'],
)
devices = dict(
chis = device('nicos.devices.generic.Axis',
description = 'Simulated CHIS axis',
motor = device('nicos.devi... | description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = ['standard', 'sampletable']
sysconfig = dict(datasinks=['caresssink'])
devices = dict(chis=device('nicos.devices.generic.Axis', description='Simulated CHIS axis', motor=device('nicos.devices.generic.VirtualMotor', fmtstr='%.2f', unit='deg... |
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s=0
for i in range(0,len(nums),2):
s+=nums[i]
return s
| class Solution:
def array_pair_sum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s = 0
for i in range(0, len(nums), 2):
s += nums[i]
return s |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AclModeEnum(object):
"""Implementation of the 'AclMode' enum.
ACL mode for this SMB share.
'kNative' specifies native ACL mode supports UNIX-like ACLs and Windows
ACLs. In native mode, because SMB natively supports both ACLs while NFS
o... | class Aclmodeenum(object):
"""Implementation of the 'AclMode' enum.
ACL mode for this SMB share.
'kNative' specifies native ACL mode supports UNIX-like ACLs and Windows
ACLs. In native mode, because SMB natively supports both ACLs while NFS
only supports UNIX ACLs, ACLs will not be shared between S... |
def Text(Text="", classname="", Type="h1", TextStyle="", Id="0"):
if TextStyle != "":
if classname != "":
return f"""<{Type} id={Id} class='{classname}' style='{TextStyle}'>{Text}</{Type}>"""
else:
return f"""<{Type} id={Id} style='{TextStyle}'>{Text}</{Type}>"""
else:
... | def text(Text='', classname='', Type='h1', TextStyle='', Id='0'):
if TextStyle != '':
if classname != '':
return f"<{Type} id={Id} class='{classname}' style='{TextStyle}'>{Text}</{Type}>"
else:
return f"<{Type} id={Id} style='{TextStyle}'>{Text}</{Type}>"
elif classname !... |
# Copyright (C) 2017 Ming-Shing Chen
def gf2_mul( a , b ):
return a&b
# gf4 := gf2[x]/x^2+x+1
# 4 and , 3 xor
def gf4_mul( a , b ):
a0 = a&1
a1 = (a>>1)&1
b0 = b&1
b1 = (b>>1)&1
ab0 = a0&b0
ab1 = (a1&b0)^(a0&b1)
ab2 = a1&b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= (ab1<<1)
return ab0
# gf16 := gf4[y]/y^... | def gf2_mul(a, b):
return a & b
def gf4_mul(a, b):
a0 = a & 1
a1 = a >> 1 & 1
b0 = b & 1
b1 = b >> 1 & 1
ab0 = a0 & b0
ab1 = a1 & b0 ^ a0 & b1
ab2 = a1 & b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= ab1 << 1
return ab0
def gf16_mul(a, b):
a0 = a & 3
a1 = a >> 2 & 3
b0 = ... |
#Dictionary and Class usage and examples
#cleaning up the input values
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs) ... | def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + '.' + secs
def get_coach_data(filename):
try:
with open(filename) as f:
... |
a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=", ")
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=", ")
a1 = a2
a2 = an
print("Even term sum =", sum_) | a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=', ')
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=', ')
a1 = a2
a2 = an
print('Even term sum =', sum_) |
# Difficulty Level: Easy
# Question: Filter the dictionary by removing all items with a value of greater
# than 1.
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# {'a': 1}
# Hint 1: Use dictionary comprehension.
# Hint 2: Inside the dictionary comprehension access dictionary items with
# d.items() if you are on... | d = {'a': 1, 'b': 2, 'c': 3}
print({i: j for (i, j) in d.items() if j <= 1})
d = {'a': 1, 'b': 2, 'c': 3}
d = dict(((key, value) for (key, value) in d.items() if value <= 1))
print(d) |
"""
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
... | """
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
... |
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n-1) * n
example = int(input())
print(factorial(example)) | def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n - 1) * n
example = int(input())
print(factorial(example)) |
'''
Created on Mar 9, 2019
@author: hzhang0418
'''
| """
Created on Mar 9, 2019
@author: hzhang0418
""" |
r=open('all.protein.faa','r')
w=open('context.processed.all.protein.faa','w')
start = True
mem = ""
for line in r:
if '>' in line and not start:
list_char = list(mem.replace('\n',''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp=""
... | r = open('all.protein.faa', 'r')
w = open('context.processed.all.protein.faa', 'w')
start = True
mem = ''
for line in r:
if '>' in line and (not start):
list_char = list(mem.replace('\n', ''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for ... |
number = int(input())
dots = ((3 * number) - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('... | number = int(input())
dots = (3 * number - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = (3 * number - (ex * 2 + 1)) // 2
for i in range(1, number // 2 + 2):
print('.' * dots ... |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(... | def main():
(a, b) = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))... |
'''
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to... | """
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy... |
"""
test
~~~~
Flask-Monitor is a simple extension to Flask allowing you to add
prometheus middleware to add basic but very useful metrics for
your Python Flask app.
:license: MIT, see LICENSE for more details.
""" | """
test
~~~~
Flask-Monitor is a simple extension to Flask allowing you to add
prometheus middleware to add basic but very useful metrics for
your Python Flask app.
:license: MIT, see LICENSE for more details.
""" |
"""
Implement an iterator over a binary search tree (BST). Your iterator will
be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
7
/ \
3 15
/ \
9 20
BSTIterator iterator ... | """
Implement an iterator over a binary search tree (BST). Your iterator will
be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
7
/ 3 15
/ 9 20
BSTIterator iterator = ne... |
JETBRAINS_IDES = {
'androidstudio': 'Android Studio',
'appcode': 'AppCode',
'datagrip': 'DataGrip',
'goland': 'GoLand',
'intellij': 'IntelliJ IDEA',
'pycharm': 'PyCharm',
'rubymine': 'RubyMine',
'webstorm': 'WebStorm'
}
JETBRAINS_IDE_NAMES = list(JETBRAINS_IDES.values())
| jetbrains_ides = {'androidstudio': 'Android Studio', 'appcode': 'AppCode', 'datagrip': 'DataGrip', 'goland': 'GoLand', 'intellij': 'IntelliJ IDEA', 'pycharm': 'PyCharm', 'rubymine': 'RubyMine', 'webstorm': 'WebStorm'}
jetbrains_ide_names = list(JETBRAINS_IDES.values()) |
mystr="Python is a multipurpose and simply learning langauge"
for i in mystr:
print(i,end=" ")
print()
print(mystr.find("simply"))
print(mystr[0:11]+ " programming")
| mystr = 'Python is a multipurpose and simply learning langauge'
for i in mystr:
print(i, end=' ')
print()
print(mystr.find('simply'))
print(mystr[0:11] + ' programming') |
T1, T2 = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i) | (t1, t2) = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i) |
#
# Copyright 2012 Sonya Huang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | use_table_margins = ['margins', 'rail_margin', 'truck_margin', 'water_margin', 'air_margin', 'pipe_margin', 'gaspipe_margin', 'wholesale_margin', 'retail_margin']
final_demand = 'f'
value_added = 'v'
intermediate_output = 'i'
fd_sectors = {1972: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1977: {'pce':... |
class FieldOffsetAttribute(Attribute,_Attribute):
"""
Indicates the physical position of fields within the unmanaged representation of a class or structure.
FieldOffsetAttribute(offset: int)
"""
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__ini... | class Fieldoffsetattribute(Attribute, _Attribute):
"""
Indicates the physical position of fields within the unmanaged representation of a class or structure.
FieldOffsetAttribute(offset: int)
"""
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex... |
config_object = {
"org_id": "",
"client_id": "",
"tech_id": "",
"pathToKey": "",
"secret": "",
"date_limit": 0,
"token": "",
"tokenEndpoint": "https://ims-na1.adobelogin.com/ims/exchange/jwt"
}
header = {"Accept": "application/json",
"Content-Type": "application/json",
... | config_object = {'org_id': '', 'client_id': '', 'tech_id': '', 'pathToKey': '', 'secret': '', 'date_limit': 0, 'token': '', 'tokenEndpoint': 'https://ims-na1.adobelogin.com/ims/exchange/jwt'}
header = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ', 'x-api-key': ''}
endpoin... |
INITIAL_HPS = {
'image_classifier': [{
'image_block_1/block_type': 'vanilla',
'image_block_1/normalize': True,
'image_block_1/augment': False,
'image_block_1_vanilla/kernel_size': 3,
'image_block_1_vanilla/num_blocks': 1,
'image_block_1_vanilla/separable': False,
... | initial_hps = {'image_classifier': [{'image_block_1/block_type': 'vanilla', 'image_block_1/normalize': True, 'image_block_1/augment': False, 'image_block_1_vanilla/kernel_size': 3, 'image_block_1_vanilla/num_blocks': 1, 'image_block_1_vanilla/separable': False, 'image_block_1_vanilla/dropout_rate': 0.25, 'image_block_1... |
file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close() | file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close() |
CAPACITY = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0]*CAPACITY
def insert(self, item):
# when heap is full
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
... | capacity = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0] * CAPACITY
def insert(self, item):
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
self.fix_heap(self.heap_size - 1)
def... |
src = Split('''
ota_service.c
ota_util.c
ota_update_manifest.c
ota_version.c
''')
component = aos_component('fota', src)
dependencis = Split('''
framework/fota/platform
framework/fota/download
utility/digest_algorithm
utility/cjson
''')
for i in dependencis:
component.add_comp_d... | src = split('\n ota_service.c\n ota_util.c\n ota_update_manifest.c\n ota_version.c\n')
component = aos_component('fota', src)
dependencis = split('\n framework/fota/platform\n framework/fota/download \n utility/digest_algorithm \n utility/cjson \n')
for i in dependencis:
component.add_comp_... |
# Works only with a good seed
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("chain-lightning", hero.findNearestEnemy())
| hero.cast('chain-lightning', hero.findNearestEnemy()) |
def main():
rst = bf_cal()
print(f"{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5")
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f"processing {x0} in (0..250)")
... | def main():
rst = bf_cal()
print(f'{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5')
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f'processing {x0} in (0..250)')
... |
sq_sum, sum = 0, 0
for i in range(1, 101):
sq_sum = sq_sum + (i * i)
sum = sum + i
print((sum * sum) - sq_sum)
| (sq_sum, sum) = (0, 0)
for i in range(1, 101):
sq_sum = sq_sum + i * i
sum = sum + i
print(sum * sum - sq_sum) |
class NotFoundException(Exception):
pass
class BadRequestException(Exception):
pass
class JobExistsException(Exception):
pass
class NoSuchImportableDataset(Exception):
pass
| class Notfoundexception(Exception):
pass
class Badrequestexception(Exception):
pass
class Jobexistsexception(Exception):
pass
class Nosuchimportabledataset(Exception):
pass |
#!/usr/bin/python3
"""
This module provides feedback control for motors
So far a PID controller......
"""
class PIDfeedback():
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_controller)
It ha... | """
This module provides feedback control for motors
So far a PID controller......
"""
class Pidfeedback:
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_controller)
It handles only the error ... |
n = int(input('Enter A Number: '))
def findFactors(num):
arr = []
for x in range(1, n + 1 ,1):
if num % x == 0:
arr.append(x)
return arr
if len(findFactors(n)) == 2: # Array will have 1 and the number itself
print(f"{n} Is Prime.")
else :
print(f"{n} Is Composite") | n = int(input('Enter A Number: '))
def find_factors(num):
arr = []
for x in range(1, n + 1, 1):
if num % x == 0:
arr.append(x)
return arr
if len(find_factors(n)) == 2:
print(f'{n} Is Prime.')
else:
print(f'{n} Is Composite') |
'''
Created on 1.12.2016
@author: Darren
'''
'''
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
'''
| """
Created on 1.12.2016
@author: Darren
"""
'\nGiven a binary search tree and a node in it, find the in-order successor of that node in the BST.\n\nNote: If the given node has no in-order successor in the tree, return null.\n' |
def printCommands():
print("Congratulations! You're running Ryan's Task list program.")
print("What would you like to do next?")
print("1. List all tasks.")
print("2. Add a task to the list.")
print("3. Delete a task.")
print("q. To quit the program")
printCommands()
aTaskListArray = ["bob", "... | def print_commands():
print("Congratulations! You're running Ryan's Task list program.")
print('What would you like to do next?')
print('1. List all tasks.')
print('2. Add a task to the list.')
print('3. Delete a task.')
print('q. To quit the program')
print_commands()
a_task_list_array = ['bob'... |
data = open("input.txt", "r")
data = data.read().split(",")
check = True
index = 0
while check is True:
section = data[index]
firstNum = int(data[int(data[index + 1])])
secondNum = int(data[int(data[index + 2])])
if section == "1":
total = firstNum + secondNum
if section == "2":
... | data = open('input.txt', 'r')
data = data.read().split(',')
check = True
index = 0
while check is True:
section = data[index]
first_num = int(data[int(data[index + 1])])
second_num = int(data[int(data[index + 2])])
if section == '1':
total = firstNum + secondNum
if section == '2':
to... |
mod = 10**9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n-1):
sumation -= a[i]
answer += a[i]*sumation
answer %= mod
print(answer)
| mod = 10 ** 9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n - 1):
sumation -= a[i]
answer += a[i] * sumation
answer %= mod
print(answer) |
{
"targets": [
{
"target_name": "sharedMemory",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/sharedMemory.cpp" ],
"libraries": [],
},
{
"target_name": "messaging",
"include_dirs": [
"<!(node -e \"require('na... | {'targets': [{'target_name': 'sharedMemory', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/sharedMemory.cpp'], 'libraries': []}, {'target_name': 'messaging', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/messaging.cpp'], 'libraries': []}]} |
def protected(func):
def wrapper(password):
if password=='platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == "__main__":
password=str(raw_input('Ingresa tu ... | def protected(func):
def wrapper(password):
if password == 'platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == '__main__':
password = str(raw_input('Ingresa ... |
s=input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon') | s = input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon') |
# Text Type: str
# Numeric Types: int, float, complex
# Sequence Types: list, tuple, range
# Mapping Type: dict
# Set Types: set, frozenset
# Boolean Type: bool
# Binary Types: bytes, bytearray, memoryview
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2... | x = float(1)
y = float(2.8)
z = float('3')
w = float('4.2')
print('--------------------------------------------------------')
num = 6
print(num)
print(str(num) + ' is my num')
print('--------------------------------------------------------') |
"""Extended Euclidean Algorithm
==============================
GCD of two numbers is the largest number that divides both of them.
A simple way to find GCD is to factorize both numbers and multiply
common factors.
GCD(a,b) = ax + by
If we can find the value of x and y then we can easily find the
... | """Extended Euclidean Algorithm
==============================
GCD of two numbers is the largest number that divides both of them.
A simple way to find GCD is to factorize both numbers and multiply
common factors.
GCD(a,b) = ax + by
If we can find the value of x and y then we can easily find the
... |
TRAIN_DATA_PATH = "data/processed/train_folds.csv"
TEST_DATA_PATH = "data/processed/test.csv"
MODEL_PATH = "models/"
NUM_FOLDS = 5
SEED = 23
VERBOSE = 0
FEATURE_COLS = [
"Pclass",
"Sex",
"Age",
"SibSp",
"Parch",
"Ticket",
"Fare",
"Cabin",
"Embarked",
"Title",
"Surname",
"... | train_data_path = 'data/processed/train_folds.csv'
test_data_path = 'data/processed/test.csv'
model_path = 'models/'
num_folds = 5
seed = 23
verbose = 0
feature_cols = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'Title', 'Surname', 'Family_Size']
target_col = 'Survived' |
"""
author: Alice Francener
problem: 1082 - Connected Components
description: https://www.urionlinejudge.com.br/judge/en/problems/view/1082
"""
'''Problema: quantos grafos conexos existem'''
class DisjointSets:
def __init__(self, n):
self.rank = [0] * n
self.parent = []
for i in rang... | """
author: Alice Francener
problem: 1082 - Connected Components
description: https://www.urionlinejudge.com.br/judge/en/problems/view/1082
"""
'Problema: quantos grafos conexos existem'
class Disjointsets:
def __init__(self, n):
self.rank = [0] * n
self.parent = []
for i in range(0,... |
def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(" ")
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.st... | def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(' ')
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.st... |
#(n-1)%M = x - 1
#(n-1)%N = y - 1
gcd = lambda a,b: gcd(b,a%b) if b else a
def finder(M,N,x,y):
for i in range(N//gcd(M,N)):
if (x-1+i*M)%N==y-1:
return x+i*M
return -1
for _ in range(int(input())):
M,N,x,y = map(int,input().split())
print(finder(M,N,x,y))
| gcd = lambda a, b: gcd(b, a % b) if b else a
def finder(M, N, x, y):
for i in range(N // gcd(M, N)):
if (x - 1 + i * M) % N == y - 1:
return x + i * M
return -1
for _ in range(int(input())):
(m, n, x, y) = map(int, input().split())
print(finder(M, N, x, y)) |
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(
type='PoseDetDetector',
pretrained='pretrained/dla34-ba72cf86.pth',
# pretrained='open-mmlab://msra/hrnetv2_w32',
backbone=dict(
type='DLA',
return_levels=True,
levels=[1, 1, 1, 2, 2, 1],
channel... | norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', backbone=dict(type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channels=[16, 32, 64, 128, 256, 512], ouput_indice=[3, 4, 5, 6]), neck=dict(type='FPN', in_channels=[64,... |
"""top-level pytest config
options can only be defined here,
not in binderhub/tests/conftest.py
"""
def pytest_addoption(parser):
parser.addoption(
"--helm",
action="store_true",
default=False,
help="Run tests marked with pytest.mark.helm",
)
| """top-level pytest config
options can only be defined here,
not in binderhub/tests/conftest.py
"""
def pytest_addoption(parser):
parser.addoption('--helm', action='store_true', default=False, help='Run tests marked with pytest.mark.helm') |
# Exceptions
class SequenceFieldException(Exception):
pass
| class Sequencefieldexception(Exception):
pass |
try:
x = int(input("X: "))
except ValueError:
print("That is not an int!")
exit()
try:
y = int(input("Y: "))
except ValueError:
print("That is not an int!")
exit()
print (x + y) | try:
x = int(input('X: '))
except ValueError:
print('That is not an int!')
exit()
try:
y = int(input('Y: '))
except ValueError:
print('That is not an int!')
exit()
print(x + y) |
# Design Linked List
class ListNode:
def __init__(self, x):
self.value = x
self.next = None
class LinkedList:
def __init__(self):
self.size = 0
self.head = ListNode(0) # Sentinel Node as psuedo-head
# add at head
def addAtHead(self, val):
self.addAtHead(0, val... | class Listnode:
def __init__(self, x):
self.value = x
self.next = None
class Linkedlist:
def __init__(self):
self.size = 0
self.head = list_node(0)
def add_at_head(self, val):
self.addAtHead(0, val)
def add_at_tail(self, val):
self.addAtTail(self.size... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.