content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def junta_listas(listas):
planarizada = []
for lista in listas:
for e in lista:
planarizada.append(e)
return planarizada
lista = [[1, 2, 3], [4, 5, 6], [7, 8], [9], [10]]
print(junta_listas(lista)) | def junta_listas(listas):
planarizada = []
for lista in listas:
for e in lista:
planarizada.append(e)
return planarizada
lista = [[1, 2, 3], [4, 5, 6], [7, 8], [9], [10]]
print(junta_listas(lista)) |
S = input()
n = S.count("N")
s = S.count("S")
e = S.count("E")
w = S.count("W")
home = False
if n and s:
if e and w:
print("Yes")
elif not e and not w:
print("Yes")
else:
print("No")
elif not n and not s:
if e and w:
print("Yes")
elif not e and not w:
print... | s = input()
n = S.count('N')
s = S.count('S')
e = S.count('E')
w = S.count('W')
home = False
if n and s:
if e and w:
print('Yes')
elif not e and (not w):
print('Yes')
else:
print('No')
elif not n and (not s):
if e and w:
print('Yes')
elif not e and (not w):
pr... |
# lec5prob9-semordnilap.py
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
# Lecture 5, problem 9
# A semordnilap is a word or a phrase that spells a different word when backwards
# ("semordnilap" is a semordnilap of "palindromes"). Here are some examples:
#
# nametag / gateman
# dog ... | def semordnilap(str1, str2):
"""
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
False otherwise.
"""
if not (len(str1) or len(str2)):
return True
if not (len(str1) and len(str2)):
return False
if str1[0] != str2[-1]:
re... |
""" Module docstring """
def _impl(_ctx):
print("printing at debug level")
my_rule = rule(
attrs = {
},
implementation = _impl,
)
| """ Module docstring """
def _impl(_ctx):
print('printing at debug level')
my_rule = rule(attrs={}, implementation=_impl) |
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if (n < 0):
x = 1 / x
n = -n
if n == 0:
return 1
half = self.myPow(x, n // 2)
if(n % 2 == 0):
retu... | class Solution(object):
def my_pow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
x = 1 / x
n = -n
if n == 0:
return 1
half = self.myPow(x, n // 2)
if n % 2 == 0:
return... |
class Auth:
"""
Base class for authentication schemes.
"""
def auth(self):
...
def synchronous_auth(self):
...
async def asynchronous_auth(self):
...
| class Auth:
"""
Base class for authentication schemes.
"""
def auth(self):
...
def synchronous_auth(self):
...
async def asynchronous_auth(self):
... |
__title__ = 'fobi.contrib.plugins.form_elements.fields.' \
'hidden_model_object.default'
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = 'Copyright (c) 2014-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('IGNORED_MODELS',)
IGNORED_MODELS = []
| __title__ = 'fobi.contrib.plugins.form_elements.fields.hidden_model_object.default'
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = 'Copyright (c) 2014-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('IGNORED_MODELS',)
ignored_models = [] |
# Description: Sequence Built-in Methods
# Sequence Methods
word = 'Hello'
print(len(word[1:3])) # 2
print(ord('A')) # 65
print(chr(65)) # A
print(str(65)) # 65
# Looping Sequence
# 1. The position index and corresponding value can be retrieved at the same time using the e... | word = 'Hello'
print(len(word[1:3]))
print(ord('A'))
print(chr(65))
print(str(65))
for (i, v) in enumerate(['tic', 'tac', 'toe']):
print(i, v)
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for (q, a) in zip(questions, answers):
print('What is your {0}? It is {... |
__author__ = "Inada Naoki <songofacandy@gmail.com>"
version_info = (1,4,2,'final',0)
__version__ = "1.4.2"
| __author__ = 'Inada Naoki <songofacandy@gmail.com>'
version_info = (1, 4, 2, 'final', 0)
__version__ = '1.4.2' |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
"""
A min priority queue implementation using a binary heap.
@author Swapnil Trambake, trambake.swapnil@gmail.com
"""
class BinaryHeap():
"""
Class implements binary heap using array
"""
def __init__(self) -> None:
super().__init__()
self.__heap = []
def print(self):
"""
... | """
A min priority queue implementation using a binary heap.
@author Swapnil Trambake, trambake.swapnil@gmail.com
"""
class Binaryheap:
"""
Class implements binary heap using array
"""
def __init__(self) -> None:
super().__init__()
self.__heap = []
def print(self):
"""
... |
# tests.utils_tests
# Tests for the Baleen utilities package.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sun Feb 21 15:31:55 2016 -0500
#
# Copyright (C) 2016 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Tests for the Baleen utiliti... | """
Tests for the Baleen utilities package.
""" |
budget = float(input())
statists = int(input())
one_costume_price = float(input())
decor_price = 0.1 * budget
costumes_price = statists * one_costume_price
if statists >= 150:
costumes_price -= 0.1 * costumes_price
total_price = decor_price + costumes_price
money_left = budget - total_price
money_needed = total_... | budget = float(input())
statists = int(input())
one_costume_price = float(input())
decor_price = 0.1 * budget
costumes_price = statists * one_costume_price
if statists >= 150:
costumes_price -= 0.1 * costumes_price
total_price = decor_price + costumes_price
money_left = budget - total_price
money_needed = total_pri... |
'''
Created on Jan 19, 2016
@author: elefebvre
'''
| """
Created on Jan 19, 2016
@author: elefebvre
""" |
a=int(input())
b=int(input())
if a>b:a,b=b,a
for i in range(a+1,b):
if i%5==2 or i%5==3:print(i)
| a = int(input())
b = int(input())
if a > b:
(a, b) = (b, a)
for i in range(a + 1, b):
if i % 5 == 2 or i % 5 == 3:
print(i) |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums, temp):
if not nums:
res.append(temp)
return
for i in range(len(nums)):
backtrack(nums[:i]+nums[i+1:], temp+[nums[i]])
ba... | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums, temp):
if not nums:
res.append(temp)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i + 1:], temp + [nums[i]])
... |
class LibTiffPackage (Package):
def __init__(self):
Package.__init__(self, 'tiff', '4.0.9',
configure_flags=[
],
sources=[
'http://download.osgeo.org/libtiff/tiff-%{version}.tar.gz',
... | class Libtiffpackage(Package):
def __init__(self):
Package.__init__(self, 'tiff', '4.0.9', configure_flags=[], sources=['http://download.osgeo.org/libtiff/tiff-%{version}.tar.gz'])
self.needs_lipo = True
lib_tiff_package() |
''' Encapsulation : Part 1
Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so that it prevents accidental data modification.
Encapsulation basically allows the internal representation of an object to be hidden from the v... | """ Encapsulation : Part 1
Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so that it prevents accidental data modification.
Encapsulation basically allows the internal representation of an object to be hidden from the v... |
#!/usr/bin/env python
"""job.py: File containing Job class to be used as the executors for the pipeline."""
__author__ = "Zeyad Osama"
class Job:
"""
Job class to be used as the executors for the pipeline.
"""
def __init__(self) -> None:
super().__init__()
def initialize(self):
... | """job.py: File containing Job class to be used as the executors for the pipeline."""
__author__ = 'Zeyad Osama'
class Job:
"""
Job class to be used as the executors for the pipeline.
"""
def __init__(self) -> None:
super().__init__()
def initialize(self):
pass
def terminate(... |
class UndefinedMockBehaviorError(Exception):
pass
class MethodWasNotCalledError(Exception):
pass
| class Undefinedmockbehaviorerror(Exception):
pass
class Methodwasnotcallederror(Exception):
pass |
class Solution:
def decodeString(self, s: str) -> str:
St = []
num = 0
curr = ''
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c == '[':
St.append([num, curr])
num = 0
curr = ''
... | class Solution:
def decode_string(self, s: str) -> str:
st = []
num = 0
curr = ''
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == '[':
St.append([num, curr])
num = 0
curr = ''
... |
# Belajar default argument value
#defaul name berfungsi memberikan pengisian default pada parameter
#sehingga pengisian parameter bersifat opsional
def say_hello(nama="aris"): #menggunakan sama dengan lalu ketik default value nya
print(f"Hello {nama}!")
say_hello("karachi")
say_hello() #akan error jika ti... | def say_hello(nama='aris'):
print(f'Hello {nama}!')
say_hello('karachi')
say_hello()
def says_hello(nama_pertama='uchiha', nama_kedua=''):
print(f'Hello {nama_pertama}-{nama_kedua}!')
says_hello('muhammad', 'aris')
says_hello(nama_kedua='shishui')
says_hello(nama_kedua='uchiha', nama_pertama='madara')
says_hel... |
# getattr(object, name[, default])
class C:
def A(self): pass
print(getattr(C, 'A'))
| class C:
def a(self):
pass
print(getattr(C, 'A')) |
arr=input("Enter array elements").split(' ')
arr=[int(x) for x in arr]
for i in range(len(arr)):
for j in range(len(arr)-1-i):
if(arr[j]>arr[j+1]):
arr[j],arr[j+1]=arr[j+1],arr[j]
print("Sorted array is:",arr)
"""
Problem Statement: Sort array using bubble sort technique
Sample Input/Output:... | arr = input('Enter array elements').split(' ')
arr = [int(x) for x in arr]
for i in range(len(arr)):
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j])
print('Sorted array is:', arr)
'\nProblem Statement: Sort array using bubble sort technique\n... |
#
# Copyright (C) 2017 The Android Open Source Project
#
# 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 la... | model = model()
i1 = input('op1', 'TENSOR_FLOAT32', '{1, 2, 3, 2}')
i2 = input('op2', 'TENSOR_FLOAT32', '{1, 2, 3, 2}')
i3 = input('op3', 'TENSOR_FLOAT32', '{1, 2, 3, 2}')
axis0 = int32_scalar('axis0', 3)
r = output('result', 'TENSOR_FLOAT32', '{1, 2, 3, 6}')
model = model.Operation('CONCATENATION', i1, i2, i3, axis0).... |
class PseudoData(dict):
def __init__(self, name_func_dict, sweep):
super(PseudoData, self).__init__()
self.name_func_dict = name_func_dict
self.sweep = sweep
def __getitem__(self, key):
if key in self.keys():
return dict.__getitem__(self, key)
elif key in sel... | class Pseudodata(dict):
def __init__(self, name_func_dict, sweep):
super(PseudoData, self).__init__()
self.name_func_dict = name_func_dict
self.sweep = sweep
def __getitem__(self, key):
if key in self.keys():
return dict.__getitem__(self, key)
elif key in se... |
# LAB EXERCISE 05
print('Lab Exercise 05 \n')
# SETUP
pop_tv_shows = [
{"Title": "WandaVision", "Creator": ["Jac Schaeffer"], "Rating": 8.2, "Genre": "Action"},
{"Title": "Attack on Titan", "Creator": ["Hajime Isayama"], "Rating": 8.9, "Genre": "Animation"},
{"Title": "Bridgerton", "Creator": ["Chris Van D... | print('Lab Exercise 05 \n')
pop_tv_shows = [{'Title': 'WandaVision', 'Creator': ['Jac Schaeffer'], 'Rating': 8.2, 'Genre': 'Action'}, {'Title': 'Attack on Titan', 'Creator': ['Hajime Isayama'], 'Rating': 8.9, 'Genre': 'Animation'}, {'Title': 'Bridgerton', 'Creator': ['Chris Van Dusen'], 'Rating': 7.3, 'Genre': 'Drama'}... |
__author__ = 'chira'
# "return" used for mathematical function composition
def f(x): # x is an INPUT
y = 2*x + 3
return y # y is an OUTPUT
def g(x): # x is an INPUT
y = pow(x,2)
return y # y is an OUTPUT
def h(x,y): # x and y are INPUTS
z = pow(x,2) + 3*y;
return z # z i... | __author__ = 'chira'
def f(x):
y = 2 * x + 3
return y
def g(x):
y = pow(x, 2)
return y
def h(x, y):
z = pow(x, 2) + 3 * y
return z
output = 0
output = f(1)
print('f(%d) = %d' % (1, output))
output = g(5)
print('g(%d) = %d' % (5, output))
output = f(25)
print('f(%d) = %d' % (25, output))
outpu... |
def balancedSums(arr):
if n == 1:
return 'YES'
sumL = 0
sumR = 0
i =0
j = n-1
while i <= j:
if i ==j and sumL == sumR:
return 'YES'
elif sumL > sumR:
sumR+=arr[j]
j =j-1
else:
sumL+=arr[i]
i =i +1
re... | def balanced_sums(arr):
if n == 1:
return 'YES'
sum_l = 0
sum_r = 0
i = 0
j = n - 1
while i <= j:
if i == j and sumL == sumR:
return 'YES'
elif sumL > sumR:
sum_r += arr[j]
j = j - 1
else:
sum_l += arr[i]
... |
def perfect_square(x):
if (x == 0 or x == 1):
return x
i = 1
result = 1
while (result <= x):
i += 1
result = i * i
return i - 1
x = int(input('Enter no.'))
print(perfect_square(x))
| def perfect_square(x):
if x == 0 or x == 1:
return x
i = 1
result = 1
while result <= x:
i += 1
result = i * i
return i - 1
x = int(input('Enter no.'))
print(perfect_square(x)) |
# Default delimiters
INPUT1 = '''
pid 2
uptime 675
version 1.2.5 END
pid 1
uptime 2
version 3
END
'''
OUTPUT1 = '''{"pid": "2", "uptime": "675", "version": "1.2.5"}
{"pid": "1", "uptime": "2", "version": "3"}
'''
# --field-delim '=', --record-delim '%\n'
INPUT2 = '''
a=1
b=2
c=3
%
d=4
e=5
f=6
%
'''
OUTPUT2 = '''{"a"... | input1 = '\npid 2\nuptime 675\nversion 1.2.5 END\npid 1\nuptime 2\nversion 3\nEND\n'
output1 = '{"pid": "2", "uptime": "675", "version": "1.2.5"}\n{"pid": "1", "uptime": "2", "version": "3"}\n'
input2 = '\na=1\nb=2\nc=3\n%\nd=4\ne=5\nf=6\n%\n'
output2 = '{"a": "1", "b": "2", "c": "3"}\n{"d": "4", "e": "5", "f": "6"}\n'... |
def capitalize(string):
sttings_upper = string.title()
for word in string.split():
words = word[:-1] + word[0-1].upper() + " "
return sttings_upper[:-1]
print(capitalize("GoLand is a new commercial IDE by JetBrains aimed at providing an ergonomic environment "
"for Go developmen... | def capitalize(string):
sttings_upper = string.title()
for word in string.split():
words = word[:-1] + word[0 - 1].upper() + ' '
return sttings_upper[:-1]
print(capitalize('GoLand is a new commercial IDE by JetBrains aimed at providing an ergonomic environment for Go development. The new IDE extends... |
"""Meta information for csv2sql."""
__version__ = '0.4.1'
__author__ = 'Yu Mochizuki'
__author_email__ = 'ymoch.dev@gmail.com'
| """Meta information for csv2sql."""
__version__ = '0.4.1'
__author__ = 'Yu Mochizuki'
__author_email__ = 'ymoch.dev@gmail.com' |
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
l1 = [int(s) for s in version1.split(".")]
l2 = [int(s) for s in version2.split(".")]
len1, len2 = len(l1), len(l2)
if len1 > len2:
l2 += [0] * (len1 - len2)
elif len1 < len2:
... | class Solution:
def compare_version(self, version1: str, version2: str) -> int:
l1 = [int(s) for s in version1.split('.')]
l2 = [int(s) for s in version2.split('.')]
(len1, len2) = (len(l1), len(l2))
if len1 > len2:
l2 += [0] * (len1 - len2)
elif len1 < len2:
... |
"""
File: anagram.py
Name: Jason Huang
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for eac... | """
File: anagram.py
Name: Jason Huang
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for eac... |
############# constants
TITLE = "Cheese Maze"
DEVELOPER = "Jack Gartner"
HISTORY = "A mouse wants eat his cheese, Make it to the Hashtag to win, watch out for plus signs, $ is a teleport, P is a power up, Obtain the Key (K) in order to unlock the door (D)"
INSTRUCTIONS = "left arrow key\t\t\tto move left\nright arrow k... | title = 'Cheese Maze'
developer = 'Jack Gartner'
history = 'A mouse wants eat his cheese, Make it to the Hashtag to win, watch out for plus signs, $ is a teleport, P is a power up, Obtain the Key (K) in order to unlock the door (D)'
instructions = 'left arrow key\t\t\tto move left\nright arrow key\t\t\tto move right\nu... |
score = float(input("Enter Score: "))
if score < 1 and score > 0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print('Value of score is out of range.')
l... | score = float(input('Enter Score: '))
if score < 1 and score > 0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print('Value of score is out of range.')
largest ... |
class BaseRequestError(Exception):
def __init__(self, *args, **kwargs):
self.errors = []
self.code = 400
if 'code' in kwargs:
self.code = kwargs['code']
def add_error(self, err):
self.info.append(err)
def set_errors(self, errors):
self.errors = errors
... | class Baserequesterror(Exception):
def __init__(self, *args, **kwargs):
self.errors = []
self.code = 400
if 'code' in kwargs:
self.code = kwargs['code']
def add_error(self, err):
self.info.append(err)
def set_errors(self, errors):
self.errors = errors
... |
'''
Created on May 19, 2019
@author: ballance
'''
# TODO: implement simulation-access methods
# - yield
# - get sim time
# - ...
#
# The launcher will ultimately implement these methods
#
| """
Created on May 19, 2019
@author: ballance
""" |
"""Provide some variants of assert."""
def _custom_assert(condition: bool, on_error_msg: str = "") -> None:
"""Provide a custom assert which is kept even if the optimized python mode is used.
See https://docs.python.org/3/reference/simple_stmts.html#assert for the documentation
on the classical assert fu... | """Provide some variants of assert."""
def _custom_assert(condition: bool, on_error_msg: str='') -> None:
"""Provide a custom assert which is kept even if the optimized python mode is used.
See https://docs.python.org/3/reference/simple_stmts.html#assert for the documentation
on the classical assert funct... |
def find_even_index(arr):
for index, int in enumerate(arr):
left = sum_range(arr, 0, index)
right = sum_range(arr, index, len(arr))
if left == right:
return index
return -1
def sum_range(arr, a, b):
return sum(arr[a:b + 1])
| def find_even_index(arr):
for (index, int) in enumerate(arr):
left = sum_range(arr, 0, index)
right = sum_range(arr, index, len(arr))
if left == right:
return index
return -1
def sum_range(arr, a, b):
return sum(arr[a:b + 1]) |
# DO NOT EDIT: this file is auto-generated
def _jvm_deps_impl(ctx):
content = """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def load_jvm_deps():
http_file(name="com.google.code.findbugs_jsr305_1.3.9", urls=["https://repo1.maven.org/maven2/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3... | def _jvm_deps_impl(ctx):
content = '\nload("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")\n\ndef load_jvm_deps():\n http_file(name="com.google.code.findbugs_jsr305_1.3.9", urls=["https://repo1.maven.org/maven2/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar"], sha256="905721a0eea90a81534abb7... |
""" CHALLENGE PROBLEM!! NOT FOR THE FAINT OF HEART!
The Fibonacci numbers, discovered by Leonardo di Fibonacci,
is a sequence of numbers that often shows up in mathematics and,
interestingly, nature. The sequence goes as such:
1,1,2,3,5,8,13,21,34,55,...
where the sequence starts with 1 and 1, and then each number i... | """ CHALLENGE PROBLEM!! NOT FOR THE FAINT OF HEART!
The Fibonacci numbers, discovered by Leonardo di Fibonacci,
is a sequence of numbers that often shows up in mathematics and,
interestingly, nature. The sequence goes as such:
1,1,2,3,5,8,13,21,34,55,...
where the sequence starts with 1 and 1, and then each number i... |
INSTALLED_APPS = (
"testapp",
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = "django_tests_secret_key"
| installed_apps = ('testapp',)
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
secret_key = 'django_tests_secret_key' |
# Databricks notebook source
# MAGIC %md # Run transform
# MAGIC this will load the schema, the raw txt tables, then transform the dataframes to structured dataframes.
# COMMAND ----------
# MAGIC %run ./transform
# COMMAND ----------
# MAGIC %md # Store
# MAGIC write the transformed dataframes to our base-path
# ... | for table in df_openalex_c:
target = f'{base_path}parquet/{table}'
if table in partition_sizes:
partitions = partition_sizes[table]
else:
partitions = partition_sizes['default']
if file_exists(target):
print(f'{target} already exists, skip')
else:
print(f'writing {tar... |
# python3
def build_heap(data):
"""Build a heap from ``data`` inplace.
Returns a sequence of swaps performed by the algorithm.
"""
# The following naive implementation just sorts the given sequence
# using selection sort algorithm and saves the resulting sequence
# of swaps. This turns the gi... | def build_heap(data):
"""Build a heap from ``data`` inplace.
Returns a sequence of swaps performed by the algorithm.
"""
swaps = []
n = len(data)
for i in range((n - 2) // 2, -1, -1):
j = i
while j < n:
m = j
l = 2 * m + 1
r = l + 1
... |
# Ex4.
#
# Create a program that is going to take a whole number as an input, and will calculate the factorial of the number.
#
# Factorial example: 5! = 5 * 4 * 3 * 2 * 1 = 120
factorial = 1
number = int(input('Enter a number: '))
for i in range(1, number+1):
factorial *= i
print(f'Factorial of {number} is {facto... | factorial = 1
number = int(input('Enter a number: '))
for i in range(1, number + 1):
factorial *= i
print(f'Factorial of {number} is {factorial}') |
"""
Parameters and syntactic sugar.
"""
def dec(func):
def wrapper(*args, **kwargs):
print('Top decoration')
rv = func(*args, **kwargs)
print('Bottom decoration')
return rv
return wrapper
@dec
def sum_it(a, b):
return(a + b)
x = sum_it(10, 5)
print(x)
| """
Parameters and syntactic sugar.
"""
def dec(func):
def wrapper(*args, **kwargs):
print('Top decoration')
rv = func(*args, **kwargs)
print('Bottom decoration')
return rv
return wrapper
@dec
def sum_it(a, b):
return a + b
x = sum_it(10, 5)
print(x) |
def read_lines_of_file(filename):
with open(filename) as f:
content = f.readlines()
return content,len(content)
alltext,alltextlen = read_lines_of_file('read.txt')
for line in alltext:
print(line.rstrip())
print("Number of lines read from file --> %d" %(alltextlen)) | def read_lines_of_file(filename):
with open(filename) as f:
content = f.readlines()
return (content, len(content))
(alltext, alltextlen) = read_lines_of_file('read.txt')
for line in alltext:
print(line.rstrip())
print('Number of lines read from file --> %d' % alltextlen) |
class Authenticator():
def validate(self, username, password):
raise NotImplementedError() # pragma: no cover
def verify(self, username):
raise NotImplementedError() # pragma: no cover
def get_password(self, username):
raise NotImplementedError() # pragma: no cover
| class Authenticator:
def validate(self, username, password):
raise not_implemented_error()
def verify(self, username):
raise not_implemented_error()
def get_password(self, username):
raise not_implemented_error() |
""" some types and constants
"""
# pylint: disable=too-few-public-methods
NS = "starters"
class Status:
""" pseudo-enum for managing statuses
"""
# the starter isn't done yet, and more data is required
CONTINUING = "continuing"
# the starter is done, and should not continue
DONE = "done"
... | """ some types and constants
"""
ns = 'starters'
class Status:
""" pseudo-enum for managing statuses
"""
continuing = 'continuing'
done = 'done'
error = 'error' |
#!/usr/local/bin/python3
class Generator():
def __init__(self, init, factor, modulo, multiple):
self.value = init
self.factor = factor
self.modulo = modulo
self.multiple = multiple
def getNext(self):
self.value = (self.value * self.factor) % self.modulo
while (s... | class Generator:
def __init__(self, init, factor, modulo, multiple):
self.value = init
self.factor = factor
self.modulo = modulo
self.multiple = multiple
def get_next(self):
self.value = self.value * self.factor % self.modulo
while self.value % self.multiple != ... |
price = 1000000
good_credit = True
high_income = True
if good_credit and high_income:
down_payment = 1.0 * price
print(f"eligible for loan")
else:
down_payment = 2.0 * price
print(f"ineligible for loan")
print(f"down payment is {down_payment}")
| price = 1000000
good_credit = True
high_income = True
if good_credit and high_income:
down_payment = 1.0 * price
print(f'eligible for loan')
else:
down_payment = 2.0 * price
print(f'ineligible for loan')
print(f'down payment is {down_payment}') |
# Constants shared between C++ code and python
# TODO: Share properly via a configuration file
# ControllerWithSimpleHistory::EvaluationPeriod
EVALUATION_PERIOD_SEQUENCES = 64
# kWorkWindowSize in SysConsts.hpp
STATE_TRANSFER_WINDOW = 300
| evaluation_period_sequences = 64
state_transfer_window = 300 |
# Python program to print
# ASCII Value of Character
# In c we can assign different
# characters of which we want ASCII value
c = 'g'
# print the ASCII value of assigned character in c
print("The ASCII value of '" + c + "' is", ord(c))
| c = 'g'
print("The ASCII value of '" + c + "' is", ord(c)) |
#!/usr/bin/python3
"""
Contains empty class BaseGeometry
with public instance method area
"""
class BaseGeometry:
"""
Methods:
area(self)
"""
def area(self):
"""not implemented"""
raise Exception("area() is not implemented")
| """
Contains empty class BaseGeometry
with public instance method area
"""
class Basegeometry:
"""
Methods:
area(self)
"""
def area(self):
"""not implemented"""
raise exception('area() is not implemented') |
"""
Enable `django-admin-tools`_ to enhance the administration interface. This enables three widgets to customize certain elements. `filebrowser`_ is used, so if your project has not enabled it, you need to remove the occurrences of these widgets.
.. warning::
This mod cannot live with `admin_style`_, you have... | """
Enable `django-admin-tools`_ to enhance the administration interface. This enables three widgets to customize certain elements. `filebrowser`_ is used, so if your project has not enabled it, you need to remove the occurrences of these widgets.
.. warning::
This mod cannot live with `admin_style`_, you have... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 21:42:34 2020
@author: lukepinkel
"""
LBFGSB_options = dict(disp=10, maxfun=5000, maxiter=5000, gtol=1e-8)
SLSQP_options = dict(disp=True, maxiter=1000)
TrustConstr_options = dict(verbose=3, gtol=1e-5)
TrustNewton_options = dict(gtol=1e-5)
Trust... | """
Created on Tue May 19 21:42:34 2020
@author: lukepinkel
"""
lbfgsb_options = dict(disp=10, maxfun=5000, maxiter=5000, gtol=1e-08)
slsqp_options = dict(disp=True, maxiter=1000)
trust_constr_options = dict(verbose=3, gtol=1e-05)
trust_newton_options = dict(gtol=1e-05)
trust_constr2_options = dict(verbose=0, gtol=1e-... |
def find(tree, key, value):
items = tree.get("children", []) if isinstance(tree, dict) else tree
for item in items:
if item[key] == value:
yield item
else:
yield from find(item, key, value)
def find_path(tree, key, value, path=()):
items = tree.get("children", []) i... | def find(tree, key, value):
items = tree.get('children', []) if isinstance(tree, dict) else tree
for item in items:
if item[key] == value:
yield item
else:
yield from find(item, key, value)
def find_path(tree, key, value, path=()):
items = tree.get('children', []) if... |
# compat2.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,R1717,W0122,W0613
###
# Functions
###
def _readlines(fname): # pragma: no cover
"""Read all lines from file."""
with open(fname, "r") as fobj:
return fobj.readlines()
# Largely from From h... | def _readlines(fname):
"""Read all lines from file."""
with open(fname, 'r') as fobj:
return fobj.readlines()
def _unicode_to_ascii(obj):
"""Convert to ASCII."""
if isinstance(obj, dict):
return dict([(_unicode_to_ascii(key), _unicode_to_ascii(value)) for (key, value) in obj.items()])
... |
'''
Problem: 13 Reasons Why
Given 3 integers A, B, C. Do the following steps-
Swap A and B.
Multiply A by C.
Add C to B.
Output new values of A and B.
'''
# When ran, you will see a blank line, as that is needed for the submission.
# If you are debugging and want it to be easier, change it too
# input ... | """
Problem: 13 Reasons Why
Given 3 integers A, B, C. Do the following steps-
Swap A and B.
Multiply A by C.
Add C to B.
Output new values of A and B.
"""
input = input()
input_list = input.split(' ')
a = int(inputList[1])
b = int(inputList[0])
c = int(inputList[2])
a = A * C
b = C + B
a = str(A)
b = st... |
class Solution:
def maxIncreaseKeepingSkyline(self, grid):
skyline = []
for v_line in grid:
skyline.append([max(v_line)] * len(grid))
for x, h_line in enumerate(list(zip(*grid))):
max_h = max(h_line)
for y in range(len(skyline)):
skyline[... | class Solution:
def max_increase_keeping_skyline(self, grid):
skyline = []
for v_line in grid:
skyline.append([max(v_line)] * len(grid))
for (x, h_line) in enumerate(list(zip(*grid))):
max_h = max(h_line)
for y in range(len(skyline)):
skyl... |
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
output = [[]]
result = []
for num in sorted(nums):
res = [lst + [num] for lst in output]
output += res
for subset in output:
if subset not in result:
... | class Solution:
def subsets_with_dup(self, nums: List[int]) -> List[List[int]]:
output = [[]]
result = []
for num in sorted(nums):
res = [lst + [num] for lst in output]
output += res
for subset in output:
if subset not in result:
r... |
with open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/general_form_ocr.txt') as f:
text = f.readlines()
f2 = open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/dlo_address.txt', 'w+')
# data = list(set(text))
# data.sort()
# # count2 = 0
# count = {e: 0 for e in data}
# count2 = 0
for e in text:
... | with open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/general_form_ocr.txt') as f:
text = f.readlines()
f2 = open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/dlo_address.txt', 'w+')
for e in text:
e = e.strip()
length = len(e)
if length > 25:
f2.write(f'{e[:length // 2]}\n')
... |
# -*- coding: utf-8 -*-
"""Top-level package for Hauberk Email Automations."""
__author__ = """Andrew Kail"""
__email__ = 'andrew.a.kail@gmail.com'
__version__ = '0.1.0'
| """Top-level package for Hauberk Email Automations."""
__author__ = 'Andrew Kail'
__email__ = 'andrew.a.kail@gmail.com'
__version__ = '0.1.0' |
"""Common testing word list."""
# word list Breakdown
# 1: a (1)
# 2: go. no, be, by (4)
# 3: cry, fun, run, for (4)
# 4: demo, foul, wait, sell (4)
# 5: yeast, wrong, water, skill (4)
# 6: accept, admire, bicorn, biceps, planks (5)
# 7: bizonal, biofuel, bigfoot, scalene (4)
# 8: mobility, notebook, superior, taxpaye... | """Common testing word list."""
list_example = ['a', 'go', 'no', 'be', 'by', 'cry', 'fun', 'run', 'for', 'demo', 'foul', 'wait', 'sell', 'yeast', 'wrong', 'water', 'skill', 'accept', 'admire', 'bicorn', 'biceps', 'planks', 'bizonal', 'biofuel', 'bigfoot', 'scalene', 'mobility', 'notebook', 'superior', 'taxpayer', 'sque... |
def foo():
'''
>>> class bad():
... pass
'''
pass
| def foo():
"""
>>> class bad():
... pass
"""
pass |
# -*- coding: utf-8 -*-
"""
Useful exception classes that are used to return HTTP errors.
"""
class ApiException(Exception):
"""
The base exception class for all APIExceptions.
Parameters
----------
code : str
Error code.
message : str
Human readable string describing the exce... | """
Useful exception classes that are used to return HTTP errors.
"""
class Apiexception(Exception):
"""
The base exception class for all APIExceptions.
Parameters
----------
code : str
Error code.
message : str
Human readable string describing the exception.
status_code : ... |
class InstanceObjectManager:
def __init__(self, parent):
self.parent = parent
# All Instance Id's of instanced objects on this server.
self.localInstanceIds = set()
# Dict of {Temp Id: Instance Object}
self.tempId2iObject = {}
# Dict of {Instance Id: Instance Object}
self.instanceId2iObject = {}
#... | class Instanceobjectmanager:
def __init__(self, parent):
self.parent = parent
self.localInstanceIds = set()
self.tempId2iObject = {}
self.instanceId2iObject = {}
self.locationDict = {}
def store_temp_object(self, tempId, iObject):
if tempId in self.tempId2iObjec... |
def append(list1, list2):
pass
def concat(lists):
pass
def filter(function, list):
pass
def length(list):
pass
def map(function, list):
pass
def foldl(function, list, initial):
pass
def foldr(function, list, initial):
pass
def reverse(list):
pass
| def append(list1, list2):
pass
def concat(lists):
pass
def filter(function, list):
pass
def length(list):
pass
def map(function, list):
pass
def foldl(function, list, initial):
pass
def foldr(function, list, initial):
pass
def reverse(list):
pass |
class Solution:
def rob(self, nums: List[int]) -> int:
def dp(i: int) -> int:
if i == 0:
return nums[0]
if i == 1:
return max(nums[0], nums[1])
if i not in memo:
memo[i] = max(dp(i-1), nums[i]+dp(i-2))
return mem... | class Solution:
def rob(self, nums: List[int]) -> int:
def dp(i: int) -> int:
if i == 0:
return nums[0]
if i == 1:
return max(nums[0], nums[1])
if i not in memo:
memo[i] = max(dp(i - 1), nums[i] + dp(i - 2))
re... |
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# 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... | def segment_overlap(a, b, x, y):
if b < x or a > y:
return False
return True
def vector_projection_overlap(p0, p1, p2, p3):
v = p1.subtract(p0)
n_square = v.norm_square()
v0 = p2.subtract(p0)
v1 = p3.subtract(p0)
t0 = v0.dot(v)
t1 = v1.dot(v)
if t0 > t1:
t = t0
... |
class Matrix:
def transpose(self, matrix):
return list(zip(*matrix))
def column(self, matrix, i):
return [row[i] for row in matrix] | class Matrix:
def transpose(self, matrix):
return list(zip(*matrix))
def column(self, matrix, i):
return [row[i] for row in matrix] |
class Solution:
def flipLights(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
if n == 1:
return 1 if m == 0 else 2
if m == 0:
return 1
elif m & 1:
if m == 1:
return 3 if n <= 2 else 4
... | class Solution:
def flip_lights(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
if n == 1:
return 1 if m == 0 else 2
if m == 0:
return 1
elif m & 1:
if m == 1:
return 3 if n <= 2 else 4
... |
#!/usr/bin/env python3
"""
PartBuilder exception for part builder errors
"""
class PartBuilderException(Exception):
"""
Raised by PartBuilder functions when things go wrong
"""
pass
| """
PartBuilder exception for part builder errors
"""
class Partbuilderexception(Exception):
"""
Raised by PartBuilder functions when things go wrong
"""
pass |
def create_histo_table(dataname, dimPerfMap, lines, histoLambda, meanLambda, subsectitle, header):
colPairs = len(dimPerfMap)
colspecs = '|c|c|' * colPairs
lines.append("\\begin{table}[H]")
lines.append("\centering")
lines.append("\caption{%s: %s}" % (subsectitle, header))
lines.append("\\begin{adjustbox}{wid... | def create_histo_table(dataname, dimPerfMap, lines, histoLambda, meanLambda, subsectitle, header):
col_pairs = len(dimPerfMap)
colspecs = '|c|c|' * colPairs
lines.append('\\begin{table}[H]')
lines.append('\\centering')
lines.append('\\caption{%s: %s}' % (subsectitle, header))
lines.append('\\beg... |
#!/usr/bin/python
FILENAME="arr1new.txt"
def matrix2column(filename):
"""
@filename: a file contains data format looks like
<string1: value01, value02, .....>
<string2: value11, value12, .....>
return: a list looks like
[value01, value11, ......, value02, value12......]
"""
... | filename = 'arr1new.txt'
def matrix2column(filename):
"""
@filename: a file contains data format looks like
<string1: value01, value02, .....>
<string2: value11, value12, .....>
return: a list looks like
[value01, value11, ......, value02, value12......]
"""
data_list = []
... |
example_schema_array = {"type": "array", "items": {"type": "string"}}
example_array = ["string"]
example_schema_integer = {"type": "integer", "minimum": 3, "maximum": 5}
example_integer = 3
example_schema_number = {"type": "number", "minimum": 3, "maximum": 5}
example_number = 3.2
example_schema_object = {"type": "obje... | example_schema_array = {'type': 'array', 'items': {'type': 'string'}}
example_array = ['string']
example_schema_integer = {'type': 'integer', 'minimum': 3, 'maximum': 5}
example_integer = 3
example_schema_number = {'type': 'number', 'minimum': 3, 'maximum': 5}
example_number = 3.2
example_schema_object = {'type': 'obje... |
# region headers
# escript-template v20190611 / stephane.bourdeaud@nutanix.com
# * author: MITU Bogdan Nicolae (EEAS-EXT) <Bogdan-Nicolae.MITU@ext.eeas.europa.eu>
# * stephane.bourdeaud@emeagso.lab
# * version: 2019/09/18
# task_name: CalmSetProjectOwner
# description: Given a Calm project UUID, ... | username = '@@{pc.username}@@'
username_secret = '@@{pc.secret}@@'
api_server = '@@{pc_ip}@@'
nutanix_calm_user_uuid = '@@{nutanix_calm_user_uuid}@@'
nutanix_calm_user_upn = '@@{calm_username}@@'
project_uuid = '@@{project_uuid}@@'
api_server_port = '9440'
api_server_endpoint = '/api/nutanix/v3/projects_internal/{}'.fo... |
class TCPControlFlags():
def __init__(self):
'''Control Bits govern the entire process of connection establishment, data transmissions and connection termination. The control bits are listed as follows, they are'''
'''It indicates if we need to use Urgent pointer field or not. If it is set to 1 th... | class Tcpcontrolflags:
def __init__(self):
"""Control Bits govern the entire process of connection establishment, data transmissions and connection termination. The control bits are listed as follows, they are"""
'It indicates if we need to use Urgent pointer field or not. If it is set to 1 then on... |
def isPalindrome(string):
if len(string) <= 1:
return True
else:
return string[0] == string[-1] and isPalindrome(string[1:-1])
userInput = input("Please enter a sequence to check if it is an palindrome: ")
answer = isPalindrome(userInput)
print("Is '" + userInput + "' an palindrome? " + str(a... | def is_palindrome(string):
if len(string) <= 1:
return True
else:
return string[0] == string[-1] and is_palindrome(string[1:-1])
user_input = input('Please enter a sequence to check if it is an palindrome: ')
answer = is_palindrome(userInput)
print("Is '" + userInput + "' an palindrome? " + str(... |
#! /usr/bin/env python3
#
# === This file is part of Calamares - <https://calamares.io> ===
#
# SPDX-FileCopyrightText: 2019 Adriaan de Groot <groot@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
#
"""
Python3 script to scrape some data out of zoneinfo/zone.tab.
To use this script, you must have a zone.tab in a... | """
Python3 script to scrape some data out of zoneinfo/zone.tab.
To use this script, you must have a zone.tab in a standard location,
/usr/share/zoneinfo/zone.tab (this is usual on FreeBSD and Linux).
Prints out a few tables of zone names for use in translations.
"""
def scrape_file(file, regionset, zoneset):
fo... |
N = int(input())
A = [int(n) for n in input().split()]
Aset = set(A)
m = (10**9+7)
o = {}
ans = []
for a in A:
o.setdefault(a, 0)
o[a] += 1
for i in range(len(Aset)-1):
for j in range(i+1, len(Aset)):
ans.append((A[i]^A[j])*o[A[i]]*o[A[j]])
print(sum(ans)/m)
| n = int(input())
a = [int(n) for n in input().split()]
aset = set(A)
m = 10 ** 9 + 7
o = {}
ans = []
for a in A:
o.setdefault(a, 0)
o[a] += 1
for i in range(len(Aset) - 1):
for j in range(i + 1, len(Aset)):
ans.append((A[i] ^ A[j]) * o[A[i]] * o[A[j]])
print(sum(ans) / m) |
# DOWNLOADER_MIDDLEWARES = {}
# DOWNLOADER_MIDDLEWARES.update({
# 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': None,
# 'scrapy_httpcache.downloadermiddlewares.httpcache.AsyncHttpCacheMiddleware': 900,
# })
HTTPCACHE_STORAGE = 'scrapy_httpcache.extensions.httpcache_storage.MongoDBCacheStorage'
... | httpcache_storage = 'scrapy_httpcache.extensions.httpcache_storage.MongoDBCacheStorage'
httpcache_mongodb_host = '127.0.0.1'
httpcache_mongodb_port = 27017
httpcache_mongodb_username = None
httpcache_mongodb_password = None
httpcache_mongodb_auth_db = None
httpcache_mongodb_db = 'cache_storage'
httpcache_mongodb_coll =... |
def flatten(aList):
myList = []
for el in aList:
if isinstance(el, list) or isinstance(el, tuple):
myList.extend(flatten(el))
else:
myList.append(el)
return myList
| def flatten(aList):
my_list = []
for el in aList:
if isinstance(el, list) or isinstance(el, tuple):
myList.extend(flatten(el))
else:
myList.append(el)
return myList |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def zlib():
if "zlib" not in native.existing_rules():
http_archive(
name = "zlib",
build_file = "//third_party/zlib:zlib.BUILD",
sha256 = "91844808532e5ce316b3c010929493c0244f3d37593afd6de04f71821d5136d... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def zlib():
if 'zlib' not in native.existing_rules():
http_archive(name='zlib', build_file='//third_party/zlib:zlib.BUILD', sha256='91844808532e5ce316b3c010929493c0244f3d37593afd6de04f71821d5136d9', strip_prefix='zlib-1.2.12', url='https:... |
class Sampler(object):
def __init__(self):
self._params = None
self._dim = None
self._iteration = 0
def setParameters(self, params):
self._params = params
self._dim = params.getStochasticDim()
def nextSamples(self, *args, **kws):
raise NotImplementedError()... | class Sampler(object):
def __init__(self):
self._params = None
self._dim = None
self._iteration = 0
def set_parameters(self, params):
self._params = params
self._dim = params.getStochasticDim()
def next_samples(self, *args, **kws):
raise not_implemented_err... |
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.main_trie = dict()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
nav = self.main_trie
#print(f"Inserting {word}")
f... | class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.main_trie = dict()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
nav = self.main_trie
for c in word:
if c in nav:
... |
#
def calcula_investimento(inv, mes, tipo):
# seleciona tipo de investimento
# CDB
if tipo == 'CDB':
for i in range(1, mes + 1):
inv = inv * 1.013
if i % 6 == 0:
inv = inv * 1.012
# LCI
elif tipo == 'LCI':
inv = inv*1.016**(... | def calcula_investimento(inv, mes, tipo):
if tipo == 'CDB':
for i in range(1, mes + 1):
inv = inv * 1.013
if i % 6 == 0:
inv = inv * 1.012
elif tipo == 'LCI':
inv = inv * 1.016 ** mes
'for i in range(1, mes + 1):\n inv = inv * 1.016'
... |
#!/usr/bin/env python3
def collatz(x):
if x <= 0:
raise ValueError("Collatz has become 0")
if (x % 2) == 0:
return x/2
else:
return 3*x+1
if __name__ == "__main__":
number = 10
print("Ausgangszahl: ", number)
iteration = 0
while True:
number = collatz(numbe... | def collatz(x):
if x <= 0:
raise value_error('Collatz has become 0')
if x % 2 == 0:
return x / 2
else:
return 3 * x + 1
if __name__ == '__main__':
number = 10
print('Ausgangszahl: ', number)
iteration = 0
while True:
number = collatz(number)
iteration ... |
'''
256 definitions cause LOAD_NAME and LOAD_CONST to both require EXTENDED_ARGS.
Generated with: `for i in range(0, 0xff, 0x10): print(*[f'x{j:02x}=0x{j:02x}' for j in range(i, i+0x10)], sep='; ')`
'''
x00=0x00; x01=0x01; x02=0x02; x03=0x03; x04=0x04; x05=0x05; x06=0x06; x07=0x07; x08=0x08; x09=0x09; x0a=0x0a; x0b=0x... | """
256 definitions cause LOAD_NAME and LOAD_CONST to both require EXTENDED_ARGS.
Generated with: `for i in range(0, 0xff, 0x10): print(*[f'x{j:02x}=0x{j:02x}' for j in range(i, i+0x10)], sep='; ')`
"""
x00 = 0
x01 = 1
x02 = 2
x03 = 3
x04 = 4
x05 = 5
x06 = 6
x07 = 7
x08 = 8
x09 = 9
x0a = 10
x0b = 11
x0c = 12
x0d = 13
x... |
# This function tells a user whether or not a number is prime
def isPrime(number):
# this will tell us if the number is prime, set to True automatically
# We will set to False if the number is divisible by any number less than it
number_is_prime = True
# loop over all numbers less than the input numb... | def is_prime(number):
number_is_prime = True
for i in range(2, number):
remainder = number % i
if remainder == 0:
number_is_prime = False
return number_is_prime |
class Solution:
def longestCommonSubstring(self, a, b):
matrix = [[0 for _ in range(len(b))] for _ in range((len(a)))]
z = 0
ret = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
if i == 0 or j == 0:
... | class Solution:
def longest_common_substring(self, a, b):
matrix = [[0 for _ in range(len(b))] for _ in range(len(a))]
z = 0
ret = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
if i == 0 or j == 0:
... |
# Copyright (c) 2020 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | def _split_counter_from_name(str):
if len(str) > 0 and (not str[-1].isdigit()):
return (str, None)
i = len(str)
while i > 0:
if not str[i - 1].isdigit():
return (str[:i], int(str[i:]))
i -= 1
return (None, int(str))
def generate_tensor_names_from_op_type(graph, keep_... |
sigla = input('Digite uma das siglas: SP / RJ / MG: ')
if sigla == 'RJ' or sigla == 'rj':
print('Carioca')
elif sigla == 'SP' or sigla == 'sp':
print('Paulista')
elif sigla == 'MG' or sigla == 'mg':
print('Mineiro')
else:
print('Outro estado') | sigla = input('Digite uma das siglas: SP / RJ / MG: ')
if sigla == 'RJ' or sigla == 'rj':
print('Carioca')
elif sigla == 'SP' or sigla == 'sp':
print('Paulista')
elif sigla == 'MG' or sigla == 'mg':
print('Mineiro')
else:
print('Outro estado') |
"""
Module: 'flowlib.lib.emoji' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
class Emoji:
''
def clear():
pass
def draw_square():
pass
def sho... | """
Module: 'flowlib.lib.emoji' on M5 FlowUI v1.4.0-beta
"""
class Emoji:
""""""
def clear():
pass
def draw_square():
pass
def show_love():
pass
def show_map():
pass
def show_normal():
pass
lcd = None
def sleep():
pass |
# Copyright (c) 2019 Ezybaas by Bhavik Shah.
# CTO @ Susthitsoft Technologies Private Limited.
# All rights reserved.
# Please see the LICENSE.txt included as part of this package.
# EZYBAAS RELEASE CONFIG
EZYBAAS_RELEASE_NAME = 'EzyBaaS'
EZYBAAS_RELEASE_AUTHOR = 'Bhavik Shah CTO @ SusthitSoft Technologies'
EZYBAAS_RE... | ezybaas_release_name = 'EzyBaaS'
ezybaas_release_author = 'Bhavik Shah CTO @ SusthitSoft Technologies'
ezybaas_release_version = '0.1.4'
ezybaas_release_date = '2019-07-20'
ezybaas_release_notes = 'https://github.com/bhavik1st/ezybaas'
ezybaas_release_standalone = True
ezybaas_release_license = 'https://github.com/bhav... |
#Oskar Svedlund
#TEINF-20
#2021-09-20
#For i For loop
for i in range(1,10):
for j in range(1,10):
print(i*j, end="\t")
print()
| for i in range(1, 10):
for j in range(1, 10):
print(i * j, end='\t')
print() |
#!/usr/bin/env python
'''
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'StackPath (StackPath)'
def is_waf(self):
schemes = [
self.matchContent(r"This website is using a security service to protect itself"),
self.matchContent(r'You performed an ac... | """
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
"""
name = 'StackPath (StackPath)'
def is_waf(self):
schemes = [self.matchContent('This website is using a security service to protect itself'), self.matchContent('You performed an action that triggered the service and blocked... |
"""Advent of Code Day 4 - High-Entropy Passphrases"""
# Open list, read it and split by newline
pass_txt = open('inputs/day_04.txt')
lines = pass_txt.read()
pass_list = lines.split('\n')
def dupe_check(passphrase):
"""Return only if input has no duplicate words in it."""
words = passphrase.split(' ')
un... | """Advent of Code Day 4 - High-Entropy Passphrases"""
pass_txt = open('inputs/day_04.txt')
lines = pass_txt.read()
pass_list = lines.split('\n')
def dupe_check(passphrase):
"""Return only if input has no duplicate words in it."""
words = passphrase.split(' ')
unique = set(words)
if words != ['']:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.