content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module NCRBSC-OPT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NCRBSC-OPT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:08:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
def main(name):
print(f'Hey {name}')
if __name__ == '__main__':
name = 'Astarag'
main(name)
| def main(name):
print(f'Hey {name}')
if __name__ == '__main__':
name = 'Astarag'
main(name) |
def gather_writable_check_list(hook, check_list, **kwargs):
pass
def before_project_updated(hook, project_uploader, **kwargs):
pass
def after_project_updated(hook, project_uploader, **kwargs):
pass
def before_resource_group_updated(hook, resource_group_uploader, **kwargs):
pass
def after_resource_gr... | def gather_writable_check_list(hook, check_list, **kwargs):
pass
def before_project_updated(hook, project_uploader, **kwargs):
pass
def after_project_updated(hook, project_uploader, **kwargs):
pass
def before_resource_group_updated(hook, resource_group_uploader, **kwargs):
pass
def after_resource_gr... |
"""
'Constants' in the Redmine schema. It is possible, even probable, that
you will need to customize this based on your installation.
"""
REDMINE_CONSTS = {
'TRACKER': {
'BUG': 1,
'FEATURE': 2,
'SUPPORT': 3
},
'STATUS': {
'NEW': 1,
'IN_PROGRESS': 2,
'RESOLVED': 3,... | """
'Constants' in the Redmine schema. It is possible, even probable, that
you will need to customize this based on your installation.
"""
redmine_consts = {'TRACKER': {'BUG': 1, 'FEATURE': 2, 'SUPPORT': 3}, 'STATUS': {'NEW': 1, 'IN_PROGRESS': 2, 'RESOLVED': 3, 'FEEDBACK': 4, 'CLOSED': 5, 'REJECTED': 6}, 'PRIORITY': {... |
#! /usr/bin/env python3
x = 2.21
print(str(x), "Gigowatts !!!", str(x), "Gigowatts !! Nom de Zeus ! Marty !")
print("%s Gigowatts !!! %s Gigowatts !! Nom de Zeus ! Marty !" %(x, x))
print("{} Gigowatts !!! {} Gigowatts !! Nom de Zeus ! Marty !".format(x, x))
| x = 2.21
print(str(x), 'Gigowatts !!!', str(x), 'Gigowatts !! Nom de Zeus ! Marty !')
print('%s Gigowatts !!! %s Gigowatts !! Nom de Zeus ! Marty !' % (x, x))
print('{} Gigowatts !!! {} Gigowatts !! Nom de Zeus ! Marty !'.format(x, x)) |
class Solution:
def combinationSum(self, candidates, target: int):
res = []
for i in candidates:
if i == target:
res.append([i])
continue
if i > target:
continue
ext = self.combinationSum(candidates, target - i)
... | class Solution:
def combination_sum(self, candidates, target: int):
res = []
for i in candidates:
if i == target:
res.append([i])
continue
if i > target:
continue
ext = self.combinationSum(candidates, target - i)
... |
_base_ = "./resnest50d_online_AugCosyAAEGray_mlBCE_DoubleMask_lmoRealNBPbr_100e_01_ape_bop_test.py"
OUTPUT_DIR = (
"output/gdrn/lmoRealPbrSO/resnest50d_online_AugCosyAAEGray_mlBCE_DoubleMask_lmoRealNBPbr_100e_SO/holepuncher"
)
DATASETS = dict(TRAIN=("lmo_pbr_holepuncher_train", "lmo_NoBopTest_holepuncher_train"))
| _base_ = './resnest50d_online_AugCosyAAEGray_mlBCE_DoubleMask_lmoRealNBPbr_100e_01_ape_bop_test.py'
output_dir = 'output/gdrn/lmoRealPbrSO/resnest50d_online_AugCosyAAEGray_mlBCE_DoubleMask_lmoRealNBPbr_100e_SO/holepuncher'
datasets = dict(TRAIN=('lmo_pbr_holepuncher_train', 'lmo_NoBopTest_holepuncher_train')) |
def max_of_min(num1, num2, value1, value2):
min_num = min(num1, num2)
min_val = min(value1, value2)
return max(min_num, min_val)
| def max_of_min(num1, num2, value1, value2):
min_num = min(num1, num2)
min_val = min(value1, value2)
return max(min_num, min_val) |
#
# PySNMP MIB module CISCO-TRUSTSEC-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TRUSTSEC-SERVER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:14:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
# Description: Count number of *.ccp4 (electron density map) files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of ccp4 electron density files in current directory.");')
cmd.do('print("Usage: cntccp4s");')
cmd.do('myPath = os.getcwd();')
cmd.do('ccp4Counter = len(glob.glob1(myPath,... | """
cmd.do('print("Count the number of ccp4 electron density files in current directory.");')
cmd.do('print("Usage: cntccp4s");')
cmd.do('myPath = os.getcwd();')
cmd.do('ccp4Counter = len(glob.glob1(myPath,"*.pse"));')
cmd.do('print("Number of number of ccp4 electron density files in the current directory: ", ccp4Count... |
"""
Given n non-negative integers, find the two lines that make the walls of the larges volume of water.
Other words: Find two numbers i, j
where (j - i) * min(arr[i], arr[j]) is maximized.
"""
class Solution:
def maxArea(self, height):
valueMinMaxInds = {}
for ind, h in enumerate(height):
if h in v... | """
Given n non-negative integers, find the two lines that make the walls of the larges volume of water.
Other words: Find two numbers i, j
where (j - i) * min(arr[i], arr[j]) is maximized.
"""
class Solution:
def max_area(self, height):
value_min_max_inds = {}
for (ind, h) in enumerate(height):... |
t=int(input())
while(t):
t=t-1
n,m,k=input().split()
n,m,k=int(n),int(m),int(k)
a,b=min(n,m),max(n,m)
c=b-a
c1=c-k
print(max(c1,0))
| t = int(input())
while t:
t = t - 1
(n, m, k) = input().split()
(n, m, k) = (int(n), int(m), int(k))
(a, b) = (min(n, m), max(n, m))
c = b - a
c1 = c - k
print(max(c1, 0)) |
def consumer():
r = ''
while True:
n = yield r
if not n:return
print('consuming the event %s'%n)
r = '200 OK'
def produce(c):
c.send(None)
for n in range(1,6):
print('producing event %s'%n)
r = c.send(n)
print('the consumer response %s'%r)
c.c... | def consumer():
r = ''
while True:
n = (yield r)
if not n:
return
print('consuming the event %s' % n)
r = '200 OK'
def produce(c):
c.send(None)
for n in range(1, 6):
print('producing event %s' % n)
r = c.send(n)
print('the consumer res... |
def letters( input):
return ''.join(filter(str.isalpha, input))
def strip_input_name( input ):
return | def letters(input):
return ''.join(filter(str.isalpha, input))
def strip_input_name(input):
return |
print(r"""Switching on camera from habitat with camels...
___.-''''-.
/___ @ |
',,,,. | _.'''''''._
' | / \
| \ _.-' \
| '.-' '-.
| ',
| '',
... | print("Switching on camera from habitat with camels...\n ___.-''''-.\n/___ @ |\n',,,,. | _.'''''''._\n ' | / \\\n | \\ _.-' \\\n | '.-' '-.\n | ',\n | '',\n ... |
# 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, software
# distributed under the... | """
Basic FSM for building CLI parsers for prompt expansions, etc.
"""
any = -1
class Fsmerror(Exception):
pass
class Fsm:
any = ANY
def __init__(self, initial_state=0):
self._transitions = {}
self.default_transition = None
self.RESET = initial_state
self.initial_state = s... |
def print_parentheses(P):
stack = list()
for p in P:
if stack and stack[-1] == '(' and p == ')':
stack.pop()
print(' ' * len(stack) + p)
else:
stack.append(p)
print(' ' * (len(stack) - 1) + p)
print_parentheses('(()((())()))') | def print_parentheses(P):
stack = list()
for p in P:
if stack and stack[-1] == '(' and (p == ')'):
stack.pop()
print(' ' * len(stack) + p)
else:
stack.append(p)
print(' ' * (len(stack) - 1) + p)
print_parentheses('(()((())()))') |
"""Below Python Programme demonstrate rstrip
functions in a string"""
#Example:
random_string = ' this is good'
# Leading whitepsace are removed
print(random_string.rstrip())
# Argument doesn't contain 'd'
# No characters are removed.
print(random_string.rstrip('si oo'))
print(random_string.rstrip('sid oo'))
| """Below Python Programme demonstrate rstrip
functions in a string"""
random_string = ' this is good'
print(random_string.rstrip())
print(random_string.rstrip('si oo'))
print(random_string.rstrip('sid oo')) |
# caption dataset
class caption_dataset(torch.utils.data.Dataset):
def __init__(self, captions, path, tokenizer, max_len, mode):
self.captions = captions
self.path = path
self.tokenizer = tokenizer
self.max_len = max_len
self.mode = mode
self.start = self.tokenizer.convert_tokens_to_ids('[sta... | class Caption_Dataset(torch.utils.data.Dataset):
def __init__(self, captions, path, tokenizer, max_len, mode):
self.captions = captions
self.path = path
self.tokenizer = tokenizer
self.max_len = max_len
self.mode = mode
self.start = self.tokenizer.convert_tokens_to_i... |
# from django.conf.urls import url
# from . import views
urlpatterns = [
# url(r'^change-profile/$',
# views.change_own_profile, name='change-profile'),
]
| urlpatterns = [] |
class GroupNotFoundException(Exception):
pass
class UserNotFoundException(Exception):
pass
class AlreadyExistsOnDatabaseException(Exception):
pass
class ChatIdOrTextCannotBeEmpty(Exception):
pass
| class Groupnotfoundexception(Exception):
pass
class Usernotfoundexception(Exception):
pass
class Alreadyexistsondatabaseexception(Exception):
pass
class Chatidortextcannotbeempty(Exception):
pass |
X_threads = 16
Y_threads = 1
Invoc_count = 1
start_index = 0
end_index = 0
src_list = ["needle_kernel.cu", "needle.h"]
SHARED_MEM_USE = True
total_shared_mem_size = 2.18*1024
domi_list = [481]
domi_val = [0]
| x_threads = 16
y_threads = 1
invoc_count = 1
start_index = 0
end_index = 0
src_list = ['needle_kernel.cu', 'needle.h']
shared_mem_use = True
total_shared_mem_size = 2.18 * 1024
domi_list = [481]
domi_val = [0] |
def init_grid(size=3):
"""Returns an empty Tic-tac-toe grid with measurements size x size"""
# make nested list with list comprehension
return [[' ' for col in range(size)] for row in range(size)]
def print_grid(grid):
"""Prints the grid"""
# empty line for better readability
print()
... | def init_grid(size=3):
"""Returns an empty Tic-tac-toe grid with measurements size x size"""
return [[' ' for col in range(size)] for row in range(size)]
def print_grid(grid):
"""Prints the grid"""
print()
for (i, row) in enumerate(grid):
row_string = ' ' + ' | '.join(row) + ' '
pri... |
class Tardis(object):
def __init__(self):
super().__init__()
def camouflage(self):
raise NotImplementedError('You should implement this in a subclass')
class TardisChild(Tardis):
def camouflage(self):
return 'Yay! Overridden'
if __name__ == "__main__":
# Will raise exception... | class Tardis(object):
def __init__(self):
super().__init__()
def camouflage(self):
raise not_implemented_error('You should implement this in a subclass')
class Tardischild(Tardis):
def camouflage(self):
return 'Yay! Overridden'
if __name__ == '__main__':
child = tardis_child(... |
## @package Connection Connection object that used by Configuration editor
## The class that has all the information about a connection between two modules
class Connection:
## Constructor
# @param self Object pointer
# @param model1 A Module object of one connected module
# @param model2 A module object of th... | class Connection:
def __init__(self, model1, model2, node1, node2, distance=0, angle=0):
self.Module1 = model1
self.Module2 = model2
self.Node1 = node1
self.Node2 = node2
self.Distance = distance
self.Angle = angle
def __len__(self):
return 1 |
"""Constants for Squeezebox emulation."""
PROV_ID = "squeezebox"
PROV_NAME = "Squeezebox emulation"
| """Constants for Squeezebox emulation."""
prov_id = 'squeezebox'
prov_name = 'Squeezebox emulation' |
#!/usr/bin/env python
""" Base package for the jet-hadron correlation analysis.
.. codeauthor:: Raymond Ehlers <raymond.ehlers@cern.ch>, Yale University
"""
__all__ = [
"analysis_config",
"analysis_objects",
"params",
]
| """ Base package for the jet-hadron correlation analysis.
.. codeauthor:: Raymond Ehlers <raymond.ehlers@cern.ch>, Yale University
"""
__all__ = ['analysis_config', 'analysis_objects', 'params'] |
# Employee info
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
... | class Employee:
def __init__(self, id, importance, subordinates):
self.id = id
self.importance = importance
self.subordinates = subordinates
class Solution:
def getemfromid(self, employees, id):
for em in employees:
if em.id == id:
return em
... |
'''Subtypes of str used as names
'''
Role = str
'''Basic identifier for a Node.
'''
# TODO: Suprress inherited docstrings from str
str = str
'''The name of components such as endpoints and loops
'''
| """Subtypes of str used as names
"""
role = str
'Basic identifier for a Node.\n'
str = str
'The name of components such as endpoints and loops\n' |
# This file is for import testing
# nah, nvm i will do my testing here cause i don't wanna delete the test.py file
class SeriesMixed:
def __init__(self):
self.series_side = input('[T]op or [B]ottom or [Both]:')
if self.series_side.lower() == 't':
self.top_value = list(map(int,... | class Seriesmixed:
def __init__(self):
self.series_side = input('[T]op or [B]ottom or [Both]:')
if self.series_side.lower() == 't':
self.top_value = list(map(int, input('Enter the values of the resistors on top: ').split()))
self.bottom_resistor = int(input('Enter the value ... |
def inc(x):
x = x + 1
print(x)
y = 10
inc(y)
print(y)
| def inc(x):
x = x + 1
print(x)
y = 10
inc(y)
print(y) |
# -*- encoding: utf-8 -*-
# Abrimos el archivo para leerlo
filehandler = open('data.txt', 'r')
data = []
for line in filehandler:
line = line.strip('\n')
line = line.split()
line = [float(item) for item in line]
data.append(line)
filehandler.close()
num = 0.0
den = 0.0
alpha = 1
for z, d in data:
... | filehandler = open('data.txt', 'r')
data = []
for line in filehandler:
line = line.strip('\n')
line = line.split()
line = [float(item) for item in line]
data.append(line)
filehandler.close()
num = 0.0
den = 0.0
alpha = 1
for (z, d) in data:
num = num + z / d ** alpha
den = den + 1 / d ** alpha
z... |
class Clause(object):
def __init__(self, clause):
"""Initializes a clause. Here, the input clause is either a list or set
of integers, or is an instance of Clause; in the latter case, a shallow
copy is made, so that one can modify this clause without modifying the
original clause.
... | class Clause(object):
def __init__(self, clause):
"""Initializes a clause. Here, the input clause is either a list or set
of integers, or is an instance of Clause; in the latter case, a shallow
copy is made, so that one can modify this clause without modifying the
original clause.
... |
### def cheese_and_crackers(cheese_count, boxes_of_crackers):
# print(f"cheese_count: {cheese_count}, boxes_of_crackers: {boxes_of_crackers}")
# cheese_and_crackers = (input("How many cheese do you have"), input ("How many crackers you have?"))
# print(" we can do combine the two, variable and math:")
# cheese... | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f'You have {cheese_count} cheeses!')
print(f'You have {boxes_of_crackers} boxes of crackers!')
print("Man that's enough for a party!")
print('Get a blanket.\n')
print('We can just give the function numbers directly:')
cheese_and_crackers(20... |
"""DTO that holds all information about word, its stem and assigned group"""
class ProcessingEntry:
def __init__(self, org):
"""Initialize ProcessingEntry class"""
self.__org = org
self.__stem = org
self.__group = -1
self.__is_exemplar = False
@property
def org(se... | """DTO that holds all information about word, its stem and assigned group"""
class Processingentry:
def __init__(self, org):
"""Initialize ProcessingEntry class"""
self.__org = org
self.__stem = org
self.__group = -1
self.__is_exemplar = False
@property
def org(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Constants for APRS Module Tests."""
__author__ = 'Greg Albrecht W2GMD <gba@orionlabs.co>'
__license__ = 'Apache License, Version 2.0'
__copyright__ = 'Copyright 2015 Orion Labs, Inc.'
TEST_FRAMES = 'tests/test_frames.log'
| """Constants for APRS Module Tests."""
__author__ = 'Greg Albrecht W2GMD <gba@orionlabs.co>'
__license__ = 'Apache License, Version 2.0'
__copyright__ = 'Copyright 2015 Orion Labs, Inc.'
test_frames = 'tests/test_frames.log' |
line = input().split()
n = int(line[0])
k = int(line[1])
line = [int(i) for i in input().split()]
counter = 0
for j in line:
if(5 - j >= k):
counter += 1
print(str(counter//3))
| line = input().split()
n = int(line[0])
k = int(line[1])
line = [int(i) for i in input().split()]
counter = 0
for j in line:
if 5 - j >= k:
counter += 1
print(str(counter // 3)) |
# coding: utf-8
def array_values(arr):
if isinstance(arr, dict):
return arr.values()
return arr[:]
if __name__ == '__main__':
array = {"size": "XL", "color": "gold"}
print(array_values(array))
| def array_values(arr):
if isinstance(arr, dict):
return arr.values()
return arr[:]
if __name__ == '__main__':
array = {'size': 'XL', 'color': 'gold'}
print(array_values(array)) |
class Node:
def __init__(self, key=0, data=0):
self.data = data
self.key = key
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.lookup = {}
self.size = 0
self.head = Node()
... | class Node:
def __init__(self, key=0, data=0):
self.data = data
self.key = key
self.prev = None
self.next = None
class Lrucache:
def __init__(self, capacity: int):
self.capacity = capacity
self.lookup = {}
self.size = 0
self.head = node()
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 14:11:08 2021
@author: asagar
"""
def static_rules():
# rules defined and more can be added
# ref: https://en.wikipedia.org/wiki/Tuple
# ref:https://www.proz.com/kudoz/english/other/526192-2%3Ddouble3%3Dtriplewhats-for-456etc.html
rules = {'numbers':... | """
Created on Tue Mar 23 14:11:08 2021
@author: asagar
"""
def static_rules():
rules = {'numbers': {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}, 'tuples': {'double': 2, 'triple': 3, 'quadruple': 4, 'quintuple': 5, 'sextuple': 6, 'septuple': 7, 'oc... |
# -*- Mode: Python; tab-width: 4 -*-
# SMR 2012: originally from dynwin, circa 1995
###########################################################################
# regions
###########################################################################
#
# do two rectangular regions intersect?
#
# +--->
# | lb,tb... | def region_intersect_p(a, b):
return a[2] >= b[0] and b[2] >= a[0] and (a[3] >= b[1]) and (b[3] >= a[1])
def point_in_region_p(x, y, r):
return r[0] <= x <= r[2] and r[1] <= y <= r[3]
def region_contains_region_p(a, b):
return a[0] <= b[0] and a[2] >= b[2] and (a[1] <= b[1]) and (a[3] >= b[3])
def union(... |
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
# build a class to manage nodes
class LinkedList:
def __init__(self):
self.head = None # stores a node that is the begining of the list
self.tail = None # stores a node ... | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
output = ''
current_node = self.head
while current_... |
# Prints sum
count = sum = 0
while True:
n = int(input('Digite um valor (999 para parar): '))
if n == 999:
break
count += 1
sum += n
print(f'A soma dos {count} valores foi {sum}!')
| count = sum = 0
while True:
n = int(input('Digite um valor (999 para parar): '))
if n == 999:
break
count += 1
sum += n
print(f'A soma dos {count} valores foi {sum}!') |
def Rotate(arr):
temp=[]
for i in range(len(arr)):
for j in range(0,len(arr)):
if i != j and i < j :
arr[i][j],arr[j][i]=arr[j][i],arr[i][j]
for l in arr:
l.reverse()
print(l)
arr=[[1,2,3],
[4,5,6],
[7,8,9]]
Rotate(arr)
| def rotate(arr):
temp = []
for i in range(len(arr)):
for j in range(0, len(arr)):
if i != j and i < j:
(arr[i][j], arr[j][i]) = (arr[j][i], arr[i][j])
for l in arr:
l.reverse()
print(l)
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotate(arr) |
class Form(GenericForm, IDisposable):
""" An object that represents a Form within the Autodesk Revit Massing Family. """
def AddEdge(self, *__args):
"""
AddEdge(self: Form,faceReference: Reference,point: XYZ)
Add an edge to the form,connecting two edges on different profiles,by a
s... | class Form(GenericForm, IDisposable):
""" An object that represents a Form within the Autodesk Revit Massing Family. """
def add_edge(self, *__args):
"""
AddEdge(self: Form,faceReference: Reference,point: XYZ)
Add an edge to the form,connecting two edges on different profiles,by a
specified... |
expected_output = {
"on_demand_tunnel":{
"20":{
"system-ip":"20.0.0.20",
"on-demand":"no"
},
"21":{
"system-ip":"21.0.0.21",
"on-demand":"yes",
"status":"inactive"
},
"22":{
"system-ip":"22.0.0.22",
... | expected_output = {'on_demand_tunnel': {'20': {'system-ip': '20.0.0.20', 'on-demand': 'no'}, '21': {'system-ip': '21.0.0.21', 'on-demand': 'yes', 'status': 'inactive'}, '22': {'system-ip': '22.0.0.22', 'on-demand': 'no'}, '23': {'system-ip': '23.0.0.23', 'on-demand': 'yes', 'status': 'inactive'}, '24': {'system-ip': '2... |
class FieldMetaMixin:
@classmethod
def get_field_meta(cls, field_name):
return cls._meta.get_field(field_name).get_meta()
@classmethod
def has_field_meta(cls, field_name):
return hasattr(cls._meta.get_field(field_name), "_meta") \
and cls.get_field_meta(field_name) is not... | class Fieldmetamixin:
@classmethod
def get_field_meta(cls, field_name):
return cls._meta.get_field(field_name).get_meta()
@classmethod
def has_field_meta(cls, field_name):
return hasattr(cls._meta.get_field(field_name), '_meta') and cls.get_field_meta(field_name) is not None |
# loop through a string
s = "string"
#Version 1
for i in s:
print(i)
#version 2
for i in range(len(s)):
print(s[i]) | s = 'string'
for i in s:
print(i)
for i in range(len(s)):
print(s[i]) |
def to_str(data):
return str(data), None
def to_list(data):
return [data], None
def to_int(data):
try:
return int(data), None
except ValueError:
return data, None | def to_str(data):
return (str(data), None)
def to_list(data):
return ([data], None)
def to_int(data):
try:
return (int(data), None)
except ValueError:
return (data, None) |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
... | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copy_random_list(self, head: 'Node') -> 'Node':
if not head:
return None
... |
CONFIG = {
"testing": False
}
| config = {'testing': False} |
def path_exists(node1, node2, G):
"""
This function checks whether a path exists between two nodes (node1,
node2) in graph G.
Special thanks to @ghirlekar for suggesting that we keep track of the
"visited nodes" to prevent infinite loops from happening. This also
removes the need to remove node... | def path_exists(node1, node2, G):
"""
This function checks whether a path exists between two nodes (node1,
node2) in graph G.
Special thanks to @ghirlekar for suggesting that we keep track of the
"visited nodes" to prevent infinite loops from happening. This also
removes the need to remove node... |
words= []
# this opens the text file that contains a english lanuage dictionary
with open("words.txt") as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
words.append(line.lower())
# these are test shreds in a list of lists. Each list represents the words you kight find ... | words = []
with open('words.txt') as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
words.append(line.lower())
shreds = [['futu', 'for', 'ngth', 're su', 'd st', 'ce a', 'ecial', 'rms book'], ['re price', 'each in', 'of your', 'bject to,', 'nding a', 'portion', 'discount... |
# https://rosalind.info/problems/kmp/
def fmtfa(fasta: list):
prev = True
header = []
seq = []
for f in fasta:
if ">" in f:
header.append(f[1:])
prev = True
elif prev:
seq.append(f)
prev = False
else:
seq[-1] += f
... | def fmtfa(fasta: list):
prev = True
header = []
seq = []
for f in fasta:
if '>' in f:
header.append(f[1:])
prev = True
elif prev:
seq.append(f)
prev = False
else:
seq[-1] += f
return (header, seq)
def revcomp(seq: s... |
######################
# Choose dataset: #
######################
dataset = 'eight'
#########
# Data: #
#########
weighted = False
scaler = 1.
##############
# Training: #
##############
lr = 1e-3
batch_size = 2048
gamma = 0.995
weight_decay = 1e-5
betas = (0.9, 0.999)
n_epochs = 200
n_its_per_epoch = 1
#####... | dataset = 'eight'
weighted = False
scaler = 1.0
lr = 0.001
batch_size = 2048
gamma = 0.995
weight_decay = 1e-05
betas = (0.9, 0.999)
n_epochs = 200
n_its_per_epoch = 1
n_blocks = 12
n_units = 48
n_layers = 3
show_interval = 10
save_interval = 10
test = False
train = True
save_model = True
load_model = False
save_dir = ... |
class AndroidViewport:
def __init__(self, native):
self.native = native
self.dpi = 96 # FIXME This is almost certainly wrong...
# self.dpi = ... self.interface.app._impl.device_scale
@property
def width(self):
return self.native.ClientSize.Width
@property
def heig... | class Androidviewport:
def __init__(self, native):
self.native = native
self.dpi = 96
@property
def width(self):
return self.native.ClientSize.Width
@property
def height(self):
return self.native.ClientSize.Height
class Window:
def __init__(self, interface):
... |
puzzle_input = input("> ")
MIN, MAX = (int(x) for x in puzzle_input.split("-"))
# PART 1
def is_ordered(n):
return list(str(c)) == sorted(str(c))
def has_double(n):
return len(set(str(n))) < len(str(n))
c = MIN
matching = 0
while c <= MAX:
if is_ordered(c):
if has_double(c):
matching +... | puzzle_input = input('> ')
(min, max) = (int(x) for x in puzzle_input.split('-'))
def is_ordered(n):
return list(str(c)) == sorted(str(c))
def has_double(n):
return len(set(str(n))) < len(str(n))
c = MIN
matching = 0
while c <= MAX:
if is_ordered(c):
if has_double(c):
matching += 1
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {}
modules = []
doc_url = "https://chho-work.github.io/biolab/"
git_url = "https://github.com/chho-work/biolab/tree/main/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {}
modules = []
doc_url = 'https://chho-work.github.io/biolab/'
git_url = 'https://github.com/chho-work/biolab/tree/main/'
def custom_doc_links(name):
return None |
"""The common ANTLR rule implementation."""
load(":lang.bzl", "C", "CPP", "GO", "PYTHON", "PYTHON2", "PYTHON3")
AntlrInfo = provider(
fields = {
"sources": "The generated source files.",
"headers": "For C/C++ the generated header files.",
"data": "Additional ANTLR data files",
},
d... | """The common ANTLR rule implementation."""
load(':lang.bzl', 'C', 'CPP', 'GO', 'PYTHON', 'PYTHON2', 'PYTHON3')
antlr_info = provider(fields={'sources': 'The generated source files.', 'headers': 'For C/C++ the generated header files.', 'data': 'Additional ANTLR data files'}, doc='A provider containing information about... |
# Describe an image
# mean (c) 2011
#
FMT_NTSC=0
FMT_PAL=1
FMT_FILM=2
FMT_UNKNOWN=-3
AR_1_1=0
AR_4_3=1
AR_16_9=2
#
#
#
class resizer(object):
def __init(self):
self.width=0
self.height=0
self.topbottom=0
self.leftright=0
self.ar=ADM_image.AR_1_1
#
#
#
#
class image:
def... | fmt_ntsc = 0
fmt_pal = 1
fmt_film = 2
fmt_unknown = -3
ar_1_1 = 0
ar_4_3 = 1
ar_16_9 = 2
class Resizer(object):
def __init(self):
self.width = 0
self.height = 0
self.topbottom = 0
self.leftright = 0
self.ar = ADM_image.AR_1_1
class Image:
def __init__(self):
s... |
strategies = 0
def fit(current_value, max_val):
global strategies, available_coins, goal_value
if current_value == goal_value:
strategies = strategies + 1
return
remaining_value = goal_value - current_value
end = min(remaining_value, max_val)
if end == 1:
strategies += 1... | strategies = 0
def fit(current_value, max_val):
global strategies, available_coins, goal_value
if current_value == goal_value:
strategies = strategies + 1
return
remaining_value = goal_value - current_value
end = min(remaining_value, max_val)
if end == 1:
strategies += 1
... |
# Estrutura de dados - Listas
nomes = ["Amanda","Bruno","Camila","Davi","Elen","Felipe"]
for i in range(0,6,2):
print(nomes[i])
| nomes = ['Amanda', 'Bruno', 'Camila', 'Davi', 'Elen', 'Felipe']
for i in range(0, 6, 2):
print(nomes[i]) |
#!/usr/bin/env python3
class ActionLight:
def __init__(self, funcName, func):
self.funcName = funcName
self.func = func
self.resourceType = False
self.pending = True
self.max_depth = 0
def equals(self, other):
# TODO: should we compare func?
return (t... | class Actionlight:
def __init__(self, funcName, func):
self.funcName = funcName
self.func = func
self.resourceType = False
self.pending = True
self.max_depth = 0
def equals(self, other):
return type(self) == type(other) and self.funcName == other.funcName |
# Must have
device = ['RTR02']
mode = 'collect' # collect, compare ,commit , commit_only, 'jsnapy_pre', 'jsnapy_post'
playbook_summary = 'Check interfaces'
custom_def = False
# conditional
# if mode = commit or commit_only
commit_comments = 'commit_comments'
# if mode not jsnapy_*,commit only
commands = ['show versio... | device = ['RTR02']
mode = 'collect'
playbook_summary = 'Check interfaces'
custom_def = False
commit_comments = 'commit_comments'
commands = ['show version | match junos', 'show configuration interfaces | display set']
config_dir = 'path_to_config_folder'
def nornir_task(task):
pass
csv_report = True
exclude_device... |
#################################################################################
# Class ConlluData
#
# represents a token (a row of 10 columns) in CoNLLU format
#
# Author: Ika Alfina (ika.alfina@cs.ui.ac.id)
#
#################################################################################
class ConlluData:
def ... | class Conlludata:
def __init__(self, ID, form, lemma, UPOS, XPOS, FEAT, headID, deprel):
self.ID = int(ID)
self.lemma = lemma
self.form = form
self.UPOS = UPOS
self.XPOS = XPOS
self.FEAT = FEAT
self.headID = int(headID)
self.deprel = deprel
def g... |
class Solution:
def cheapestJump(self, A, B):
n = len(A)
preMin = {n - 1:[n]}
for i in range(n - 2, -1, -1):
if A[i] == -1:
continue
mn, preIndex = float("inf"), None
for ind in range(i + 1, i + B + 1 <= n and i + B + 1 or n):
... | class Solution:
def cheapest_jump(self, A, B):
n = len(A)
pre_min = {n - 1: [n]}
for i in range(n - 2, -1, -1):
if A[i] == -1:
continue
(mn, pre_index) = (float('inf'), None)
for ind in range(i + 1, i + B + 1 <= n and i + B + 1 or n):
... |
non_valid_licenses_rdf = """@prefix odrl: <http://www.w3.org/ns/odrl/2/> .
@prefix cc: <http://creativecommons.org/ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
<http://example.org/License/1> a odrl:Policy ;
rdfs:label "not valid:CommercialUse should not be a Duty" ;
odrl:Duty cc:Notice,
... | non_valid_licenses_rdf = '@prefix odrl: <http://www.w3.org/ns/odrl/2/> .\n@prefix cc: <http://creativecommons.org/ns#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n<http://example.org/License/1> a odrl:Policy ;\n rdfs:label "not valid:CommercialUse should not be a Duty" ;\n odrl:Duty cc:Notice,\n... |
# -*- coding: utf-8 -*-
""" Python package of code for Gaussian process classification experiments. """
__authors__ = 'Matt Graham'
__copyright__ = 'Copyright 2015, Matt Graham'
__license__ = 'MIT'
| """ Python package of code for Gaussian process classification experiments. """
__authors__ = 'Matt Graham'
__copyright__ = 'Copyright 2015, Matt Graham'
__license__ = 'MIT' |
# -*- encoding: utf-8 -*-
# ! python3
default_app_config = 'web.apps.WebAppConfig'
| default_app_config = 'web.apps.WebAppConfig' |
#!/usr/bin/env python
ref_file = open('../../../result/PhastCons46Ways_miRBase_v21_hg38Tohg19_kmeans5_2015-07-17.txt','r')
input_file = open('../../../data/mirMark/S1_site-level_human_miRNA-target_site_pairs_from_miRecords_id-seq.txt','r')
output_file = open('../../../result/PhastCons46Ways_miRBase_v21_hg38Tohg19_... | ref_file = open('../../../result/PhastCons46Ways_miRBase_v21_hg38Tohg19_kmeans5_2015-07-17.txt', 'r')
input_file = open('../../../data/mirMark/S1_site-level_human_miRNA-target_site_pairs_from_miRecords_id-seq.txt', 'r')
output_file = open('../../../result/PhastCons46Ways_miRBase_v21_hg38Tohg19_with_miRecords_kmeans5_20... |
# https://www.codewars.com/kata/array-mash/python
def array_mash(a, b):
mesh = []
for one, two in zip(a, b):
mesh.extend([one, two])
return mesh
| def array_mash(a, b):
mesh = []
for (one, two) in zip(a, b):
mesh.extend([one, two])
return mesh |
DEBUG = False
# specify which folder in the static_folder is used to store essays
ESSAY_RESOURCE_FOLDER = 'essay_resources'
HOST = '127.0.0.1'
PORT = 8000
| debug = False
essay_resource_folder = 'essay_resources'
host = '127.0.0.1'
port = 8000 |
class Stack:
# Constructor
def __init__(self):
self.collection = []
# Append data on the top of the stack
def push(self, data):
self.collection.append(data)
# Remove and return the last item on the top of the stack
def pop(self):
return self.collection.pop()
... | class Stack:
def __init__(self):
self.collection = []
def push(self, data):
self.collection.append(data)
def pop(self):
return self.collection.pop()
def peek(self):
return self.collection[len(self.collection) - 1]
def size(self):
return len(self.collectio... |
#
# Tutt library III location codes
#
FULL_CODE_MAP = {
'dacc': 'Digital Archives of Colorado College',
'ewww':'Online',
'ewwwd':'Online Government Documents',
'ewwwp':'Online Periodcals',
'ewwwn':'Online',
'tarf':'Tutt Reference',
'tarfa':'Tutt 1st Floor South',
'tarfc':'Tutt Reference... | full_code_map = {'dacc': 'Digital Archives of Colorado College', 'ewww': 'Online', 'ewwwd': 'Online Government Documents', 'ewwwp': 'Online Periodcals', 'ewwwn': 'Online', 'tarf': 'Tutt Reference', 'tarfa': 'Tutt 1st Floor South', 'tarfc': 'Tutt Reference', 'tarfd': 'Tutt Reference Desk', 'tarfg': 'Tutt Reference Desk'... |
def isDigit(string):
#11ELF
try:
float(string)
except ValueError:
try:
complex(string)
except ValueError:
return False
return True | def is_digit(string):
try:
float(string)
except ValueError:
try:
complex(string)
except ValueError:
return False
return True |
#!/usr/bin/env python
# API Header parameter
header_param_name = 'project_id'
# Blockfrost Network URL
bf_url_cardano_mainnet = 'https://cardano-mainnet.blockfrost.io/api/v0/'
bf_url_cardano_testnet = 'https://cardano-testnet.blockfrost.io/api/v0/'
# Blockfrost Stake URL
bf_stake_url = 'accounts/'
bf_stake_rewards_u... | header_param_name = 'project_id'
bf_url_cardano_mainnet = 'https://cardano-mainnet.blockfrost.io/api/v0/'
bf_url_cardano_testnet = 'https://cardano-testnet.blockfrost.io/api/v0/'
bf_stake_url = 'accounts/'
bf_stake_rewards_url = '/rewards'
bf_stake_amount_history_url = '/history'
bf_stake_delegation_url = '/delegations... |
def crop_to_square(x):
crop_width, remainder = divmod(abs(x.shape[0] - x.shape[1]), 2)
if x.shape[0] < x.shape[1]:
return x[:, crop_width : x.shape[1] - crop_width - remainder]
else:
return x[crop_width : x.shape[0] - crop_width - remainder]
| def crop_to_square(x):
(crop_width, remainder) = divmod(abs(x.shape[0] - x.shape[1]), 2)
if x.shape[0] < x.shape[1]:
return x[:, crop_width:x.shape[1] - crop_width - remainder]
else:
return x[crop_width:x.shape[0] - crop_width - remainder] |
#!/usr/bin/env python
# software from PDBe: Protein Data Bank in Europe; https://pdbe.org
#
# Copyright 2018 EMBL - European Bioinformatics Institute
# 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 Licens... | def str_to_int(i):
"""
Converts a string into integer. Returns 0 if a string cannot be
converted.
Args:
i (str): string representation of an integer
Returns:
int: conversion of the string
"""
try:
return int(i)
except ValueError:
return 0
def str_to_flo... |
class Card:
SUIT_SYMBOLS = {
0: u"\u2666", # diamonds
1: u"\u2665", # hearts
2: u"\u2663", # clubs
3: u"\u2660" # spades
}
VALUE_NAMES = {
1: "A",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
... | class Card:
suit_symbols = {0: u'♦', 1: u'♥', 2: u'♣', 3: u'♠'}
value_names = {1: 'A', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'T', 11: 'J', 12: 'Q', 13: 'K'}
def __init__(self):
pass
def __str__(self):
pass |
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# Write a program that determines whether a year with a given
# number ends with two zeros. If the year ends, then output "YES",
# otherwise output "NO".Write a program that determines whether
# a year wi... | def is_century_beginning(year: int) -> bool:
return year % 10 == year % 100 // 10 == 0
def check_year(year: int) -> str:
if is_century_beginning(year):
return 'YES'
return 'NO'
if __name__ == '__main__':
print(check_year(int(input()))) |
class Banner:
TEXT = """
________________________________________________________________________________
'####:'##::: ##::'#######::'####::'######::
. ##:: ###:: ##:'##.... ##:. ##::'##... ##:
: ##:: ####: ##: ##:::: ##:: ##:: ##:::..::
: ##:: ## ## ##: ##:::: ##:: ##::. ######::
: ##:: ##. ####: ##:::: ##:: ##:... | class Banner:
text = "\n________________________________________________________________________________\n\n'####:'##::: ##::'#######::'####::'######::\n. ##:: ###:: ##:'##.... ##:. ##::'##... ##:\n: ##:: ####: ##: ##:::: ##:: ##:: ##:::..::\n: ##:: ## ## ##: ##:::: ##:: ##::. ######::\n: ##:: ##. ####: ##:::: ##::... |
# -*- coding: utf-8 -*-
@auth.requires_login()
def index():
return locals()
@auth.requires_login()
def cadastrar_medicamento():
form = SQLFORM(db.lista_medicamentos)
if form.process().accepted:
id = form.vars.id
redirect(URL(c='admin', f='ver_medicamento', args=id), client_side=True)
... | @auth.requires_login()
def index():
return locals()
@auth.requires_login()
def cadastrar_medicamento():
form = sqlform(db.lista_medicamentos)
if form.process().accepted:
id = form.vars.id
redirect(url(c='admin', f='ver_medicamento', args=id), client_side=True)
return locals()
@auth.req... |
#!/usr/bin/env python3
path_on_servers = '~/.dcp'
setup_cache = '.cache_setup'
listener_py = 'dcp/http_listener.py'
listener_deps = ['dcp/actions.py']
| path_on_servers = '~/.dcp'
setup_cache = '.cache_setup'
listener_py = 'dcp/http_listener.py'
listener_deps = ['dcp/actions.py'] |
n=int(input("Enter the number"))
ls=[]
ls1=[]
co=0
for i in range(n):
ls.append(input())
if len(ls) == len(set(ls)):
print("No Repeated Values here")
else:
le=len(ls)
for i in range(le-1):
for j in range(i+1,le):
if ls[i]==ls[j]:
ls1.append(ls[j])
... | n = int(input('Enter the number'))
ls = []
ls1 = []
co = 0
for i in range(n):
ls.append(input())
if len(ls) == len(set(ls)):
print('No Repeated Values here')
else:
le = len(ls)
for i in range(le - 1):
for j in range(i + 1, le):
if ls[i] == ls[j]:
ls1.append(ls[j])
... |
# arrays are indexed (their conetnts get assigned a number)
# the index always starts at 0
choices = ["rock", "paper", "scissors"]
player_lives = 3
computer_lives = 3
total_lives = 3
#True and False are Boolen data types -> they are the equivalent of on or off, 1 or 0
player = False | choices = ['rock', 'paper', 'scissors']
player_lives = 3
computer_lives = 3
total_lives = 3
player = False |
def merge(a: list, b: list) -> list:
"""Merges B into A in sorted order
a is modified in place and also returned
Args:
a: sorted list with enough buffer at the end to hold b
b: sorted list
Returns:
A single sorted list
"""
end_b = len(b) - 1
for idx, val in enumera... | def merge(a: list, b: list) -> list:
"""Merges B into A in sorted order
a is modified in place and also returned
Args:
a: sorted list with enough buffer at the end to hold b
b: sorted list
Returns:
A single sorted list
"""
end_b = len(b) - 1
for (idx, val) in enume... |
class Signal:
"""A convinience class that encapsulates a signal in order to
be used in the DisconnectedSignals context manager
"""
def __init__(self, signal, receiver, sender):
self.signal = signal
self.receiver = receiver
self.sender = sender
def connect(self):
... | class Signal:
"""A convinience class that encapsulates a signal in order to
be used in the DisconnectedSignals context manager
"""
def __init__(self, signal, receiver, sender):
self.signal = signal
self.receiver = receiver
self.sender = sender
def connect(self):
... |
class UiGroup(object):
def __init__(self):
self.elements = []
def add_element(self, element):
self.elements.append(element)
def set_visible(self, value):
for e in self.elements:
e.set_visible(value)
def inputs(self, events):
for e in self.elements:
... | class Uigroup(object):
def __init__(self):
self.elements = []
def add_element(self, element):
self.elements.append(element)
def set_visible(self, value):
for e in self.elements:
e.set_visible(value)
def inputs(self, events):
for e in self.elements:
... |
class Solution:
def validPalindrome(self, s: str) -> bool:
def verify(s, left, right, counter=0):
while left < right:
if s[left] != s[right]:
if counter == 1:
return False
return verify(s, left+1, right, counter+1) o... | class Solution:
def valid_palindrome(self, s: str) -> bool:
def verify(s, left, right, counter=0):
while left < right:
if s[left] != s[right]:
if counter == 1:
return False
return verify(s, left + 1, right, counter... |
def factorial(n):
result = 1
for number in range(1, n + 1):
result *= number
return result
# nPr = n! / (n - r)!
# 4 r=2
def permutation(n, r):
return factorial(n) // factorial(n - r)
# nCr = nPr / r!
def combination(n, r):
return permutation(n, r) // factorial(r)
print(combination(4, ... | def factorial(n):
result = 1
for number in range(1, n + 1):
result *= number
return result
def permutation(n, r):
return factorial(n) // factorial(n - r)
def combination(n, r):
return permutation(n, r) // factorial(r)
print(combination(4, 0))
print(combination(4, 1))
print(combination(4, 2... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python [conda env:bandit_38]
# language: python
# name: conda-env-bandi... | work_dir = '/Users/pnorton/Projects/National_Hydrology_Model/src/tests_prms6/sagehen/input/prms'
filename = f'{work_dir}/prms_orig.params'
new_file = f'{work_dir}/prms_orig_v2.params'
fhdl = open(filename, 'r')
rawdata = fhdl.read().splitlines()
fhdl.close()
it = iter(rawdata)
out_fhdl = open(new_file, 'w')
for line in... |
#
# PySNMP MIB module INTELCORPORATIONSERVERHEALTH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATIONSERVERHEALTH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:55:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 02:58:39 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
03.5-Finger Apply to Each 01
-----------------------------
Here is the code for a function applyToEach:
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
Assume tha... | """
Created on Mon Oct 7 02:58:39 2019
@author: sodatab
MITx: 6.00.1x
"""
'\n03.5-Finger Apply to Each 01\n-----------------------------\n Here is the code for a function applyToEach:\n\ndef applyToEach(L, f):\n for i in range(len(L)):\n L[i] = f(L[i])\n\nAssume that\n\ntestList = [1, -4, 8, -9]\n\nFor eac... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | def triangle(a, b, c):
sides = sorted([a, b, c])
set_len = len(set(sides))
if sides[0] < 1:
raise TriangleError
elif sides[0] + sides[1] < sides[2]:
raise TriangleError
if set_len == 1:
return 'equilateral'
elif set_len == 2:
return 'isosceles'
return 'scalene... |
# -*- coding: utf-8 -*-
"""Top-level package for hello-cc."""
__author__ = """lin zhang"""
__email__ = 'audreyr@example.com'
__version__ = '0.1.0'
| """Top-level package for hello-cc."""
__author__ = 'lin zhang'
__email__ = 'audreyr@example.com'
__version__ = '0.1.0' |
def f(items):
items.append(100)
def g(items):
items.append(items.pop() * 2)
def h(items):
items.extend([items.pop()] * 10)
| def f(items):
items.append(100)
def g(items):
items.append(items.pop() * 2)
def h(items):
items.extend([items.pop()] * 10) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#ENSEMBLES keep function
def keep_ensembles(i, ensemble_results, results, ensemble_target, target, ensemble_patient, patient):
if i==0:
return ensemble_results.append(results), ensemble_target.append(target), ensemble_patient.append(patient)
else:
... | def keep_ensembles(i, ensemble_results, results, ensemble_target, target, ensemble_patient, patient):
if i == 0:
return (ensemble_results.append(results), ensemble_target.append(target), ensemble_patient.append(patient))
else:
return (ensemble_results.append(results), ensemble_target, ensemble_p... |
# Given an array of distinct integers candidates and a target integer target,
# return a list of all unique combinations of candidates where the chosen numbers sum to target.
# You may return the combinations in any order.
# The same number may be chosen from candidates an unlimited number of times.
# Two combinati... | class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
return self.appendCombos(candidates, target, [], [])
def append_combos(self, candidates: List[int], target: int, comb, node):
if target < 0:
return
if target == 0:
... |
class InstallmentForm(object):
def __init__(self):
pass
def media(self):
pass
def static(self):
pass
| class Installmentform(object):
def __init__(self):
pass
def media(self):
pass
def static(self):
pass |
"""
Execute following command to ignore local changes on this file
$ git update-index --skip-worktree tests/tokens.py
Execute following command to track local changes on this file again
$ git update-index --no-skip-worktree tests/tokens.py
"""
API_TOKEN = '<Your API token>'
MESSENGER_HOOK_URL = '<Your hook url>'
| """
Execute following command to ignore local changes on this file
$ git update-index --skip-worktree tests/tokens.py
Execute following command to track local changes on this file again
$ git update-index --no-skip-worktree tests/tokens.py
"""
api_token = '<Your API token>'
messenger_hook_url = '<Your hook url>' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.