content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 04:40:43 2020
@author: Abhishek Mukherjee
"""
class Solution:
def decodeString(self, s: str) -> str:
tempNum=[]
tempAlpha=[]
tempPrime=[]
temp3=[]
flagPrime=1
tempNum1=""
for i in s:
... | """
Created on Thu Aug 27 04:40:43 2020
@author: Abhishek Mukherjee
"""
class Solution:
def decode_string(self, s: str) -> str:
temp_num = []
temp_alpha = []
temp_prime = []
temp3 = []
flag_prime = 1
temp_num1 = ''
for i in s:
if i.isdigit() and... |
def process_blok(x0_x1_y0_y1_z0_z1_):
x0_, x1_, y0_, y1_, z0_, z1_ = x0_x1_y0_y1_z0_z1_
print('Setting number of threads in process_blok to %d.\n' %nthread)
os.environ['MKL_NUM_THREADS'] = str(nthread)
# load and dilate initial voxel peak positions
voxl_peaklidx_blok = np.zeros_like(bimag... | def process_blok(x0_x1_y0_y1_z0_z1_):
(x0_, x1_, y0_, y1_, z0_, z1_) = x0_x1_y0_y1_z0_z1_
print('Setting number of threads in process_blok to %d.\n' % nthread)
os.environ['MKL_NUM_THREADS'] = str(nthread)
voxl_peaklidx_blok = np.zeros_like(bimage_peak_fine.value)
voxl_peaklidx_blok[x0_:x1_, y0_:y1_,... |
def defaultify(value,default):
"""Return `default` if `value` is `None`. Otherwise, return `value`"""
if None == value:
return default
else:
return value
def defaultifyDict(dictionary,key,default):
"""Return `default` if either `key` is not in `dictionary`, or `dictionary[key]` is `None... | def defaultify(value, default):
"""Return `default` if `value` is `None`. Otherwise, return `value`"""
if None == value:
return default
else:
return value
def defaultify_dict(dictionary, key, default):
"""Return `default` if either `key` is not in `dictionary`, or `dictionary[key]` is `... |
add_library('video')
c=None
w=640.0
h=480.0
darkmode=False
def setup():
global c,cx,cy
size(640,480)
background(0 if darkmode else 255)
stroke(23,202,230)
imageMode(CENTER)
c=Capture(this,640,480)
c.start();
def genart():
line(dx,cy-h/2,dx,cy+h/2)
def draw():
cx=width/2
cy=he... | add_library('video')
c = None
w = 640.0
h = 480.0
darkmode = False
def setup():
global c, cx, cy
size(640, 480)
background(0 if darkmode else 255)
stroke(23, 202, 230)
image_mode(CENTER)
c = capture(this, 640, 480)
c.start()
def genart():
line(dx, cy - h / 2, dx, cy + h / 2)
def draw(... |
#
# PySNMP MIB module CLNS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CLNS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
VERSION = (0, 2, 2, '', 1)
if VERSION[3] and VERSION[4]:
VERSION_TEXT = '{0}.{1}.{2}{3}{4}'.format(*VERSION)
else:
VERSION_TEXT = '{0}.{1}.{2}'.format(*VERSION[0:3])
VERSION_EXTRA = ''
LICENSE = 'MIT License'
| version = (0, 2, 2, '', 1)
if VERSION[3] and VERSION[4]:
version_text = '{0}.{1}.{2}{3}{4}'.format(*VERSION)
else:
version_text = '{0}.{1}.{2}'.format(*VERSION[0:3])
version_extra = ''
license = 'MIT License' |
def selection_sort(array):
"""Program for selection sort
Inplace sorting
Space Complexity O(1) only constant number of variables is used
Time complexity O(n^2)
>>> arr = [1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> print(arr)
[1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> selection_sort(arr)
>>> print... | def selection_sort(array):
"""Program for selection sort
Inplace sorting
Space Complexity O(1) only constant number of variables is used
Time complexity O(n^2)
>>> arr = [1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> print(arr)
[1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> selection_sort(arr)
>>> print... |
#NOTE: LIST - Secuence of mutable values
names = ["Harry", "Hik", "Linkin", "Park"]
#ADDS ANOTHER ITEM IN THE LIST
names.append("Paramore")
#SORT THE LIST IN APLHABETIC ORDER
names.sort()
#PRINTS THE LIST
print(names) | names = ['Harry', 'Hik', 'Linkin', 'Park']
names.append('Paramore')
names.sort()
print(names) |
subor = open("17_1input.txt", "r")
r = [x.strip() for x in subor.readlines()]
n=6
roz=(n+1)*2+len(r[0])
pole=[[["." for a in range(roz)] for a in range(roz)]for a in range((n+1)*2+1)]
#vypisanie pola
def vypis(x):
for a in x:
for b in a:
for c in b:
print(c,end=" ")
... | subor = open('17_1input.txt', 'r')
r = [x.strip() for x in subor.readlines()]
n = 6
roz = (n + 1) * 2 + len(r[0])
pole = [[['.' for a in range(roz)] for a in range(roz)] for a in range((n + 1) * 2 + 1)]
def vypis(x):
for a in x:
for b in a:
for c in b:
print(c, end=' ')
... |
__author__ = "Ian Goodfellow"
class Agent(object):
pass
| __author__ = 'Ian Goodfellow'
class Agent(object):
pass |
def pytest_report_header():
return """
------------------------
EXECUTING WEB UI TESTS
------------------------
"""
| def pytest_report_header():
return '\n ------------------------\n EXECUTING WEB UI TESTS\n ------------------------\n ' |
c = 41 # THE VARIABLE C equals 41
c == 40 # c eqauls 40 which is false becasue of the variable above
c != 40 and c <41 #c does not equal 40 is a true statement but the other statement is false, making it a false statement
c != 40 or c <41 #True statement in an or statement
not c == 40 #this is a true statement
not c > ... | c = 41
c == 40
c != 40 and c < 41
c != 40 or c < 41
not c == 40
not c > 40
c <= 41
not false
True and false
false or True
false or false or false
True and True and false
false == 0
True == 0
True == 1 |
dna = 'ACGTN'
rna = 'ACGUN'
# dictionary nucleotide acronym to full name
nuc2name = {
'A': 'Adenosine',
'C': 'Cysteine',
'T': 'Thymine',
'G': 'Guanine',
'U': 'Uracil',
'N': 'Unknown'
} | dna = 'ACGTN'
rna = 'ACGUN'
nuc2name = {'A': 'Adenosine', 'C': 'Cysteine', 'T': 'Thymine', 'G': 'Guanine', 'U': 'Uracil', 'N': 'Unknown'} |
print("Checking Imports")
import_list = ['signal', 'psutil', 'time', 'pypresence', 'random']
modules = {}
for package in import_list:
try:
modules[package] = __import__(package)
except ImportError:
print(f"Package: {package} is missing please install")
print("Loading CONFIG\n")
# # # # # # # # ... | print('Checking Imports')
import_list = ['signal', 'psutil', 'time', 'pypresence', 'random']
modules = {}
for package in import_list:
try:
modules[package] = __import__(package)
except ImportError:
print(f'Package: {package} is missing please install')
print('Loading CONFIG\n')
client_id = '8089... |
# A linked list node
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
# Helper function to print given linked list
def printList(head):
ptr = head
while ptr:
print(ptr.value, end=" -> ")
ptr = ptr.next
print("None")
# Function to remove duplicates from a sorted... | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def print_list(head):
ptr = head
while ptr:
print(ptr.value, end=' -> ')
ptr = ptr.next
print('None')
def remove_duplicates(head):
previous = None
current = head
s = ... |
#!/usr/bin/env python3
# https://www.urionlinejudge.com.br/judge/en/problems/view/1014
def main():
X = int(input())
Y = float(input())
CONSUMPTION = X / Y
print(format(CONSUMPTION, '.3f'), "km/l")
# Start the execution if it's the main script
if __name__ == "__main__":
main()
| def main():
x = int(input())
y = float(input())
consumption = X / Y
print(format(CONSUMPTION, '.3f'), 'km/l')
if __name__ == '__main__':
main() |
'''
Data Columns - Exercise 1
The file reads the file with neuron lengths (neuron_data.txt)
and saves an identical copy of the file.
'''
Infile = open('neuron_data.txt')
Outfile = open('neuron_data-copy.txt', 'w')
for line in Infile:
Outfile.write(line)
Outfile.close()
| """
Data Columns - Exercise 1
The file reads the file with neuron lengths (neuron_data.txt)
and saves an identical copy of the file.
"""
infile = open('neuron_data.txt')
outfile = open('neuron_data-copy.txt', 'w')
for line in Infile:
Outfile.write(line)
Outfile.close() |
"""In this bite you will work with a list of names.
First you will write a function to take out duplicates and title case them.
Then you will sort the list in alphabetical descending order by surname and lastly determine what the shortest first name is. For this exercise you can assume there is always one name and on... | """In this bite you will work with a list of names.
First you will write a function to take out duplicates and title case them.
Then you will sort the list in alphabetical descending order by surname and lastly determine what the shortest first name is. For this exercise you can assume there is always one name and on... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your... | """*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
class Video:
def __init__(self, files):
self.files = files
def setFiles(self, files):
self.files = files
def getFiles(self):
return self.files | class Video:
def __init__(self, files):
self.files = files
def set_files(self, files):
self.files = files
def get_files(self):
return self.files |
class JsonUtil:
@staticmethod
def list_obj_dict(list):
new_list = []
for obj in list:
new_list.append(obj.__dict__)
return new_list
| class Jsonutil:
@staticmethod
def list_obj_dict(list):
new_list = []
for obj in list:
new_list.append(obj.__dict__)
return new_list |
# pylint: disable=inconsistent-return-statements
def sanitize(value, output_type):
"""
Handy wrapper function for individual sanitize functions.
:param value: Input value to be sanitized
:param output_type: Class of required output
:type output_type: bool or int
"""
# pylint: disable=no-e... | def sanitize(value, output_type):
"""
Handy wrapper function for individual sanitize functions.
:param value: Input value to be sanitized
:param output_type: Class of required output
:type output_type: bool or int
"""
if output_type == bool:
return sanitize_bool(value)
elif outp... |
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
start = 0
end = len(arr) - 1
while start < end:
mid = (start + end) // 2
if arr[m... | class Solution(object):
def find_closest_elements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
start = 0
end = len(arr) - 1
while start < end:
mid = (start + end) // 2
if ar... |
# 1
x = float(input("First number: "))
y = float(input("Second number: "))
if x > y:
print(f"{x} is greater than {y}")
elif x < y:
print(f"{x} is less than {y}")
else:
print(f"{x} is equal to {y}")
# bb
quiz = float(input("quiz: "))
mid_term = float(input("midterm: "))
final = float(input("final: "))
avg ... | x = float(input('First number: '))
y = float(input('Second number: '))
if x > y:
print(f'{x} is greater than {y}')
elif x < y:
print(f'{x} is less than {y}')
else:
print(f'{x} is equal to {y}')
quiz = float(input('quiz: '))
mid_term = float(input('midterm: '))
final = float(input('final: '))
avg = (quiz + m... |
x = {}
print(type(x))
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
print(file_counts)
print(file_counts["txt"])
print("html" in file_counts) #true if found
#dictionaries are mutable
file_counts["cfg"] = 8 #add item
print(file_counts)
file_counts["csv"] = 17 #replaces value for already assigned csv
print... | x = {}
print(type(x))
file_counts = {'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23}
print(file_counts)
print(file_counts['txt'])
print('html' in file_counts)
file_counts['cfg'] = 8
print(file_counts)
file_counts['csv'] = 17
print(file_counts)
del file_counts['cfg']
print(file_counts)
file_counts = {'jpg': 10, 'txt': 14, 'cs... |
# Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
| def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list)) |
'''
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity
'''
class Solution:
def searchRange(self, nums: List[int], target... | """
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity
"""
class Solution:
def search_range(self, nums: List[int], targe... |
def knapsack(limit, values, weights):
"""Returns the maximum value that can be reached using given weights"""
n = len(weights)
dp = [0]*(limit+1)
for i in range(n):
for j in range(limit, weights[i]-1, -1):
dp[j] = max(dp[j], values[i] + dp[j - weights[i]])
return dp[-1] | def knapsack(limit, values, weights):
"""Returns the maximum value that can be reached using given weights"""
n = len(weights)
dp = [0] * (limit + 1)
for i in range(n):
for j in range(limit, weights[i] - 1, -1):
dp[j] = max(dp[j], values[i] + dp[j - weights[i]])
return dp[-1] |
_base_ = [
'../_base_/models/resnet50.py', '../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs256.py', '../_base_/default_runtime.py'
]
load_from = "https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth" | _base_ = ['../_base_/models/resnet50.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs256.py', '../_base_/default_runtime.py']
load_from = 'https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth' |
x = int(input("Please enter a number: "))
if x % 2 == 0 :
print(x, "is even")
else :
print(x, "is odd")
| x = int(input('Please enter a number: '))
if x % 2 == 0:
print(x, 'is even')
else:
print(x, 'is odd') |
class Memoization:
allow_attr_memoization = False
def _set_attr(obj, attr_name, value_func):
setattr(obj, attr_name, value_func())
return getattr(obj, attr_name)
def _memoize_attr(obj, attr_name, value_func):
if not Memoization.allow_attr_memoization:
return value_func()
try:
return getattr(obj, a... | class Memoization:
allow_attr_memoization = False
def _set_attr(obj, attr_name, value_func):
setattr(obj, attr_name, value_func())
return getattr(obj, attr_name)
def _memoize_attr(obj, attr_name, value_func):
if not Memoization.allow_attr_memoization:
return value_func()
try:
retur... |
class BotConfiguration(object):
def __init__(self, auth_token, name, avatar):
self._auth_token = auth_token
self._name = name
self._avatar = avatar
@property
def name(self):
return self._name
@property
def avatar(self):
return self._avatar
@property
def auth_token(self):
return self._auth_token
| class Botconfiguration(object):
def __init__(self, auth_token, name, avatar):
self._auth_token = auth_token
self._name = name
self._avatar = avatar
@property
def name(self):
return self._name
@property
def avatar(self):
return self._avatar
@property
... |
#author SANKALP SAXENA
# Complete the has_cycle function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def has_cycle(head):
s = set()
temp = head
while True:
if temp.next == None:
return False
if temp.next not i... | def has_cycle(head):
s = set()
temp = head
while True:
if temp.next == None:
return False
if temp.next not in s:
s.add(temp.next)
else:
return True
temp = temp.next
return False |
{
'targets': [
{
'target_name': 'test_new_target',
'defines': [ 'V8_DEPRECATION_WARNINGS=1' ],
'sources': [
'../entry_point.c',
'test_new_target.c'
]
}
]
}
| {'targets': [{'target_name': 'test_new_target', 'defines': ['V8_DEPRECATION_WARNINGS=1'], 'sources': ['../entry_point.c', 'test_new_target.c']}]} |
x = 10
print(x)
"""
tests here
""" | x = 10
print(x)
'\ntests here\n' |
usa = ['atlanta','new york','chicago','baltimore']
uk = ['london','bristol','cambridge']
india = ['mumbai','delhi','banglore']
'''
#(a)
i=input("Enter city name: ")
if i in usa:
print('city is in USA')
elif i in uk:
print('city is in UK')
elif i in india:
print('city is in INDIA')
else:
print('idk the ... | usa = ['atlanta', 'new york', 'chicago', 'baltimore']
uk = ['london', 'bristol', 'cambridge']
india = ['mumbai', 'delhi', 'banglore']
'\n#(a)\ni=input("Enter city name: ")\nif i in usa:\n print(\'city is in USA\')\nelif i in uk:\n print(\'city is in UK\')\nelif i in india:\n print(\'city is in INDIA\')\nelse:\... |
#Base Class, Uses a descriptor to set a value
class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr( self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
#Descriptor for enforci... | class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for (key, value) in opts.items():
setattr(self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
class Typed(Descriptor):
expected_type = type(None)
def _... |
{
"targets": [
{
"target_name": "napi_test",
"sources": [ "napi.test.c" ]
},
{
"target_name": "napi_arguments",
"sources": [ "napi_arguments.c" ]
},
{
"target_name": "napi_async",
"sources": [ "napi_async.cc" ]
},
{
"target_name": "napi_construct",... | {'targets': [{'target_name': 'napi_test', 'sources': ['napi.test.c']}, {'target_name': 'napi_arguments', 'sources': ['napi_arguments.c']}, {'target_name': 'napi_async', 'sources': ['napi_async.cc']}, {'target_name': 'napi_construct', 'sources': ['napi_construct.c']}, {'target_name': 'napi_error', 'sources': ['napi_erro... |
__title__ = 'Django Platform Data Service'
__version__ = '0.0.4'
__author__ = 'Komol Nath Roy'
__license__ = 'MIT'
__copyright__ = 'Copyright 2020 Komol Nath Roy'
VERSION = __version__
default_app_config = 'django_pds.apps.DjangoPdsConfig'
| __title__ = 'Django Platform Data Service'
__version__ = '0.0.4'
__author__ = 'Komol Nath Roy'
__license__ = 'MIT'
__copyright__ = 'Copyright 2020 Komol Nath Roy'
version = __version__
default_app_config = 'django_pds.apps.DjangoPdsConfig' |
#!C:\Python27
# For 500,000 mutables, this takes WAY to long. Look for better options
orgFile = open('InputList.txt', 'r')
newFile = open('SortedList.txt', 'w')
unsortedList = [line.strip() for line in orgFile]
def bubble_sort(list):
for i in reversed(range(len(list))):
finished = True
... | org_file = open('InputList.txt', 'r')
new_file = open('SortedList.txt', 'w')
unsorted_list = [line.strip() for line in orgFile]
def bubble_sort(list):
for i in reversed(range(len(list))):
finished = True
for j in range(i):
if list[j] > list[j + 1]:
(list[j], list[j + 1])... |
students = []
def displayMenu():
print("What would you like to do?")
print("\t(a) Add new student: ")
print("\t(v) View students: ")
print("\t(q) Quit: ")
choice = input("Type one letter (a/v/q): ").strip()
return choice
#test the function
def doAdd():
currentstudent = {}
currentstude... | students = []
def display_menu():
print('What would you like to do?')
print('\t(a) Add new student: ')
print('\t(v) View students: ')
print('\t(q) Quit: ')
choice = input('Type one letter (a/v/q): ').strip()
return choice
def do_add():
currentstudent = {}
currentstudent['name'] = input... |
def collect(items, item):
if item in collecting_items:
return
collecting_items.append(item)
return
def drop(items, item):
if item in collecting_items:
collecting_items.remove(item)
return
return
def combine_items(old, new):
if old in collecting_items:
for el i... | def collect(items, item):
if item in collecting_items:
return
collecting_items.append(item)
return
def drop(items, item):
if item in collecting_items:
collecting_items.remove(item)
return
return
def combine_items(old, new):
if old in collecting_items:
for el in ... |
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '... | secret_key = ''
databases = {'default': {'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}}
jobs_new_threshold = 1
jobs_notification_list = []
gatekeeper_enable_automoderation = True
gatekeeper_default_status = 0
gatekeeper_moderator_list = JOBS_NOTIFICATION_LIST |
#* Asked by Facebook
#? Given a list of sorted numbers, build a list of strings displaying numbers,
#? Where each string is first and last number of linearly increasing numbers.
#! Example:
#? Input: [0,1,2,2,5,7,8,9,9,10,11,15]
#? Output: ['0 -> 2','5 -> 5','7 -> 11','15 -> 15']
#! Note that numbers will not be l... | def truncate_list(lst):
if len(lst) == 0:
return list()
num = lst[0]
next_num = num + 1
start_num = num
final_lst = list()
i = 1
while i < len(lst):
if lst[i] == num or lst[i] == next_num:
pass
else:
final_lst.append(f'{start_num} -> {num}')
... |
# Copyright (c) 2018-2019 Arizona Board of Regents
#
# 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 ... | class Figsize(object):
"""Helper to compute the size of matplotlib figures.
The idea is to perform conversion between absolute margin sizes (and spacing between rows and columns
in case of multiple subplots) and their corresponding relative that are needed for matplotlib.
Additionnally, there is the possibilit... |
#!/usr/bin/env python3
"""
Advent of Code 2018
Puzzle #2 - 2018-12-02: Find two strings with hamming distance of one
# https://adventofcode.com/2018/day/2
Input (via stdin): A series of strings. e.g.:
abcdef
hijklm
uvwxyz
azcdef
Output: One of two strings that differ by exactly one character, with the matching char... | """
Advent of Code 2018
Puzzle #2 - 2018-12-02: Find two strings with hamming distance of one
# https://adventofcode.com/2018/day/2
Input (via stdin): A series of strings. e.g.:
abcdef
hijklm
uvwxyz
azcdef
Output: One of two strings that differ by exactly one character, with the matching character excluded. e.g.:
ac... |
"""
Navigation provides the basic functionality of a page navigation
to navigate between sites
"""
class Navigation:
TEMPLATE = 'nav.j2'
def __init__(self, env, pages):
self._env = env
self._pages = pages
def render(self, name, current_page, tpl_file=None):
if tpl_file i... | """
Navigation provides the basic functionality of a page navigation
to navigate between sites
"""
class Navigation:
template = 'nav.j2'
def __init__(self, env, pages):
self._env = env
self._pages = pages
def render(self, name, current_page, tpl_file=None):
if tpl_file is ... |
expected_output = {
"session_type": {
"AnyConnect": {
"username": {
"lee": {
"index": {
1: {
"assigned_ip": "192.168.246.1",
"bytes": {"rx": 4942, "tx": 11079},
... | expected_output = {'session_type': {'AnyConnect': {'username': {'lee': {'index': {1: {'assigned_ip': '192.168.246.1', 'bytes': {'rx': 4942, 'tx': 11079}, 'duration': '0h:00m:15s', 'encryption': 'RC4 AES128', 'group_policy': 'EngPolicy', 'hashing': 'SHA1', 'inactivity': '0h:00m:00s', 'license': 'AnyConnect Premium', 'lo... |
"""
@name: Modules/House/Lighting/Lights/__init__.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2020-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Feb 5, 2020
"""
__updated__ = '2020-02-09'
__version_info__ = (20, 2, 9)
__version__ = '.'.join(map(str... | """
@name: Modules/House/Lighting/Lights/__init__.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2020-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Feb 5, 2020
"""
__updated__ = '2020-02-09'
__version_info__ = (20, 2, 9)
__version__ = '.'.join(map(str,... |
"""
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Not... | """
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Not... |
"""
A pytest plugin for testing Tornado apps using plain (undecorated) coroutine tests.
"""
__version_info__ = (0, 6, 0, 'post2')
__version__ = '.'.join(map(str, __version_info__))
| """
A pytest plugin for testing Tornado apps using plain (undecorated) coroutine tests.
"""
__version_info__ = (0, 6, 0, 'post2')
__version__ = '.'.join(map(str, __version_info__)) |
class XtbOutputParser:
"""Class for parsing xtb output"""
def __init__(self, output):
self.output = output
self.lines = output.split('\n')
def parse(self):
# output variable
xtb_output_data = {}
# go through lines to find targets
for i in... | class Xtboutputparser:
"""Class for parsing xtb output"""
def __init__(self, output):
self.output = output
self.lines = output.split('\n')
def parse(self):
xtb_output_data = {}
for i in range(len(self.lines)):
if 'HOMO-LUMO GAP' in self.lines[i]:
... |
# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de>
class MovingAverage:
postfix = "avg"
def __init__(self):
self.sum = 0.0
self.count = 0
def add_value(self, sigma, addcount=1):
self.sum += sigma
self.count += addcount
def add_average(self, avg, addcount):
... | class Movingaverage:
postfix = 'avg'
def __init__(self):
self.sum = 0.0
self.count = 0
def add_value(self, sigma, addcount=1):
self.sum += sigma
self.count += addcount
def add_average(self, avg, addcount):
self.sum += avg * addcount
self.count += addcou... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/2/25 15:45
# @Author : Vodka0629
# @Email : 563511@qq.com, ZhangXiangming@gmail.com
# @FileName: mj_value.py
# @Software: Mahjong II
# @Blog :
class MjValue(object):
__slots__ = ("meld", "orphan",
"is_ready", "listening", "mahj... | class Mjvalue(object):
__slots__ = ('meld', 'orphan', 'is_ready', 'listening', 'mahjong_chance', 'count_down', 'waiting', 'waiting_chance')
def __init__(self, meld: int=0, orphan: int=0, is_ready: bool=False, listening=None, mahjong_chance=0, count_down: int=0, waiting=None, waiting_chance=0):
self.mel... |
ejem = "esto es un ejemplo"
print (ejem)
print (ejem[8:18], ejem[5:7], ejem[0:4])
subejem = ejem[8:18] + ejem[4:8] + ejem[0:4]
print (subejem)
#ejem = ejem.split(" ")
#print (ejem[2:4], ejem[1::-1]) | ejem = 'esto es un ejemplo'
print(ejem)
print(ejem[8:18], ejem[5:7], ejem[0:4])
subejem = ejem[8:18] + ejem[4:8] + ejem[0:4]
print(subejem) |
"""Constants for the Almond integration."""
DOMAIN = "almond"
TYPE_OAUTH2 = "oauth2"
TYPE_LOCAL = "local"
| """Constants for the Almond integration."""
domain = 'almond'
type_oauth2 = 'oauth2'
type_local = 'local' |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | def verify_capital(answers: dict) -> dict:
"""
Takes in a dictionary with states as keys and user's answers as values.
Attributes:
mark_scheme: dicitonary containing the correct answers of the quiz.
score: user's total score after quiz.
result: a dictionary containing the correc... |
"""Top-level package for Proto Wind."""
__author__ = """Kais Sghari"""
__email__ = 'kais.sghari@gmail.com'
__version__ = '0.1.0'
| """Top-level package for Proto Wind."""
__author__ = 'Kais Sghari'
__email__ = 'kais.sghari@gmail.com'
__version__ = '0.1.0' |
"""
pytokio implements its command-line tools within this package. Each such CLI
tool either implements some useful analysis on top of pytokio connectors,
tools, or analysis or maps some of the internal python APIs to command-line
arguments.
Most of these tools implement a ``--help`` option to explain the command-lin... | """
pytokio implements its command-line tools within this package. Each such CLI
tool either implements some useful analysis on top of pytokio connectors,
tools, or analysis or maps some of the internal python APIs to command-line
arguments.
Most of these tools implement a ``--help`` option to explain the command-lin... |
max_char = 105
sample_rate = 22050
n_fft = 1024
hop_length = 256
win_length = 1024
preemphasis = 0.97
ref_db = 20
max_db = 100
mel_dim = 80
max_length = 780
reduction = 4
embedding_dim = 128
symbol_length = 70
d = 256
c = 512
f = n_fft // 2 + 1
batch_size = 16
checkpoint_step = 500
max_T = 160
learning_rate = 0.0002
be... | max_char = 105
sample_rate = 22050
n_fft = 1024
hop_length = 256
win_length = 1024
preemphasis = 0.97
ref_db = 20
max_db = 100
mel_dim = 80
max_length = 780
reduction = 4
embedding_dim = 128
symbol_length = 70
d = 256
c = 512
f = n_fft // 2 + 1
batch_size = 16
checkpoint_step = 500
max_t = 160
learning_rate = 0.0002
be... |
"""Testes para as rotas de auth"""
def test_authentication(fake_user, client_auth_with_one):
"""Testando a rota authentication"""
url = "/api/auth/"
data = {"email": fake_user.email, "password": fake_user.password}
response = client_auth_with_one.post(url=url, json=data)
assert response.status_... | """Testes para as rotas de auth"""
def test_authentication(fake_user, client_auth_with_one):
"""Testando a rota authentication"""
url = '/api/auth/'
data = {'email': fake_user.email, 'password': fake_user.password}
response = client_auth_with_one.post(url=url, json=data)
assert response.status_code... |
'''
Problem Description
The program takes two dictionaries and
concatenates them into one dictionary.
Problem Solution
1. Declare and initialize two dictionaries
with some key-value pairs
2. Use the update() function to add the
key-value pair from the second dictionary
to the first dictionary.
3. Print ... | """
Problem Description
The program takes two dictionaries and
concatenates them into one dictionary.
Problem Solution
1. Declare and initialize two dictionaries
with some key-value pairs
2. Use the update() function to add the
key-value pair from the second dictionary
to the first dictionary.
3. Print the final d... |
LOC_RECENT = u'/AppData/Roaming/Microsoft/Windows/Recent/'
LOC_REG = u'/Windows/System32/config/'
LOC_WINEVT = LOC_REG
LOC_WINEVTX = u'/Windows/System32/winevt/logs/'
LOC_AMCACHE = u'/Windows/AppCompat/Programs/'
SYSTEM_FILE = [ # [artifact, src_path, dest_dir]
# registry hives
['regb', LOC_REG + u'RegBack/SA... | loc_recent = u'/AppData/Roaming/Microsoft/Windows/Recent/'
loc_reg = u'/Windows/System32/config/'
loc_winevt = LOC_REG
loc_winevtx = u'/Windows/System32/winevt/logs/'
loc_amcache = u'/Windows/AppCompat/Programs/'
system_file = [['regb', LOC_REG + u'RegBack/SAM', u'/Registry/RegBack/'], ['regb', LOC_REG + u'RegBack/SECU... |
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... | """The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... |
class Config():
appId = None
apiKey = None
domain = None
def __init__(self, appId, apiKey, domain):
self.appId = appId
self.apiKey = apiKey
self.domain = domain | class Config:
app_id = None
api_key = None
domain = None
def __init__(self, appId, apiKey, domain):
self.appId = appId
self.apiKey = apiKey
self.domain = domain |
"""
A utility for summing up two numbers.
"""
def add_two_numbers(first, second):
"""Adds up both numbers and return the sum.
Input values must be numbers."""
if not isinstance(first, (int, float)) or not (isinstance(second, (int, float))):
raise ValueError("Inputs must be numbers.")
return fi... | """
A utility for summing up two numbers.
"""
def add_two_numbers(first, second):
"""Adds up both numbers and return the sum.
Input values must be numbers."""
if not isinstance(first, (int, float)) or not isinstance(second, (int, float)):
raise value_error('Inputs must be numbers.')
return firs... |
for i in range(int(input())):
array_length = int(input())
array = map(int, input().split())
s = sum(array)
if s < array_length:
print(1)
else:
print(s - array_length)
| for i in range(int(input())):
array_length = int(input())
array = map(int, input().split())
s = sum(array)
if s < array_length:
print(1)
else:
print(s - array_length) |
def _get_value(obj, key):
list_end = key.find("]")
is_list = list_end > 0
if is_list:
list_index = int(key[list_end - 1])
return obj[list_index]
return obj[key]
def find(obj, path):
try:
# Base case
if len(path) == 0:
return obj
key = str(path[0]... | def _get_value(obj, key):
list_end = key.find(']')
is_list = list_end > 0
if is_list:
list_index = int(key[list_end - 1])
return obj[list_index]
return obj[key]
def find(obj, path):
try:
if len(path) == 0:
return obj
key = str(path[0])
rest = path... |
GRAPH = {
"A":["B","D","E"],
"B":["A","C","D"],
"C":["B","G"],
"D":["A","B","E","F"],
"E":["A","D"],
"F":["D"],
"G":["C"]
}
visited_list = [] # an empty list of visited nodes
def dfs(graph, current_vertex, visited):
visited.append(current_vertex)
for vertex in graph[current_vertex]... | graph = {'A': ['B', 'D', 'E'], 'B': ['A', 'C', 'D'], 'C': ['B', 'G'], 'D': ['A', 'B', 'E', 'F'], 'E': ['A', 'D'], 'F': ['D'], 'G': ['C']}
visited_list = []
def dfs(graph, current_vertex, visited):
visited.append(current_vertex)
for vertex in graph[current_vertex]:
if vertex not in visited:
... |
class Solution:
def minCostClimbingStairs(self, cost):
dp = [0] * (len(cost) + 1)
for i in range(2, len(dp)):
dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1])
return dp[-1]
s = Solution()
print(s.minCostClimbingStairs([10, 15, 20]))
print(s.minCostClimbingStairs([1... | class Solution:
def min_cost_climbing_stairs(self, cost):
dp = [0] * (len(cost) + 1)
for i in range(2, len(dp)):
dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1])
return dp[-1]
s = solution()
print(s.minCostClimbingStairs([10, 15, 20]))
print(s.minCostClimbingStairs(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Version Number
# ------------------------------------------------------------------------------
major_version = "1"
minor_version = "2"
patch_version = "0"
# -------------------------------... | major_version = '1'
minor_version = '2'
patch_version = '0'
help = '====================================================\nufolint\nCopyright 2019 Source Foundry Authors\nMIT License\nSource: https://github.com/source-foundry/ufolint\n====================================================\n\nufolint is a UFO source file l... |
def save_transcriptions(path, transcriptions):
with open(path, 'w') as f:
for key in transcriptions:
f.write('{} {}\n'.format(key, transcriptions[key]))
def load_transcriptions(path):
transcriptions = {}
with open(path, "r") as f:
for line_no, line in enumerate(f):
... | def save_transcriptions(path, transcriptions):
with open(path, 'w') as f:
for key in transcriptions:
f.write('{} {}\n'.format(key, transcriptions[key]))
def load_transcriptions(path):
transcriptions = {}
with open(path, 'r') as f:
for (line_no, line) in enumerate(f):
... |
class Halo_Status_Class():
def __init__(self):
# Halos information exist?
self.HalosDataExist = False
# AGNs information exist?
self.AGNsDataExist = False
# Solved for Lx, T, flux?
self.LxTxSolved = False
# Trasformed into XCat prefered coordinate?
self.XCatPr... | class Halo_Status_Class:
def __init__(self):
self.HalosDataExist = False
self.AGNsDataExist = False
self.LxTxSolved = False
self.XCatPreferedCoordinate = False
def update(self, Halo_data):
self.HalosDataExist = True
self.AGNsDataExist = False
self.LxTxSo... |
def load(info):
info['config']['/jquery'] = {
'tools.staticdir.on': 'True',
'tools.staticdir.dir': 'clients/jquery'
}
| def load(info):
info['config']['/jquery'] = {'tools.staticdir.on': 'True', 'tools.staticdir.dir': 'clients/jquery'} |
class Foo(object):
def __init__(self):
with open('b.py'):
self.scope = "a"
pass
def get_scope(self):
return self.scope | class Foo(object):
def __init__(self):
with open('b.py'):
self.scope = 'a'
pass
def get_scope(self):
return self.scope |
def shell(arr):
gap = len(arr) // 2
while gap >= 1:
for i in xrange(len(arr)):
if i + gap > len(arr) - 1:
break
insertion_sort_gap(arr, i, gap)
gap //= 2
def insertion_sort_gap(arr, start, gap):
pos = start + gap
while pos - gap >= 0 and arr[pos]... | def shell(arr):
gap = len(arr) // 2
while gap >= 1:
for i in xrange(len(arr)):
if i + gap > len(arr) - 1:
break
insertion_sort_gap(arr, i, gap)
gap //= 2
def insertion_sort_gap(arr, start, gap):
pos = start + gap
while pos - gap >= 0 and arr[pos] ... |
# This program says hello and asks for my name and show my age.
print('Hello, World!')
print('What is your name?') #ask for name
myName = input()
print('It is good to meet you ' + myName)
print('The length of your name is :')
print(len(myName))
print('Please tell your age:') # ask for age
myAge = input()
print('Yo... | print('Hello, World!')
print('What is your name?')
my_name = input()
print('It is good to meet you ' + myName)
print('The length of your name is :')
print(len(myName))
print('Please tell your age:')
my_age = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.') |
# -*- coding: utf-8 -*-
"""
_app_name_.manage.stores
~~~~~~~~~~~~~~~~~~~~~~
store management commands
"""
| """
_app_name_.manage.stores
~~~~~~~~~~~~~~~~~~~~~~
store management commands
""" |
load("//:third_party/org_sonatype_sisu.bzl", org_sonatype_sisu_deps = "dependencies")
load("//:third_party/org_eclipse_sisu.bzl", org_eclipse_sisu_deps = "dependencies")
load("//:third_party/org_eclipse_aether.bzl", org_eclipse_aether_deps = "dependencies")
load("//:third_party/org_checkerframework.bzl", org_checkerfra... | load('//:third_party/org_sonatype_sisu.bzl', org_sonatype_sisu_deps='dependencies')
load('//:third_party/org_eclipse_sisu.bzl', org_eclipse_sisu_deps='dependencies')
load('//:third_party/org_eclipse_aether.bzl', org_eclipse_aether_deps='dependencies')
load('//:third_party/org_checkerframework.bzl', org_checkerframework... |
#-*-coding:utf-8-*-
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n < 0:
n = -n
x = 1.0 / x
return self.myPow(x * x, n/2) if n % 2 == 0 else ... | class Solution(object):
def my_pow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n < 0:
n = -n
x = 1.0 / x
return self.myPow(x * x, n / 2) if n % 2 == 0 else self.myPow(x * x,... |
"""
1. Clarification
2. Possible solutions
- Binary Search
3. Coding
4. Tests
"""
# T=O(nlg(sigma(w))), S=O(1)
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
if not weights or D < 1: return 0
left, right = max(weights), sum(weights)
while left < right:
... | """
1. Clarification
2. Possible solutions
- Binary Search
3. Coding
4. Tests
"""
class Solution:
def ship_within_days(self, weights: List[int], D: int) -> int:
if not weights or D < 1:
return 0
(left, right) = (max(weights), sum(weights))
while left < right:
mi... |
def getFuel(mass):
return int(mass/3)-2
def getTotalFuel_1(values):
total = 0
for v in values:
total += getFuel(v)
return total
def getTotalFuel_2(values):
total = 0
for v in values:
while(True):
v = getFuel(v)
if v < 0:
break
... | def get_fuel(mass):
return int(mass / 3) - 2
def get_total_fuel_1(values):
total = 0
for v in values:
total += get_fuel(v)
return total
def get_total_fuel_2(values):
total = 0
for v in values:
while True:
v = get_fuel(v)
if v < 0:
break
... |
# -*- coding: utf-8 -*-
{
'name': "Merced Report",
'summary': """Informe de Presupuesto""",
'description': """
Este informe imprime el nombre del usuario logueado, el cual crea el informe del presupuesto
""",
'author': "Soluciones4G",
'website': "http://www.soluciones4g.com",
... | {'name': 'Merced Report', 'summary': 'Informe de Presupuesto', 'description': '\n Este informe imprime el nombre del usuario logueado, el cual crea el informe del presupuesto\n ', 'author': 'Soluciones4G', 'website': 'http://www.soluciones4g.com', 'category': 'Sale', 'version': '1', 'depends': ['sale'], '... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftIGUALDADDESIGUALDADleftMAYORMENORMAYORIGUALMENORIGUALleftSUMARESTAleftMULTIPLICACIONDIVISIONleftPAR_ABREPAR_CIERRALLAVE_ABRELLAVE_CIERRACADENA DECIMAL DESIGUALDAD D... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftIGUALDADDESIGUALDADleftMAYORMENORMAYORIGUALMENORIGUALleftSUMARESTAleftMULTIPLICACIONDIVISIONleftPAR_ABREPAR_CIERRALLAVE_ABRELLAVE_CIERRACADENA DECIMAL DESIGUALDAD DIVISION ELSE ENTERO ID IF IGUALDAD IMPRIMIR LLAVE_ABRE LLAVE_CIERRA MAYOR MAYORIGUAL MENOR MEN... |
def calculate(expr: str) -> int:
"""Evaluate 'expr', which contains only non-negative integers,
{+,-,*,/} operators and empty spaces."""
plusOrMinus = {'+': lambda x, y: x + y ,
'-': lambda x, y: x - y}
mulOrDiv = {'*': lambda x, y: x * y ,
'/': lambda x, y: x // y}
... | def calculate(expr: str) -> int:
"""Evaluate 'expr', which contains only non-negative integers,
{+,-,*,/} operators and empty spaces."""
plus_or_minus = {'+': lambda x, y: x + y, '-': lambda x, y: x - y}
mul_or_div = {'*': lambda x, y: x * y, '/': lambda x, y: x // y}
stack = []
operators = []
... |
# Python support inheritance from multiple classes. This part will show you:
# how multiple inheritance works
# how to use super() to call methods inherited from multiple parents
# what complexities derive from multiple inheritance
# how to write a mixin, which is a common use of multiple inheritance
class RightPyram... | class Rightpyramid(Triangle, Square):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def what_am_i(self):
return 'Pyramid'
class A:
def __init__(self):
print('A')
super().__init__()
class B(A):
def __init__(self):
... |
# -*- coding: utf-8 -*-
E = int(input())
N = int(input())
P = float(input())
SALARY = N * P
print("NUMBER = %d" % (E))
print("SALARY = U$ %.2f" % (SALARY)) | e = int(input())
n = int(input())
p = float(input())
salary = N * P
print('NUMBER = %d' % E)
print('SALARY = U$ %.2f' % SALARY) |
data = open(r"C:\Users\gifte\Desktop\game\data_number.txt",'r')
x = data.readlines()
string=""
for line in x:
for _ in line:
if _ =="0":
string+="a"
elif _ =="1":
string+="s"
elif _ =="2":
string+="d"
elif _ =="3":
string+="... | data = open('C:\\Users\\gifte\\Desktop\\game\\data_number.txt', 'r')
x = data.readlines()
string = ''
for line in x:
for _ in line:
if _ == '0':
string += 'a'
elif _ == '1':
string += 's'
elif _ == '2':
string += 'd'
elif _ == '3':
stri... |
#
# PySNMP MIB module ADIC-INTELLIGENT-STORAGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADIC-INTELLIGENT-STORAGE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) ... |
def get_cleaned_url(url, api_host, api_version):
if any(prefix in url for prefix in ["http://", "https://"]):
return url
cleaned_url = api_host.rstrip("/")
if url.startswith("/{}".format(api_version)):
cleaned_url += url
else:
cleaned_url += "/{}{}".format(api_version, url)
... | def get_cleaned_url(url, api_host, api_version):
if any((prefix in url for prefix in ['http://', 'https://'])):
return url
cleaned_url = api_host.rstrip('/')
if url.startswith('/{}'.format(api_version)):
cleaned_url += url
else:
cleaned_url += '/{}{}'.format(api_version, url)
... |
def generate_full_name(firstname, lastname):
space = ' '
fullname = firstname + space + lastname
return fullname
| def generate_full_name(firstname, lastname):
space = ' '
fullname = firstname + space + lastname
return fullname |
balance = 1000.00
name = "Chuck Black"
account_no = "01123581321"
print("name:", name, " account:", account_no, " original balance:", "$" + str(balance))
charge01 = 5.99
charge02 = 12.45
charge03 = 28.05
balance = balance - charge01
print("name:", name, " account:", account_no, " charge:", cha... | balance = 1000.0
name = 'Chuck Black'
account_no = '01123581321'
print('name:', name, ' account:', account_no, ' original balance:', '$' + str(balance))
charge01 = 5.99
charge02 = 12.45
charge03 = 28.05
balance = balance - charge01
print('name:', name, ' account:', account_no, ' charge:', charge01, ' ne... |
class Article:
url = ''
title = ''
summary = ''
date = ''
keywords = ''
class Author:
url = ''
name = ''
major = ''
sum_publish = ''
sum_download = ''
class Organization:
url = ''
name = ''
website = ''
used_name = ''
region = ''
class Source:
url = ... | class Article:
url = ''
title = ''
summary = ''
date = ''
keywords = ''
class Author:
url = ''
name = ''
major = ''
sum_publish = ''
sum_download = ''
class Organization:
url = ''
name = ''
website = ''
used_name = ''
region = ''
class Source:
url = ''
... |
# ['alexnet', 'deeplabv3_resnet101', 'deeplabv3_resnet50', 'densenet121', 'densenet161', 'densenet169', 'densenet201',
# 'fcn_resnet101', 'fcn_resnet50', 'googlenet', 'inception_v3', 'mnasnet0_5', 'mnasnet0_75', 'mnasnet1_0', 'mnasnet1_3',
# 'mobilenet_v2', 'resnet101', 'resnet152', 'resnet18', 'resnet34', 'resnet50'... | model_config = dict(model='resnext101_32x8d', num_classes=5, pretrained=True)
data_name = 'cassava'
data_root = 'data/cassava/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
dataset = dict(raw_train_path=data_root + 'train.csv', raw_split=[('train', 0.8), ('val', 1.0)], b... |
#
# PySNMP MIB module SYMMCOMMONNETWORK (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONNETWORK
# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:11 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (de... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
# AutoTransform
# Large scale, component based code modification library
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>
# SPDX-License-Identifier: MIT
# Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro>
# @black_format
"""Batchers take filtered Items and separate them in... | """Batchers take filtered Items and separate them in to logical groupings
with associated metadata that can be acted on independently.""" |
class MergeRequest:
class MergeType(str):
pass
MergeType.DEV = MergeType('dev')
MergeType.PROD = MergeType('prod')
MergeType.MAINTENANCE = MergeType('maintenance')
def __init__(self, merge_type: MergeType, source_branch: str, target_branch: str):
self.merge_type = merge_type
... | class Mergerequest:
class Mergetype(str):
pass
MergeType.DEV = merge_type('dev')
MergeType.PROD = merge_type('prod')
MergeType.MAINTENANCE = merge_type('maintenance')
def __init__(self, merge_type: MergeType, source_branch: str, target_branch: str):
self.merge_type = merge_type
... |
def calc( X=1, Y=2 ):
try:
return X % Y
except TypeError:
return 5
def process( A=0, B=0 ):
V, Z = (0, 0)
try:
Z = calc( int(A), B )
except ValueError:
V += 16
except ZeroDivisionError:
V += 8
except:
V += 4
else:
V += 2
finally... | def calc(X=1, Y=2):
try:
return X % Y
except TypeError:
return 5
def process(A=0, B=0):
(v, z) = (0, 0)
try:
z = calc(int(A), B)
except ValueError:
v += 16
except ZeroDivisionError:
v += 8
except:
v += 4
else:
v += 2
finally:
... |
# Settings File to declare constants
TRAINING__DATA_PATH = '../training.csv'
TESTING__DATA_PATH = '../test.csv'
SAVE_PREDICTION_PATH = '../predictions.csv'
SAVE_MODEL_PATH = '../model.pkl'
CELERY_SETTINGS = 'celeryconfig' | training__data_path = '../training.csv'
testing__data_path = '../test.csv'
save_prediction_path = '../predictions.csv'
save_model_path = '../model.pkl'
celery_settings = 'celeryconfig' |
"""
Auto DM
Jeremy L Thompson
This file provides dictionaries for random modules
"""
# ------------------------------------------------------------------------------
# Dictionary of Monsters
# ------------------------------------------------------------------------------
ALL_MONSTERS = [ # Monster Manual... | """
Auto DM
Jeremy L Thompson
This file provides dictionaries for random modules
"""
all_monsters = [{'Name': 'commoner', 'CR': '0', 'Env': ['arctic', 'coastal', 'desert', 'forest', 'grassland', 'hill', 'urban']}, {'Name': 'Owl', 'CR': '0', 'Env': ['arctic', 'forest']}, {'Name': 'bandit', 'CR': '1/8', 'En... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.