content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module CISCO-STACK-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACK-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:12:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ... |
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache='localhost',
instrument='ESTIA',
experiment='Exp',
datasinks=['conssink', 'filesink', 'daemonsink'],
)
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(
ESTIA=device('nicos.devices.instrument.Instrum... | description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='ESTIA', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink'])
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(ESTIA=device('nicos.devices.instrument.Instrument', description='instrument... |
a = float(input())
b = float(input())
c = float(input())
media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5)
print("MEDIA = {:.1f}".format(media))
| a = float(input())
b = float(input())
c = float(input())
media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5)
print('MEDIA = {:.1f}'.format(media)) |
#Aula 7
#Dicionarios
lista = []
# dicionario = {'Nome':'Matheus', 'Sobrenome': 'Schuetz' }
# print(dicionario)
# print(dicionario['Sobrenome'])
nome = 'Maria'
lista_notas = [10,20,50,70]
media = sum(lista_notas)/len(lista_notas)
situacao = 'Reprovado'
if media >=7:
situacao = 'Aprovado'
dicionario_alunos = {'No... | lista = []
nome = 'Maria'
lista_notas = [10, 20, 50, 70]
media = sum(lista_notas) / len(lista_notas)
situacao = 'Reprovado'
if media >= 7:
situacao = 'Aprovado'
dicionario_alunos = {'Nome': nome, 'Lista_Notas': lista_notas, 'Media': media, 'Situacao': situacao}
print(f"{dicionario_alunos['Nome']} - {dicionario_alun... |
TEACHER_AUTHORITIES = [
'VIEW_PROFILE',
'JUDGE_TASK',
'SHARE_TASK',
'VIEW_ABSENT',
'SUBMIT_LESSON',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'EDIT_PROFILE',
'GIVE_TASK',
'VIEW_TASK',
'ADD_ABSENT'
]
STUDENT_AUTHORITIES = [
'VIEW_PROFILE',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'VIEW_TASK_FRAGMENT',
'DOING_TASK',
'VIEW... | teacher_authorities = ['VIEW_PROFILE', 'JUDGE_TASK', 'SHARE_TASK', 'VIEW_ABSENT', 'SUBMIT_LESSON', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'EDIT_PROFILE', 'GIVE_TASK', 'VIEW_TASK', 'ADD_ABSENT']
student_authorities = ['VIEW_PROFILE', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'VIEW_TASK_FRAGMENT', 'DOING_TASK', 'VIEW_ABSENT', 'EDIT_PROFI... |
def _init():
global _global_dict
_global_dict = {}
def set_value(key, value):
_global_dict[key] = value
def get_value(key):
return _global_dict.get(key)
_init() | def _init():
global _global_dict
_global_dict = {}
def set_value(key, value):
_global_dict[key] = value
def get_value(key):
return _global_dict.get(key)
_init() |
#
# PySNMP MIB module CISCO-VLAN-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-GROUP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) ... |
def hello_world():
print("hello world")
# [REQ-002]
def hello_world_2():
print("hello world")
# [/REQ-002]
| def hello_world():
print('hello world')
def hello_world_2():
print('hello world') |
class Solution:
def solve(self, s, pairs):
letters = set(ascii_lowercase)
leaders = {letter:letter for letter in letters}
followers = {letter:[letter] for letter in letters}
for a,b in pairs:
if leaders[a] == leaders[b]: continue
if len(followers... | class Solution:
def solve(self, s, pairs):
letters = set(ascii_lowercase)
leaders = {letter: letter for letter in letters}
followers = {letter: [letter] for letter in letters}
for (a, b) in pairs:
if leaders[a] == leaders[b]:
continue
if len(f... |
prompt = "How old are you?"
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
age = int(message)
if age < 3:
print("Free")
elif age < 12:
print("The fare is 10 dollar")
else:
print("The fare is 15 dollar")
| prompt = 'How old are you?'
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':
age = int(message)
if age < 3:
print('Free')
elif age < 12:
print('The fare is 10 dollar')
else:
print('The fare is 15 dollar') |
# Variables
first_name = "Ada"
# print function followed by variable name.
print("Hello,", first_name)
print(first_name, "is learning Python")
# print takes multiple arguments.
print("These", "will be", "joined together by spaces")
# input statement.
first_name = input("What is your first name? ")
print("Hello,", fi... | first_name = 'Ada'
print('Hello,', first_name)
print(first_name, 'is learning Python')
print('These', 'will be', 'joined together by spaces')
first_name = input('What is your first name? ')
print('Hello,', first_name) |
def extractThehlifestyleCom(item):
'''
Parser for 'thehlifestyle.com'
'''
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "... | def extract_thehlifestyle_com(item):
"""
Parser for 'thehlifestyle.com'
"""
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""Volatility 3 Linux Constants.
Windows-specific values that aren't found in debug symbols
"""
KERNEL_MODULE_NAMES = ["ntkrnlmp", ... | """Volatility 3 Linux Constants.
Windows-specific values that aren't found in debug symbols
"""
kernel_module_names = ['ntkrnlmp', 'ntkrnlpa', 'ntkrpamp', 'ntoskrnl']
'The list of names that kernel modules can have within the windows OS' |
"""
This subpackage is intented for low-level extension developers and compiler
developers. Regular user SHOULD NOT use code in this module.
This contains compilable utility functions that can interact directly with
the compiler to implement low-level internal code.
"""
| """
This subpackage is intented for low-level extension developers and compiler
developers. Regular user SHOULD NOT use code in this module.
This contains compilable utility functions that can interact directly with
the compiler to implement low-level internal code.
""" |
'''
Given the root of a binary tree,
check whether it is a mirror of itself (i.e., symmetric around its center).
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is n... | '''
Given the root of a binary tree,
check whether it is a mirror of itself (i.e., symmetric around its center).
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ 2 2
/ \\ / 3 4 4 3
But the following is not:... |
""" Definitions used to parse DTED files. """
# Definitions of DTED Record lengths.
UHL_SIZE = 80
DSI_SIZE = 648
ACC_SIZE = 2700
# Definitions of the value DTED uses for void data.
VOID_DATA_VALUE = (-1 << 15) + 1
_UTF8 = "utf-8"
| """ Definitions used to parse DTED files. """
uhl_size = 80
dsi_size = 648
acc_size = 2700
void_data_value = (-1 << 15) + 1
_utf8 = 'utf-8' |
ATTACK = '-'
SUPPORT = '+'
NEUTRAL = '0'
CRITICAL_SUPPORT = '+!'
CRITICAL_ATTACK = '-!'
WEAK_SUPPORT = '+*'
WEAK_ATTACK = '-*'
NON_SUPPORT = '+~'
NON_ATTACK = '-~'
TRIPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL]
QUADPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT]
def get_type(val):
if val > 0:
... | attack = '-'
support = '+'
neutral = '0'
critical_support = '+!'
critical_attack = '-!'
weak_support = '+*'
weak_attack = '-*'
non_support = '+~'
non_attack = '-~'
tripolar_relations = [ATTACK, SUPPORT, NEUTRAL]
quadpolar_relations = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT]
def get_type(val):
if val > 0:
... |
# repeating strings
s = "?"
for i in range(4):
print(s, end="")
print()
print(s * 4)
# looping strings
text = "This is an example."
count = 0
for char in text:
# isalpha() returns true if the character is a-z
if char.isalpha():
count += 1 | s = '?'
for i in range(4):
print(s, end='')
print()
print(s * 4)
text = 'This is an example.'
count = 0
for char in text:
if char.isalpha():
count += 1 |
CREDENTIALS = {
'username': 'Replace with your WA username',
'password': 'Replace with your WA password (b64)'
}
DEFAULT_RECIPIENTS = ('single-user@s.whatsapp.net', 'group-chat@g.us',)
HOST_NOTIFICATION = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + \
'Host %(host)s, %(address)s is %(st... | credentials = {'username': 'Replace with your WA username', 'password': 'Replace with your WA password (b64)'}
default_recipients = ('single-user@s.whatsapp.net', 'group-chat@g.us')
host_notification = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + 'Host %(host)s, %(address)s is %(state)s.\n\n' + '%(info)s\n\n' + '%(t... |
'''9. Write a Python program to get the difference between the two lists. '''
def difference_twoLists(lst1, lst2):
lst1 = set(lst1)
lst2 = set(lst2)
return list(lst1 - lst2)
print(difference_twoLists([1, 2, 3, 4], [4, 5, 6, 7]))
print(difference_twoLists([1, 2, 3, 4], [0, 5, 6, 7]))
print(difference_twoLis... | """9. Write a Python program to get the difference between the two lists. """
def difference_two_lists(lst1, lst2):
lst1 = set(lst1)
lst2 = set(lst2)
return list(lst1 - lst2)
print(difference_two_lists([1, 2, 3, 4], [4, 5, 6, 7]))
print(difference_two_lists([1, 2, 3, 4], [0, 5, 6, 7]))
print(difference_two... |
'''
module for implementation of
cycle sort
'''
def cycle_sort(arr: list):
writes = 0
for cycleStart in range(0, len(arr) - 1):
item = arr[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if (arr[i] < item):
pos += 1
if (p... | """
module for implementation of
cycle sort
"""
def cycle_sort(arr: list):
writes = 0
for cycle_start in range(0, len(arr) - 1):
item = arr[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if arr[i] < item:
pos += 1
if pos == cyc... |
class Error(Exception):
"""Base class for BMI exceptions"""
pass
class VarNameError(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class BMI(object):
def initialize(self, f... | class Error(Exception):
"""Base class for BMI exceptions"""
pass
class Varnameerror(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Bmi(object):
def initialize(self, fil... |
class Script:
@staticmethod
def main():
cities = ["Albuquerque", "Anaheim", "Anchorage", "Arlington", "Atlanta", "Aurora", "Austin", "Bakersfield", "Baltimore", "Boston", "Buffalo", "Charlotte-Mecklenburg", "Cincinnati", "Cleveland", "Colorado Springs", "Corpus Christi", "Dallas", "Denver", "Detroit", "El Paso", "... | class Script:
@staticmethod
def main():
cities = ['Albuquerque', 'Anaheim', 'Anchorage', 'Arlington', 'Atlanta', 'Aurora', 'Austin', 'Bakersfield', 'Baltimore', 'Boston', 'Buffalo', 'Charlotte-Mecklenburg', 'Cincinnati', 'Cleveland', 'Colorado Springs', 'Corpus Christi', 'Dallas', 'Denver', 'Detroit', ... |
"""
Some of the options of the protocol specification
LINE
1-8
PAGE
A-Z (remapped to 0-25)
LEADING
A/a = Immediate (Image will be immediately disappeared)
B/b = Xopen (Image will be disappeared from center and extend to 4 side)
C/c = Curtain UP (Image will be disappeared one ... | """
Some of the options of the protocol specification
LINE
1-8
PAGE
A-Z (remapped to 0-25)
LEADING
A/a = Immediate (Image will be immediately disappeared)
B/b = Xopen (Image will be disappeared from center and extend to 4 side)
C/c = Curtain UP (Image will be disappeared one ... |
fig, ax = create_map_background()
# Contour 1 - Temperature, dotted
cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2),
colors='grey', linestyles='dotted', transform=dataproj)
plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
rightside_up=True, use_clabelte... | (fig, ax) = create_map_background()
cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2), colors='grey', linestyles='dotted', transform=dataproj)
plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)
clev850 = np.arange(0, 4000, 30)
cs = ax.contour(lon,... |
#Ejercicio 01
def binarySearch(arr, valor):
#Dado un arreglo y un elemento
#Busca el elemento dado en el arreglo
inicio = 0
final = len(arr) - 1
while inicio <= final:
medio = (inicio + final) // 2
if arr[medio] == valor:
return True
elif arr[medio... | def binary_search(arr, valor):
inicio = 0
final = len(arr) - 1
while inicio <= final:
medio = (inicio + final) // 2
if arr[medio] == valor:
return True
elif arr[medio] < valor:
inicio = medio + 1
elif arr[medio] > valor:
final = medio - 1
... |
# William Thompson (wtt53)
# Software Testing and QA
# Assignment 1: Test Driven Development
# Retirement: Takes current age (int), annual salary (float),
# percent of annual salary saved (float), and savings goal (float)
# and outputs what age savings goal will be met
def calc_retirement(age, salary, percent, goal):... | def calc_retirement(age, salary, percent, goal):
try:
age = int(age)
salary = float(salary)
percent = float(percent)
goal = float(goal)
except Exception:
return False
if (age < 15 or age > 99) or salary <= 0 or percent <= 0 or (goal <= 0):
return False
raw... |
"""
this module provides encryption and decryption of strings
"""
_eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
_rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)]
_alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet}
def _add_encrypted_... | """
this module provides encryption and decryption of strings
"""
_eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
_rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)]
_alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet}
def _add_encrypted_cha... |
def solution(value):
print("Solution: {}".format(value))
| def solution(value):
print('Solution: {}'.format(value)) |
# See LICENSE for licensing information.
#
# Copyright (c) 2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
class test_bench:
"""
Class to generate the ... | class Test_Bench:
"""
Class to generate the test bench file for simulation.
"""
def __init__(self, cache_config, name):
cache_config.set_local_config(self)
self.name = name
self.success_message = 'Simulation successful.'
self.failure_message = 'Simulation failed.'
d... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message... | def test():
assert not world_df is None, 'Your answer for world_df does not exist. Have you loaded the TopoJSON data to the correct variable name?'
assert 'topo_feature' in __solution__, 'The loaded data should be in TopoJSON format. In order to read TopoJSON file correctly, you need to use the alt.topo_feature... |
class SimpleSpriteList:
def __init__(self) -> None:
self.sprites = list()
def draw(self) -> None:
for sprite in self.sprites:
sprite.draw()
def update(self) -> None:
for sprite in self.sprites:
sprite.update()
def append(self, sprite) -> None:
... | class Simplespritelist:
def __init__(self) -> None:
self.sprites = list()
def draw(self) -> None:
for sprite in self.sprites:
sprite.draw()
def update(self) -> None:
for sprite in self.sprites:
sprite.update()
def append(self, sprite) -> None:
... |
"""
Problem: https://www.hackerrank.com/challenges/nested-list/problem
Max Score: 10
Difficulty: Easy
Author: Ric
Date: Nov 13, 2019
"""
def secondLow(classList):
secondLowScore = sorted(set(m[1] for m in classList))[1]
result = sorted([m[0] for m in classList if m[1] == secondLowScore])
return result
n =... | """
Problem: https://www.hackerrank.com/challenges/nested-list/problem
Max Score: 10
Difficulty: Easy
Author: Ric
Date: Nov 13, 2019
"""
def second_low(classList):
second_low_score = sorted(set((m[1] for m in classList)))[1]
result = sorted([m[0] for m in classList if m[1] == secondLowScore])
return result... |
numberLines = int(input())
while 0 < numberLines:
number = int(input())
sum = 0
for i in range(number):
if i%3 == 0 or i%5 == 0:
sum = sum + i
print(sum)
numberLines = numberLines - 1 | number_lines = int(input())
while 0 < numberLines:
number = int(input())
sum = 0
for i in range(number):
if i % 3 == 0 or i % 5 == 0:
sum = sum + i
print(sum)
number_lines = numberLines - 1 |
#!/usr/bin/env python3
#bpm to millisecond for compressor release
def compressor_release(bpm, note_length):
'''
Inputs: BPM, note length
Output: compression release time
Note: Function returns perfect compression release time for standard note lengths. Electronic music is not standard mus ic so t... | def compressor_release(bpm, note_length):
"""
Inputs: BPM, note length
Output: compression release time
Note: Function returns perfect compression release time for standard note lengths. Electronic music is not standard mus ic so this does not have much of an application
"""
standard_lengths... |
#Mock class for GPIO
BOARD = 1
BCM = 2
OUT = 1
IN = 1
HIGH = 1
LOW = 0
def setmode(a):
print ("setmode GPIO",a)
def setup(a, b):
print ("setup GPIO", a, b)
def output(a, b):
print ("output GPIO", a, b)
def cleanup():
print ("cleanup GPIO", a, b)
def setwarnings(flag):
print ("setwarnings"... | board = 1
bcm = 2
out = 1
in = 1
high = 1
low = 0
def setmode(a):
print('setmode GPIO', a)
def setup(a, b):
print('setup GPIO', a, b)
def output(a, b):
print('output GPIO', a, b)
def cleanup():
print('cleanup GPIO', a, b)
def setwarnings(flag):
print('setwarnings', flag) |
__author__ = 'yinjun'
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n<=2 :
return n
stairs = [0 for i in range(n)]
stairs[0] = 1
stairs[1] = 2
for i in range(2, n):... | __author__ = 'yinjun'
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climb_stairs(self, n):
if n <= 2:
return n
stairs = [0 for i in range(n)]
stairs[0] = 1
stairs[1] = 2
for i in range(2, n):
stairs[i] = stairs[... |
# Damage Skin - Violetta
success = sm.addDamageSkin(2433197)
if success:
sm.chat("The Damage Skin - Violetta has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2433197)
if success:
sm.chat("The Damage Skin - Violetta has been added to your account's damage skin collection.") |
#!/usr/bin/env python3
formulas = [
"XNd perr",
"PNd (PNd (call And (XNu exc)))",
"PNd (han And (XNd (exc And (XBu call))))",
"G (exc --> XBu call)",
"T Ud exc",
"PNd (PNd (T Ud exc))",
"G ((call And pa And ((~ ret) Ud WRx)) --> XNu exc)",
"PNd (PBu call)",
"PNd (PNd (PNd (PBu call)... | formulas = ['XNd perr', 'PNd (PNd (call And (XNu exc)))', 'PNd (han And (XNd (exc And (XBu call))))', 'G (exc --> XBu call)', 'T Ud exc', 'PNd (PNd (T Ud exc))', 'G ((call And pa And ((~ ret) Ud WRx)) --> XNu exc)', 'PNd (PBu call)', 'PNd (PNd (PNd (PBu call)))', 'XNd (PNd (PBu call))', 'G ((call And pa And (PNu exc Or... |
class Iterator(object):
def __init__(self, iterable, looping: bool = False):
self.iterable = iterable
self.lastPos = 0
self.looping = looping
def __next__(self):
pos = self.lastPos
self.lastPos += 1
if self.lastPos >= len(self.iterable):
if self.looping:
self.lastPos = 0
else:
raise StopIt... | class Iterator(object):
def __init__(self, iterable, looping: bool=False):
self.iterable = iterable
self.lastPos = 0
self.looping = looping
def __next__(self):
pos = self.lastPos
self.lastPos += 1
if self.lastPos >= len(self.iterable):
if self.loopin... |
##################################################################################
#### Runtime configuration
##################################################################################
sampleCounter = 0
##################################################################################
#### General configurati... | sample_counter = 0
version = '1.0.2103.0401'
lcd_i2c_expander_type = 'PCF8574'
lcd_i2c_address = 39
lcd_column_count = 20
lcd_row_count = 4 |
# REPLACE EVERYTHING IN CURLY BRACKETS {}, INCLUDING THE BRACKETS THEMSELVES.
# THEN RENAME THIS FILE TO constants.py AND MOVE IT INTO YOUR PROJECT'S ROOT
CONNECT_BASE_URL = '{YOUR BASE URL}/api/xml?action='
CONNECT_LOGIN = '{YOUR LOGIN}'
CONNECT_PWD = '{YOUR PASSWORD}'
# USERS YOU WANT TO BE ABLE TO EXCLUDE FROM REP... | connect_base_url = '{YOUR BASE URL}/api/xml?action='
connect_login = '{YOUR LOGIN}'
connect_pwd = '{YOUR PASSWORD}'
connect_admin_users = ['{USER1LOGIN}', '{USER2LOGIN}', '{USER3LOGIN}'] |
# -*- coding: utf-8 -*-
def crearCombinaciones(abecedario):
for d1 in abecedario:
for d2 in abecedario:
for d3 in abecedario:
for d4 in abecedario:
#print(d1 + '' + d2 + '' + d3 + '' + d4)
f.write(d1 + '' + d2 + '' + d3 + '' + d4)
... | def crear_combinaciones(abecedario):
for d1 in abecedario:
for d2 in abecedario:
for d3 in abecedario:
for d4 in abecedario:
f.write(d1 + '' + d2 + '' + d3 + '' + d4)
f.write('\n')
abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ... |
set_name(0x8009CFEC, "VID_OpenModule__Fv", SN_NOWARN)
set_name(0x8009D0AC, "InitScreens__Fv", SN_NOWARN)
set_name(0x8009D19C, "MEM_SetupMem__Fv", SN_NOWARN)
set_name(0x8009D1C8, "SetupWorkRam__Fv", SN_NOWARN)
set_name(0x8009D258, "SYSI_Init__Fv", SN_NOWARN)
set_name(0x8009D364, "GM_Open__Fv", SN_NOWARN)
set_name(0x8009... | set_name(2148126700, 'VID_OpenModule__Fv', SN_NOWARN)
set_name(2148126892, 'InitScreens__Fv', SN_NOWARN)
set_name(2148127132, 'MEM_SetupMem__Fv', SN_NOWARN)
set_name(2148127176, 'SetupWorkRam__Fv', SN_NOWARN)
set_name(2148127320, 'SYSI_Init__Fv', SN_NOWARN)
set_name(2148127588, 'GM_Open__Fv', SN_NOWARN)
set_name(214812... |
class MusicTextView:
"""This class represents one instance of a view for the music maze. The
purpose of this class is to represent the maze through text and also to
create a basis on the methods needed to cover all of the view's expected
features for sanity checking purposes."""
| class Musictextview:
"""This class represents one instance of a view for the music maze. The
purpose of this class is to represent the maze through text and also to
create a basis on the methods needed to cover all of the view's expected
features for sanity checking purposes.""" |
lr_scheduler = dict(
name='poly_scheduler',
epochs=30,
power=0.9
)
| lr_scheduler = dict(name='poly_scheduler', epochs=30, power=0.9) |
size(800, 600)
background(255)
triangle(20, 20, 20, 50, 50, 20)
triangle(200, 100, 200, 150, 300, 320)
triangle(700, 500, 800, 550, 600, 600) | size(800, 600)
background(255)
triangle(20, 20, 20, 50, 50, 20)
triangle(200, 100, 200, 150, 300, 320)
triangle(700, 500, 800, 550, 600, 600) |
def get_bit_mask(bit_num):
"""Returns as bit mask with bit_num set.
:param bit_num: The bit number.
:type bit_num: int
:returns: int -- the bit mask
:raises: RangeError
>>> bin(pifacecommon.core.get_bit_mask(0))
1
>>> pifacecommon.core.get_bit_mask(1)
2
>>> bin(pifacecommon.cor... | def get_bit_mask(bit_num):
"""Returns as bit mask with bit_num set.
:param bit_num: The bit number.
:type bit_num: int
:returns: int -- the bit mask
:raises: RangeError
>>> bin(pifacecommon.core.get_bit_mask(0))
1
>>> pifacecommon.core.get_bit_mask(1)
2
>>> bin(pifacecommon.cor... |
"""
Module: 'lidar' 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
def deinit():
pass
def distance():
pass
def draw_map():
pass
def get_distance():
pass
def ge... | """
Module: 'lidar' on M5 FlowUI v1.4.0-beta
"""
def deinit():
pass
def distance():
pass
def draw_map():
pass
def get_distance():
pass
def get_frame():
pass
def init():
pass |
"""Functions for determining micrograph scaling.
"""
def determine_scaling(image, bar_length_um, bar_frac):
r"""Determine um per pixels scaling for an image provided the bar length in um and the fraction of the image for
which it occupies.
Parameters
----------
image : ndarray
Input image... | """Functions for determining micrograph scaling.
"""
def determine_scaling(image, bar_length_um, bar_frac):
"""Determine um per pixels scaling for an image provided the bar length in um and the fraction of the image for
which it occupies.
Parameters
----------
image : ndarray
Input image. ... |
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 152, 0)
deep_orange = (255, 87, 34)
brown = (121, 85, 72)
green = (0, 128, 0)
light_green = (139, 195, 74)
teal = (0, 150, 136)
blue = (33, 150, 136)
purple = (156, 39, 176)
pink = (234, 30, 99)
deep_purple = (103, 58, 183)
color_dict = {
0: black,... | black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 152, 0)
deep_orange = (255, 87, 34)
brown = (121, 85, 72)
green = (0, 128, 0)
light_green = (139, 195, 74)
teal = (0, 150, 136)
blue = (33, 150, 136)
purple = (156, 39, 176)
pink = (234, 30, 99)
deep_purple = (103, 58, 183)
color_dict = {0: black, 2: red, 4: green, 8: ... |
#part 1
count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
with open("input.txt") as f:
for line in f:
if line != '\n':
fields = {i[:3] for i in line.split(' ')}
received_fields.update(fields)
else:
difference = e... | count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
with open('input.txt') as f:
for line in f:
if line != '\n':
fields = {i[:3] for i in line.split(' ')}
received_fields.update(fields)
else:
difference = expected_... |
ACTION_CREATED = 'created'
ACTION_UPDATED = 'updated'
ACTION_DELETED = 'deleted'
ACTION_OTHER = 'other'
ACTION_CHOICES = (
(ACTION_CREATED, ACTION_CREATED),
(ACTION_UPDATED, ACTION_UPDATED),
(ACTION_DELETED, ACTION_DELETED),
(ACTION_OTHER, ACTION_OTHER),
)
LOG_LEVEL_CRITICAL = 'CRITICAL'
LOG_LEVEL_ERRO... | action_created = 'created'
action_updated = 'updated'
action_deleted = 'deleted'
action_other = 'other'
action_choices = ((ACTION_CREATED, ACTION_CREATED), (ACTION_UPDATED, ACTION_UPDATED), (ACTION_DELETED, ACTION_DELETED), (ACTION_OTHER, ACTION_OTHER))
log_level_critical = 'CRITICAL'
log_level_error = 'ERROR'
log_leve... |
"""
A command line interface to the qcfractal.
"""
# from tornado.options import options, define
# import tornado.ioloop
# import tornado.web
# define("port", default=8888, help="Run on the given port.", type=int)
# define("mongod_ip", default="127.0.0.1", help="The Mongod instances IP.", type=str)
# define("mongod_p... | """
A command line interface to the qcfractal.
"""
if __name__ == '__main__':
server = qcdb_server()
server.start()
def main():
server = qcfractal.server()
server.start()
if __name__ == '__main__':
main() |
def interest(n, principle_amount):
def years(x):
return principle_amount + (n * principle_amount * x) / 100
return years
principle = 100000
home_loan = interest(7, principle) # percentage of 7
personal_loan = interest(11, principle) # percentage of 11
print(home_loan(20)) # for 20 years
print(per... | def interest(n, principle_amount):
def years(x):
return principle_amount + n * principle_amount * x / 100
return years
principle = 100000
home_loan = interest(7, principle)
personal_loan = interest(11, principle)
print(home_loan(20))
print(personal_loan(3)) |
class ProducerEvent:
timestamp = 0
csvName = ""
houseId = 0
deviceId = 0
id = 0
def __init__(self, timestamp, ids, csv_name):
self.timestamp = int(timestamp)
self.csvName = csv_name
# ids_list = list(map(int, ids.replace("[", "").replace("]", "").replace("pv_producer", "... | class Producerevent:
timestamp = 0
csv_name = ''
house_id = 0
device_id = 0
id = 0
def __init__(self, timestamp, ids, csv_name):
self.timestamp = int(timestamp)
self.csvName = csv_name
ids_list = csv_name.split('_')
self.houseId = int(ids_list[0])
self.de... |
# some mnemonics as specific to capstone
CJMP_INS = ["je", "jne", "js", "jns", "jp", "jnp", "jo", "jno", "jl", "jle", "jg", "jge", "jb", "jbe", "ja", "jae", "jcxz", "jecxz", "jrcxz"]
LOOP_INS = ["loop", "loopne", "loope"]
JMP_INS = ["jmp", "ljmp"]
CALL_INS = ["call", "lcall"]
RET_INS = ["ret", "retn", "retf", "iret"]
... | cjmp_ins = ['je', 'jne', 'js', 'jns', 'jp', 'jnp', 'jo', 'jno', 'jl', 'jle', 'jg', 'jge', 'jb', 'jbe', 'ja', 'jae', 'jcxz', 'jecxz', 'jrcxz']
loop_ins = ['loop', 'loopne', 'loope']
jmp_ins = ['jmp', 'ljmp']
call_ins = ['call', 'lcall']
ret_ins = ['ret', 'retn', 'retf', 'iret']
end_ins = ['ret', 'retn', 'retf', 'iret', ... |
def main():
# input
N = int(input())
# compute
N = int(1.08*N)
# output
if N < 206:
print('Yay!')
elif N == 206:
print('so-so')
else:
print(':(')
if __name__ == '__main__':
main()
| def main():
n = int(input())
n = int(1.08 * N)
if N < 206:
print('Yay!')
elif N == 206:
print('so-so')
else:
print(':(')
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
strings = {
'test.fallback': 'A fallback string'
}
| strings = {'test.fallback': 'A fallback string'} |
def climb_stairs2(n: int) -> int:
if n == 1 or n == 2:
return n
n1 = 1
n2 = 2
t = 0
for i in range(3, n + 1):
t = n1 + n2
n1 = n2
n2 = t
return t
class StairClimber:
# total variable needed for the recursive solution
total = 0
# recursive, mathy w... | def climb_stairs2(n: int) -> int:
if n == 1 or n == 2:
return n
n1 = 1
n2 = 2
t = 0
for i in range(3, n + 1):
t = n1 + n2
n1 = n2
n2 = t
return t
class Stairclimber:
total = 0
def climb_stairs(self, n: int) -> int:
if n == 0:
self.tot... |
#!usr/bin/python
# -*- coding:utf8 -*-
def gen_func():
try:
yield "http://projectesdu.com"
except GeneratorExit:
pass
yield 2
yield 3
return "bobby"
if __name__ == "__main__":
gen = gen_func()
next(gen)
gen.close()
next(gen)
| def gen_func():
try:
yield 'http://projectesdu.com'
except GeneratorExit:
pass
yield 2
yield 3
return 'bobby'
if __name__ == '__main__':
gen = gen_func()
next(gen)
gen.close()
next(gen) |
list_images = [
".jpeg",".jpg",".png",".gif",".webp",".tiff",".psd",".raw",".bmp",".heif",".indd",".svg",".ico"
]
list_documents = [
".doc",".txt",".pdf",".xlsx",".docx",".xls",".rtf",".md",".ods",".ppt",".pptx"
]
list_videos = [
".mp4",".m4v",".f4v",".f4a",".m4b",".m4r",".f4b",".mov",".3gp",
".... | list_images = ['.jpeg', '.jpg', '.png', '.gif', '.webp', '.tiff', '.psd', '.raw', '.bmp', '.heif', '.indd', '.svg', '.ico']
list_documents = ['.doc', '.txt', '.pdf', '.xlsx', '.docx', '.xls', '.rtf', '.md', '.ods', '.ppt', '.pptx']
list_videos = ['.mp4', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '... |
# Least Common Multiple (LCM) Calculator - Burak Karabey
def LCM(x, y):
if x > y:
limit = x
else:
limit = y
prime_numbers = [] # Start of Finding Prime Number
if limit < 2:
return prime_numbers.append(0)
elif limit == 2:
return prime_numbers.append(2)
else:
... | def lcm(x, y):
if x > y:
limit = x
else:
limit = y
prime_numbers = []
if limit < 2:
return prime_numbers.append(0)
elif limit == 2:
return prime_numbers.append(2)
else:
prime_numbers.append(2)
for t in range(3, limit):
find_prime = Fals... |
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
T = int(input())
for _ in range(T):
if... | def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
t = int(input())
for _ in range(T):
if ... |
#!/usr/bin/env python3
sum=0
a=1
while a<=100:
sum +=a
a+=1
print(sum)
| sum = 0
a = 1
while a <= 100:
sum += a
a += 1
print(sum) |
class PositionedObjectError(Exception):
def __init__(self, *args):
super().__init__(*args)
class RelativePositionNotSettableError(PositionedObjectError):
pass
class RelativeXNotSettableError(RelativePositionNotSettableError):
pass
class RelativeYNotSettableError(RelativePositionNotSettableErro... | class Positionedobjecterror(Exception):
def __init__(self, *args):
super().__init__(*args)
class Relativepositionnotsettableerror(PositionedObjectError):
pass
class Relativexnotsettableerror(RelativePositionNotSettableError):
pass
class Relativeynotsettableerror(RelativePositionNotSettableError)... |
# Image types
INTENSITY = 'intensity'
LABEL = 'label'
SAMPLING_MAP = 'sampling_map'
# Keys for dataset samples
PATH = 'path'
TYPE = 'type'
STEM = 'stem'
DATA = 'data'
AFFINE = 'affine'
# For aggregator
IMAGE = 'image'
LOCATION = 'location'
# In PyTorch convention
CHANNELS_DIMENSION = 1
# Code repository
REPO_URL = ... | intensity = 'intensity'
label = 'label'
sampling_map = 'sampling_map'
path = 'path'
type = 'type'
stem = 'stem'
data = 'data'
affine = 'affine'
image = 'image'
location = 'location'
channels_dimension = 1
repo_url = 'https://github.com/fepegar/torchio/'
data_repo = 'https://github.com/fepegar/torchio-data/raw/master/da... |
#!/usr/local/bin/python3
# Copyright 2019 NineFx Inc.
# Justin Baum
# 3 June 2019
# Precis Code-Generator ReasonML
# https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt
fp = open('precis_cp.txt', 'r')
ranges = []
line = fp.readline()
code = "DISALLOWED"
prev = "DISALLOWED"
firstOccurence = 0
co... | fp = open('precis_cp.txt', 'r')
ranges = []
line = fp.readline()
code = 'DISALLOWED'
prev = 'DISALLOWED'
first_occurence = 0
count = 0
while line:
count += 1
line = fp.readline()
if len(line) < 2:
break
linesplit = line.split(';')
codepoint = int(linesplit[0])
code = linesplit[1][:-1]
... |
"""Search filters for ExploreCourses queries"""
# Term offered
AUTUMN = "filter-term-Autumn"
WINTER = "filter-term-Winter"
SPRING = "filter-term-Spring"
SUMMER = "filter-term-Summer"
# Teaching presence
INPERSON = "filter-instructionmode-INPERSON"
ONLINEASYNC = "filter-instructionmode-ONLINEASYNC"
ONLINESYNC = "filte... | """Search filters for ExploreCourses queries"""
autumn = 'filter-term-Autumn'
winter = 'filter-term-Winter'
spring = 'filter-term-Spring'
summer = 'filter-term-Summer'
inperson = 'filter-instructionmode-INPERSON'
onlineasync = 'filter-instructionmode-ONLINEASYNC'
onlinesync = 'filter-instructionmode-ONLINESYNC'
remotea... |
# https://leetcode.com/problems/unique-morse-code-words/
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
dictx = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.",
"h": "....", "i": "..", "j": ".---", "k": "-... | class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
dictx = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.',... |
class BadBatchRequestException(Exception):
def __init__(self, org, repo, message=None):
super()
self.org = org
self.repo = repo
self.message = message
class UnknownBatchOperationException(Exception):
def __init__(self, org, repo, operation, message=None):
super()
... | class Badbatchrequestexception(Exception):
def __init__(self, org, repo, message=None):
super()
self.org = org
self.repo = repo
self.message = message
class Unknownbatchoperationexception(Exception):
def __init__(self, org, repo, operation, message=None):
super()
... |
class Agent:
def __init__(self, name):
self.name = name
def reset(self, state):
# Completely resets the state of the Agent for a new game
return
def make_action(self, state):
# Returns a valid move in (row, column) format where 0 <= row, column < board_len
move = (0, 0)
return move
def u... | class Agent:
def __init__(self, name):
self.name = name
def reset(self, state):
return
def make_action(self, state):
move = (0, 0)
return move
def update_state(self, move):
return
@staticmethod
def get_params():
return () |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=c=0;r=[]
for x in map(int,[*open(0)][1].split()):
if x<0:
if n==2:
r+=[c]
n=1
c=0
else:n+=1
c+=1
r+=[c]
print(len(r))
print(*r) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n = c = 0
r = []
for x in map(int, [*open(0)][1].split()):
if x < 0:
if n == 2:
r += [c]
n = 1
c = 0
else:
n += 1
c += 1
r += [c]
print(len(r))
print(*r) |
#
# PySNMP MIB module ONEACCESS-SYS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SYS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class GitCommandError(Exception):
""" Exception which can be raised when git exits with a non-zero exit code.
"""
pass
class InvalidUpgradePath(Exception):
"""
Exception which is thrown if an invalid upgrade path is detected. This
is usually when... | class Gitcommanderror(Exception):
""" Exception which can be raised when git exits with a non-zero exit code.
"""
pass
class Invalidupgradepath(Exception):
"""
Exception which is thrown if an invalid upgrade path is detected. This
is usually when attempting to upgrade to a version before the on... |
TOKEN = b'd4r3d3v!l'
def chall():
s = Sign()
while True:
choice = input("> ").rstrip()
if choice == 'P':
print("\nN : {}".format(hex(s.n)))
print("\ne : {}".format(hex(s.e)))
elif choice == 'S':
try:
msg = bytes.fromhex(input('msg to si... | token = b'd4r3d3v!l'
def chall():
s = sign()
while True:
choice = input('> ').rstrip()
if choice == 'P':
print('\nN : {}'.format(hex(s.n)))
print('\ne : {}'.format(hex(s.e)))
elif choice == 'S':
try:
msg = bytes.fromhex(input('msg to s... |
# Python Class 2406
# Lesson 12 Problem 1
# Author: snowapple (471208)
class Game:
def __init__(self, n):
'''__init__(n) -> Game
creates an instance of the Game class'''
if n% 2 == 0: #n has to be odd
print('Please enter an odd n!')
raise ValueError
self.n ... | class Game:
def __init__(self, n):
"""__init__(n) -> Game
creates an instance of the Game class"""
if n % 2 == 0:
print('Please enter an odd n!')
raise ValueError
self.n = n
self.board = [[0 for x in range(self.n)] for x in range(self.n)]
self... |
""" Challenge - Program Flow
# TODO: Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop.
But your program should just count however many ar... | """ Challenge - Program Flow
# TODO: Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop.
But your program should just count however many ar... |
def BFS(graph,root,p1,max1):
checked = []
visited=[]
energy=[]
level=[]
l=[]
l.append(root)
level.append(l)
checked.append(root)
inienergy=14600
threshold=10
l1=0
flag=0
energy.append(inienergy)
while(len(checked)>0):
l1=l1+1
#print... | def bfs(graph, root, p1, max1):
checked = []
visited = []
energy = []
level = []
l = []
l.append(root)
level.append(l)
checked.append(root)
inienergy = 14600
threshold = 10
l1 = 0
flag = 0
energy.append(inienergy)
while len(checked) > 0:
l1 = l1 + 1
... |
s="this this is a a cat cat cat ram ram jai it"
l=[]
count=[]
i=0
#j=0
str=""
for i in s:
#print(i,end="")
if i==" ":
if str in l:
for j in range(len(l)):
if str == l[j]:
count[j] += 1
str=""
continue
else:
... | s = 'this this is a a cat cat cat ram ram jai it'
l = []
count = []
i = 0
str = ''
for i in s:
if i == ' ':
if str in l:
for j in range(len(l)):
if str == l[j]:
count[j] += 1
str = ''
continue
else:
l... |
class LRUCache:
def __init__(self, capacity: int):
self.db = dict()
self.capacity = capacity
self.time = 0
def get(self, key: int) -> int:
if key in self.db:
self.db[key][1] = self.time
self.time += 1
return self.db[key][0]
else:
... | class Lrucache:
def __init__(self, capacity: int):
self.db = dict()
self.capacity = capacity
self.time = 0
def get(self, key: int) -> int:
if key in self.db:
self.db[key][1] = self.time
self.time += 1
return self.db[key][0]
else:
... |
# 2021.04.14
# Problem Statement:
# https://leetcode.com/problems/majority-element/
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# trivial question, no need to explain
if len(nums) == 1: return nums[0]
dict = {}
for element in nums:
if element not i... | class Solution:
def majority_element(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dict = {}
for element in nums:
if element not in dict.keys():
dict[element] = 1
else:
dict[element] = dict[element] + 1
... |
def ParseGraphVertexEdge(file):
with open(file, 'r') as fw:
read_data = fw.read()
res = read_data.splitlines(False)
def ParseV(v_str):
'''
@type v_str: string
:param v_str:
:return:
'''
return [int(i) for i... | def parse_graph_vertex_edge(file):
with open(file, 'r') as fw:
read_data = fw.read()
res = read_data.splitlines(False)
def parse_v(v_str):
"""
@type v_str: string
:param v_str:
:return:
"""
return [int(i) for i in v_str... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 13:54:22 2018
@author: David
"""
mainmenu = ["1:Add a new item ", "2:Move an item", "3:search an item",
"4:view the inventory of a warehouse", "0: exit the system"]
def menu():
# display a main menu
for i in mainmenu:
print(... | """
Created on Sat Nov 3 13:54:22 2018
@author: David
"""
mainmenu = ['1:Add a new item ', '2:Move an item', '3:search an item', '4:view the inventory of a warehouse', '0: exit the system']
def menu():
for i in mainmenu:
print(i)
c = input('please choose a number or press any other key to return:')
... |
"""Tools to manage census tables."""
POSTGRES_COLUMN_NAME_LIMIT = 63
def _verified_column_name(column_name, limit=POSTGRES_COLUMN_NAME_LIMIT):
if len(column_name) > limit:
raise Exception('Column name {} is too long. Postgres limit is {}.'.format(
column_name, limit))
return column_name
... | """Tools to manage census tables."""
postgres_column_name_limit = 63
def _verified_column_name(column_name, limit=POSTGRES_COLUMN_NAME_LIMIT):
if len(column_name) > limit:
raise exception('Column name {} is too long. Postgres limit is {}.'.format(column_name, limit))
return column_name
def readable_co... |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n = len(nums1)
m = len(nums2)
if (n > m):
return self.findMedianSortedArrays(nums2, nums1)
start = 0
end = n
realmidinmergedarray = (n + m + 1) // 2
wh... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
n = len(nums1)
m = len(nums2)
if n > m:
return self.findMedianSortedArrays(nums2, nums1)
start = 0
end = n
realmidinmergedarray = (n + m + 1) // 2
wh... |
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27]
data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14]
hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22]
med_temp_techs = [3, 4, 5, 9, 10, 11]
low_temp_techs = [24, 25]
no_imput_rows_color = [232, 232, 232] | data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27]
data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14]
hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22]
med_temp_techs = [3, 4, 5, 9, 10, 11]
low_temp_techs = [24, 25]
no_imput_rows_color = [232, 232, 232] |
def letter_counter(token, word):
count = 0
for letter in word:
if letter == token:
count = count + 1
else:
continue
return count
| def letter_counter(token, word):
count = 0
for letter in word:
if letter == token:
count = count + 1
else:
continue
return count |
class ExceptionBase(Exception):
"""Base exception."""
message: str
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class InvalidPduState(ExceptionBase):
"""Thrown during PDU self-validation."""
def __init__(self, message: str, pdu) -> N... | class Exceptionbase(Exception):
"""Base exception."""
message: str
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class Invalidpdustate(ExceptionBase):
"""Thrown during PDU self-validation."""
def __init__(self, message: str, pdu) -> Non... |
@React.command()
async def redirect(ctx, *, url):
await ctx.message.delete()
try:
embed = discord.Embed(color=int(json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker')
embed.set_thumbnail(url=json.load(open(f'... | @React.command()
async def redirect(ctx, *, url):
await ctx.message.delete()
try:
embed = discord.Embed(color=int(json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker')
embed.set_thumbnail(url=json.load(open(f"... |
arq_entrada = open("FORMAT.FLC", 'r')
conjunto_entradas = \
{'SISTEMA FUZZY': '',
'CONJUNTO FUZZY': '',
'GRANULARIDADE': 3,
'OPERADOR COMPOSICAO': '',
'OPERADOR AGREGACAO': '',
'INFERENCIA': '',
'REGRA': False,
'DEFAULT': ''}
for linha in arq_entrada.readlines():
#print(linha)
variavel = linha.split(':')[0]
... | arq_entrada = open('FORMAT.FLC', 'r')
conjunto_entradas = {'SISTEMA FUZZY': '', 'CONJUNTO FUZZY': '', 'GRANULARIDADE': 3, 'OPERADOR COMPOSICAO': '', 'OPERADOR AGREGACAO': '', 'INFERENCIA': '', 'REGRA': False, 'DEFAULT': ''}
for linha in arq_entrada.readlines():
variavel = linha.split(':')[0]
valor = linha.split... |
num = 1
num = 2
num = 3
num = 4
num = 5
| num = 1
num = 2
num = 3
num = 4
num = 5 |
# The MIT License (MIT)
#
# Copyright (c) 2016 Adam Schubert
#
# 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, mod... | class Missingfieldexception(Exception):
"""
Exception for cases when something is missing
"""
def __init__(self, message):
"""Initialize MissingFieldException
Args:
message: Message of exception
"""
super(MissingFieldException, self).__init__("Field '{}' no... |
class Parser:
def __init__(self, file_path):
self.dottedproductions = {'S\'': [['.', 'S']]}
file_program = self.read_program(file_path)
self.terminals = file_program[0]
self.nonTerminals = file_program[1]
self.productions = {}
self.transactions = file_program[2:]
... | class Parser:
def __init__(self, file_path):
self.dottedproductions = {"S'": [['.', 'S']]}
file_program = self.read_program(file_path)
self.terminals = file_program[0]
self.nonTerminals = file_program[1]
self.productions = {}
self.transactions = file_program[2:]
... |
class instancemethod(object):
def __init__(self, func):
self._func = func
def __get__(self, obj, type_=None):
return lambda *args, **kwargs: self._func(obj, *args, **kwargs)
class Func(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
return self, args, kwargs
class A(object):
... | class Instancemethod(object):
def __init__(self, func):
self._func = func
def __get__(self, obj, type_=None):
return lambda *args, **kwargs: self._func(obj, *args, **kwargs)
class Func(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
return (sel... |
#!/usr/bin/env python
# https://adventofcode.com/2020/day/1
# Topic: Report repair
my_list = []
with open("../data/1.puzzle.txt") as fp:
Lines = fp.readlines()
for line in Lines:
my_list.append(int(line))
my_list.sort()
num1 = 0
num2 = 0
for idx, x in enumerate(my_list):
for y in range(0, len(my_list) - id... | my_list = []
with open('../data/1.puzzle.txt') as fp:
lines = fp.readlines()
for line in Lines:
my_list.append(int(line))
my_list.sort()
num1 = 0
num2 = 0
for (idx, x) in enumerate(my_list):
for y in range(0, len(my_list) - idx):
if x + my_list[len(my_list) - 1 - y] == 2020:
num1... |
class MasterConfig:
def __init__(self, args):
self.IP = args.ip
self.PORT = args.port
self.PERSISTENCE_DIR = args.persistence_dir
self.SENDER_QUEUE_LENGTH = args.sender_queue_length
self.SENDER_TIMEOUT = args.sender_timeout
self.UI_PORT = args.ui_port
self.CPU... | class Masterconfig:
def __init__(self, args):
self.IP = args.ip
self.PORT = args.port
self.PERSISTENCE_DIR = args.persistence_dir
self.SENDER_QUEUE_LENGTH = args.sender_queue_length
self.SENDER_TIMEOUT = args.sender_timeout
self.UI_PORT = args.ui_port
self.CP... |
'''knot> pytest tests '''
def test_noting():
assert True
| """knot> pytest tests """
def test_noting():
assert True |
#********************************************************************
# Filename: SingletonPattern_With.Metaclass.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the singleton pattern.
#************************************************... | class Metasingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
pass
if __name__ == '__main__... |
"""
Purpose:
File for holding custom exception types that will be generated by the
kafka_helpers libraries
"""
###
# Consumer Exceptions
###
class TopicNotFound(Exception):
"""
Purpose:
The TopicNotFound will be raised when attempting to consume a topic that
does not exis... | """
Purpose:
File for holding custom exception types that will be generated by the
kafka_helpers libraries
"""
class Topicnotfound(Exception):
"""
Purpose:
The TopicNotFound will be raised when attempting to consume a topic that
does not exist
"""
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.