content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class handshake:
def clientside(Socket_Object):
"""This must be called with the main object from the socket"""
pass#Socket_Object.
| class Handshake:
def clientside(Socket_Object):
"""This must be called with the main object from the socket"""
pass |
#!/usr/bin/python3
# Can user retrieve reward after a time cycle?
def test_get_reward(multi, base_token, reward_token, alice, issue, chain):
amount = 10 ** 10
init_reward_balance = reward_token.balanceOf(alice)
base_token.approve(multi, amount, {"from": alice})
multi.stake(amount, {"from": alice})
... | def test_get_reward(multi, base_token, reward_token, alice, issue, chain):
amount = 10 ** 10
init_reward_balance = reward_token.balanceOf(alice)
base_token.approve(multi, amount, {'from': alice})
multi.stake(amount, {'from': alice})
chain.mine(timedelta=60)
earnings = multi.earned(alice, reward_... |
data = (
'ddwim', # 0x00
'ddwib', # 0x01
'ddwibs', # 0x02
'ddwis', # 0x03
'ddwiss', # 0x04
'ddwing', # 0x05
'ddwij', # 0x06
'ddwic', # 0x07
'ddwik', # 0x08
'ddwit', # 0x09
'ddwip', # 0x0a
'ddwih', # 0x0b
'ddyu', # 0x0c
'ddyug', # 0x0d
'ddyugg', # 0x0e
'ddyugs', # 0x0f
'dd... | data = ('ddwim', 'ddwib', 'ddwibs', 'ddwis', 'ddwiss', 'ddwing', 'ddwij', 'ddwic', 'ddwik', 'ddwit', 'ddwip', 'ddwih', 'ddyu', 'ddyug', 'ddyugg', 'ddyugs', 'ddyun', 'ddyunj', 'ddyunh', 'ddyud', 'ddyul', 'ddyulg', 'ddyulm', 'ddyulb', 'ddyuls', 'ddyult', 'ddyulp', 'ddyulh', 'ddyum', 'ddyub', 'ddyubs', 'ddyus', 'ddyuss', ... |
"""Static key/seed for keystream generation"""
ACP_STATIC_KEY = "5b6faf5d9d5b0e1351f2da1de7e8d673".decode("hex")
def generate_acp_keystream(length):
"""Get key used to encrypt the header key (and some message data?)
Args:
length (int): length of keystream to generate
Returns:
String of requested length
N... | """Static key/seed for keystream generation"""
acp_static_key = '5b6faf5d9d5b0e1351f2da1de7e8d673'.decode('hex')
def generate_acp_keystream(length):
"""Get key used to encrypt the header key (and some message data?)
Args:
length (int): length of keystream to generate
Returns:
String of requested length
... |
"""RCON exceptions."""
__all__ = ['InvalidPacketStructure', 'RequestIdMismatch', 'InvalidCredentials']
class InvalidPacketStructure(Exception):
"""Indicates an invalid packet structure."""
class RequestIdMismatch(Exception):
"""Indicates that the sent and received request IDs do not match."""
def __i... | """RCON exceptions."""
__all__ = ['InvalidPacketStructure', 'RequestIdMismatch', 'InvalidCredentials']
class Invalidpacketstructure(Exception):
"""Indicates an invalid packet structure."""
class Requestidmismatch(Exception):
"""Indicates that the sent and received request IDs do not match."""
def __init_... |
def build_mx(n, m):
grid = []
for i in range(n):
grid.append([' '] * m)
return grid
def EMPTY_SHAPE():
return [[]]
class Shape(object):
_name = None
grid = EMPTY_SHAPE()
rotate_grid = []
def __init__(self, grid):
# align each row and column is same
n = len(gri... | def build_mx(n, m):
grid = []
for i in range(n):
grid.append([' '] * m)
return grid
def empty_shape():
return [[]]
class Shape(object):
_name = None
grid = empty_shape()
rotate_grid = []
def __init__(self, grid):
n = len(grid)
m = max([len(row) for row in grid]... |
def cal_average(num):
i = 0
for x in num:
i += x
avg = i / len(num)
return avg
cal_average([1,2,3,4]) | def cal_average(num):
i = 0
for x in num:
i += x
avg = i / len(num)
return avg
cal_average([1, 2, 3, 4]) |
#!/use/bin/python3
__author__ = 'yangdd'
'''
example 024
'''
a = 2
b =1
total = 0.0
for i in range(1,21):
total += a/b
a,b=a+b,a
print(total)
| __author__ = 'yangdd'
'\n\texample 024\n'
a = 2
b = 1
total = 0.0
for i in range(1, 21):
total += a / b
(a, b) = (a + b, a)
print(total) |
#
# PySNMP MIB module RFC1285-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1285-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:48:17 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, 0... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, constraints_union, value_size_constraint) ... |
grey_image = np.mean(image, axis=-1)
print("Shape: {}".format(grey_image.shape))
print("Type: {}".format(grey_image.dtype))
print("image size: {:0.3} MB".format(grey_image.nbytes / 1e6))
print("Min: {}; Max: {}".format(grey_image.min(), grey_image.max()))
plt.imshow(grey_image, cmap=plt.cm.Greys_r)
| grey_image = np.mean(image, axis=-1)
print('Shape: {}'.format(grey_image.shape))
print('Type: {}'.format(grey_image.dtype))
print('image size: {:0.3} MB'.format(grey_image.nbytes / 1000000.0))
print('Min: {}; Max: {}'.format(grey_image.min(), grey_image.max()))
plt.imshow(grey_image, cmap=plt.cm.Greys_r) |
def start_HotSpot(ssid="Hovercraft",encrypted=False,passd="1234",iface="wlan0"):
print("HotSpot %s encrypt %s with Pass %s on Interface %s",ssid,encrypted,passd,iface)
def stop_HotSpot():
print("HotSpot stopped")
| def start__hot_spot(ssid='Hovercraft', encrypted=False, passd='1234', iface='wlan0'):
print('HotSpot %s encrypt %s with Pass %s on Interface %s', ssid, encrypted, passd, iface)
def stop__hot_spot():
print('HotSpot stopped') |
n = int(input())
left_side = 0
right_side = 0
for i in range(n):
num = int(input())
left_side += num
for i in range(n):
num = int(input())
right_side += num
if left_side == right_side:
print(f"Yes, sum = {left_side}")
else:
print(f"No, diff = {abs(left_side - right_side)}")
| n = int(input())
left_side = 0
right_side = 0
for i in range(n):
num = int(input())
left_side += num
for i in range(n):
num = int(input())
right_side += num
if left_side == right_side:
print(f'Yes, sum = {left_side}')
else:
print(f'No, diff = {abs(left_side - right_side)}') |
#
# PySNMP MIB module CTRON-PRIORITY-CLASSIFY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-PRIORITY-CLASSIFY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:30:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
DESCRIPTION = "switch to a different module"
def autocomplete(shell, line, text, state):
# todo: make this show shorter paths at a time
# should never go this big...
if len(line.split()) > 2 and line.split()[0] != "set":
return None
options = [x + " " for x in shell.plugins if x.startswith(tex... | description = 'switch to a different module'
def autocomplete(shell, line, text, state):
if len(line.split()) > 2 and line.split()[0] != 'set':
return None
options = [x + ' ' for x in shell.plugins if x.startswith(text)]
try:
return options[state]
except:
return None
def help(s... |
# test builtin issubclass
class A:
pass
print(issubclass(A, A))
print(issubclass(A, (A,)))
try:
issubclass(A, 1)
except TypeError:
print('TypeError')
try:
issubclass('a', 1)
except TypeError:
print('TypeError')
| class A:
pass
print(issubclass(A, A))
print(issubclass(A, (A,)))
try:
issubclass(A, 1)
except TypeError:
print('TypeError')
try:
issubclass('a', 1)
except TypeError:
print('TypeError') |
def install(job):
prefab = job.service.executor.prefab
# For now we download FS from there. when we have proper VM image it will be installed already
if not prefab.core.command_check('fs'):
prefab.core.dir_ensure('$BINDIR')
prefab.core.file_download('https://stor.jumpscale.org/public/fs', '... | def install(job):
prefab = job.service.executor.prefab
if not prefab.core.command_check('fs'):
prefab.core.dir_ensure('$BINDIR')
prefab.core.file_download('https://stor.jumpscale.org/public/fs', '$BINDIR/fs')
prefab.core.file_attribs('$BINDIR/fs', '0550')
def start(job):
prefab = jo... |
# Gianna-Carina Gruen
# 05/23/2016
# Homework 1
# 1. Prompt the user for their year of birth, and tell them (approximately):
year_of_birth = input ("Hello! I'm not interested in your name, but I would like to know your age. In what year were you born?")
# Additionally, if someone gives you a year in the futu... | year_of_birth = input("Hello! I'm not interested in your name, but I would like to know your age. In what year were you born?")
if int(year_of_birth) >= 2016:
year_of_birth = input('I seriously doubt that - you get another chance. Tell me the truth this time. In what year where you born?')
age = 2016 - int(year_of_... |
class Solution:
def removePalindromeSub(self, s: str) -> int:
# exception
if s == '':
return 0
elif s == s[::-1]:
return 1
else:
return 2
| class Solution:
def remove_palindrome_sub(self, s: str) -> int:
if s == '':
return 0
elif s == s[::-1]:
return 1
else:
return 2 |
#!/usr/bin/env python
# coding=utf-8
class startURL:
xinfangURL = [
'http://cs.ganji.com/fang12/o1/',
'http://cs.ganji.com/fang12/o2/',
'http://cs.ganji.com/fang12/o3/',
'http://cs.ganji.com/fang12/o4/',
'http://cs.ganji.com/fang12/o5/',
'http://cs.ganji.com/fang12/o... | class Starturl:
xinfang_url = ['http://cs.ganji.com/fang12/o1/', 'http://cs.ganji.com/fang12/o2/', 'http://cs.ganji.com/fang12/o3/', 'http://cs.ganji.com/fang12/o4/', 'http://cs.ganji.com/fang12/o5/', 'http://cs.ganji.com/fang12/o6/', 'http://cs.ganji.com/fang12/o7/', 'http://cs.ganji.com/fang12/o8/', 'http://cs.ga... |
# File: hackerone_consts.py
# Copyright (c) 2020-2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
# Constants for actions
ACTION_ID_GET_ALL = 'get_reports'
ACTION_ID_GET_UPDATED = 'get_updated_reports'
ACTION_ID_GET_ONE = 'get_report'
ACTION_ID_UPDATE = 'update_id'
ACTI... | action_id_get_all = 'get_reports'
action_id_get_updated = 'get_updated_reports'
action_id_get_one = 'get_report'
action_id_update = 'update_id'
action_id_unassign = 'unassign'
action_id_on_poll = 'on_poll'
action_id_test = 'test_asset_connectivity'
action_id_get_bounty_balance = 'get_bounty_balance'
action_id_get_billi... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
pre_n_th = n... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def remove_nth_from_end(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
pre_n_th = n_th = tail = head
i = 0
... |
# -*- coding: utf-8 -*-
# Author: Daniel Yang <daniel.yj.yang@gmail.com>
#
# License: BSD-3-Clause
__version__ = "0.0.6"
__license__ = "BSD-3-Clause License"
| __version__ = '0.0.6'
__license__ = 'BSD-3-Clause License' |
##n=int(input("enter a number:"))
##i=1
##
##count=0
##while(i<n):
## if(n%i==0):
## count=count+1
##
## i=i+1
##if(count<=2):
## print("prime")
##else:
## print("not")
i=2
j=2
while(i<=10):
while(j<i):
if(i%j==0):
break;
else:
print(i)
... | i = 2
j = 2
while i <= 10:
while j < i:
if i % j == 0:
break
else:
print(i)
j += 1
i += 1 |
for m in range(1,1000):
for n in range(m+1,1000):
c=1000-m-n
if c**2==(m**2+n**2):
print('The individual numbers a,b,c respectively are',m,n,c,'the product of abc is',m*n*c)
| for m in range(1, 1000):
for n in range(m + 1, 1000):
c = 1000 - m - n
if c ** 2 == m ** 2 + n ** 2:
print('The individual numbers a,b,c respectively are', m, n, c, 'the product of abc is', m * n * c) |
{
'target_defaults': {
'includes': ['../common-mk/common.gypi'],
'variables': {
'deps': [
'protobuf',
],
},
},
'targets': [
{
'target_name': 'media_perception_protos',
'type': 'static_library',
'variables': {
'proto_in_dir': 'proto/',
'proto_ou... | {'target_defaults': {'includes': ['../common-mk/common.gypi'], 'variables': {'deps': ['protobuf']}}, 'targets': [{'target_name': 'media_perception_protos', 'type': 'static_library', 'variables': {'proto_in_dir': 'proto/', 'proto_out_dir': 'include/media_perception'}, 'sources': ['<(proto_in_dir)/device_management.proto... |
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
# bastardized version of DFS
# if we are out of bounds return false
# else check to left and right
# same idea as sinking islands where we remove visited for current recurse
left, right ... | class Solution:
def can_reach(self, arr: List[int], start: int) -> bool:
(left, right) = (0, len(arr))
def dfs(i):
if i < left or i >= right or arr[i] < 0:
return False
if arr[i] == 0:
return True
arr[i] = -arr[i]
poss... |
class Queue:
def __init__(self, maxsize):
self.__max_size = maxsize
self.__elements = [None] * self.__max_size
self.__rear = -1
self.__front = 0
def getMaxSize(self):
return self.__max_size
def isFull(self):
return self.__rear == self.__max_size
def isE... | class Queue:
def __init__(self, maxsize):
self.__max_size = maxsize
self.__elements = [None] * self.__max_size
self.__rear = -1
self.__front = 0
def get_max_size(self):
return self.__max_size
def is_full(self):
return self.__rear == self.__max_size
def... |
def HammingDistance(p, q):
mm = [p[i] != q[i] for i in range(len(p))]
return sum(mm)
# def ImmediateNeighbors(Pattern):
# Neighborhood = [Pattern]
# for i in range(len(Pattern)):
# nuc = Pattern[i]
# for nuc2 in ['A', 'C', 'G', 'T']:
# if nuc != nuc2:
# pat =... | def hamming_distance(p, q):
mm = [p[i] != q[i] for i in range(len(p))]
return sum(mm)
def neighbors(Pattern, d):
if d == 0:
return Pattern
if len(Pattern) == 1:
return ['A', 'C', 'G', 'T']
neighborhood = set()
suffix_neighbors = neighbors(Pattern[1:], d)
for text in SuffixNe... |
'''
Description:
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,... | """
Description:
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,... |
"""
This is a modelmanager settings file.
Import or define your settings variables, functions or classes below.
For example:
```
# will only be available here
import pandas as example_module
from pandas.some_module import some_function as _pandas_function
# will be available as project.example_variable
example_varia... | """
This is a modelmanager settings file.
Import or define your settings variables, functions or classes below.
For example:
```
# will only be available here
import pandas as example_module
from pandas.some_module import some_function as _pandas_function
# will be available as project.example_variable
example_varia... |
"""
Given array of integers lengths, create an array of arrays output such that output[i] consists of lengths[i] elements and output[i][j] = j.
Example
For lengths = [1, 2, 0, 4], the output should be
create2DArray(lengths) = [[0],
[0, 1],
[],
... | """
Given array of integers lengths, create an array of arrays output such that output[i] consists of lengths[i] elements and output[i][j] = j.
Example
For lengths = [1, 2, 0, 4], the output should be
create2DArray(lengths) = [[0],
[0, 1],
[],
... |
# model settings
model = dict(
type='Classification',
pretrained=None,
backbone=dict(
type='MobileNetV3',
arch='large',
out_indices=(16,), # x-1: stage-x
norm_cfg=dict(type='BN', eps=0.001, momentum=0.01),
),
head=dict(
type='ClsHead',
loss=dict(type=... | model = dict(type='Classification', pretrained=None, backbone=dict(type='MobileNetV3', arch='large', out_indices=(16,), norm_cfg=dict(type='BN', eps=0.001, momentum=0.01)), head=dict(type='ClsHead', loss=dict(type='CrossEntropyLoss', loss_weight=1.0), with_avg_pool=True, in_channels=960, num_classes=1000)) |
"""
API for yt.frontends.gamer
"""
| """
API for yt.frontends.gamer
""" |
# Generate permutations with a space
def permutation_with_space_helper(input_val, output_val):
if len(input_val) == 0:
# Base condition to get a final output once the input string is empty
final.append(output_val)
return
# Store the first element of the string and make decisions on it ... | def permutation_with_space_helper(input_val, output_val):
if len(input_val) == 0:
final.append(output_val)
return
temp = input_val[0]
permutation_with_space_helper(input_val[1:], output_val + temp)
permutation_with_space_helper(input_val[1:], output_val + '_' + temp)
def permutation_wit... |
"""Skeleton for 'itertools' stdlib module."""
class islice(object):
def __init__(self, iterable, start, stop=None, step=None):
"""
:type iterable: collections.Iterable[T]
:type start: numbers.Integral
:type stop: numbers.Integral | None
:type step: numbers.Integral | None
... | """Skeleton for 'itertools' stdlib module."""
class Islice(object):
def __init__(self, iterable, start, stop=None, step=None):
"""
:type iterable: collections.Iterable[T]
:type start: numbers.Integral
:type stop: numbers.Integral | None
:type step: numbers.Integral | None
... |
EXAMPLE_DOCS = [ # Collection stored as "docs"
{
'_data': 'one two',
'_type': 'http://sharejs.org/types/textv1',
'_v': 8,
'_m': {
'mtime': 1415654366808,
'ctime': 1415654358668
},
'_id': '26aabd89-541b-5c02-9e6a-ad332ba43118'
},
{
... | example_docs = [{'_data': 'one two', '_type': 'http://sharejs.org/types/textv1', '_v': 8, '_m': {'mtime': 1415654366808, 'ctime': 1415654358668}, '_id': '26aabd89-541b-5c02-9e6a-ad332ba43118'}, {'_data': 'XXX', '_type': 'http://sharejs.org/types/textv1', '_v': 4, '_m': {'mtime': 1415654385628, 'ctime': 1415654381131}, ... |
def insert_line(file, text, after=None, before=None, past=None, once=True):
with open(file) as f:
lines = iter(f.readlines())
with open(file, 'w') as f:
if past:
for line in lines:
f.write(line)
if re.match(past, line):
break
... | def insert_line(file, text, after=None, before=None, past=None, once=True):
with open(file) as f:
lines = iter(f.readlines())
with open(file, 'w') as f:
if past:
for line in lines:
f.write(line)
if re.match(past, line):
break
... |
count = int(input())
tux = [" _~_ ", " (o o) ", " / V \ ", "/( _ )\\ ", " ^^ ^^ "]
for i in tux:
print(i * count)
| count = int(input())
tux = [' _~_ ', ' (o o) ', ' / V \\ ', '/( _ )\\ ', ' ^^ ^^ ']
for i in tux:
print(i * count) |
class Node():
'''
The DiNode class is specifically designed for altering path search.
- Active and passive out nodes, for easily iteratively find new nodes in path.
- Marks for easy look up edges already visited (earlier Schlaufen) / nodes in path-creation already visited
- The edge-marks have t... | class Node:
"""
The DiNode class is specifically designed for altering path search.
- Active and passive out nodes, for easily iteratively find new nodes in path.
- Marks for easy look up edges already visited (earlier Schlaufen) / nodes in path-creation already visited
- The edge-marks have the... |
class Point2D:
def __init__(self,x,y):
self.x = x
self.y = y
def __eq__(self, value):
return self.x == value.x and self.y == value.y
def __hash__(self):
return hash((self.x,self.y)) | class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, value):
return self.x == value.x and self.y == value.y
def __hash__(self):
return hash((self.x, self.y)) |
"""
This is pure Python implementation of linear search algorithm
For doctests run following command:
python3 -m doctest -v linear_search.py
For manual testing run:
python3 linear_search.py
"""
def linear_search(sequence: list, target: int) -> int:
"""A pure Python implementation of a linear search ... | """
This is pure Python implementation of linear search algorithm
For doctests run following command:
python3 -m doctest -v linear_search.py
For manual testing run:
python3 linear_search.py
"""
def linear_search(sequence: list, target: int) -> int:
"""A pure Python implementation of a linear search algorithm
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, a, b):
if a is None:
return b
if b is None:
return a
if a.val > b.va... | class Solution:
def merge_two_lists(self, a, b):
if a is None:
return b
if b is None:
return a
if a.val > b.val:
(a, b) = (b, a)
result = a
result_head = result
a = a.next
while a is not None or b is not None:
a... |
"""
package information : Core package
Author: Shanmugathas Vigneswaran
email: shanmugathas.vigneswaran@outlook.fr
Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
Licence: https://creativecommons.org/licenses/by-nc/4.0/
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING,
LICENSOR OFFERS THE WO... | """
package information : Core package
Author: Shanmugathas Vigneswaran
email: shanmugathas.vigneswaran@outlook.fr
Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
Licence: https://creativecommons.org/licenses/by-nc/4.0/
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING,
LICENSOR OFFERS THE WO... |
# DEFAULT_ASSET_URL="https://totogoto.com/assets/python_project/images/"
DEFAULT_ASSET_URL="https://cdn.jsdelivr.net/gh/totogoto/assets/"
DEFAULT_OBJECTS = [
"1",
"2",
"3",
"4",
"5",
"apple_goal",
"apple",
"around3_sol",
"banana_goal",
"banana",
"beeper_goal",
"box_goal",... | default_asset_url = 'https://cdn.jsdelivr.net/gh/totogoto/assets/'
default_objects = ['1', '2', '3', '4', '5', 'apple_goal', 'apple', 'around3_sol', 'banana_goal', 'banana', 'beeper_goal', 'box_goal', 'box', 'bricks', 'bridge', 'carrot_goal', 'carrot', 'daisy_goal', 'daisy', 'dandelion_goal', 'dandelion', 'desert', 'ea... |
def main():
with open('test.txt','rt') as infile:
test2 = infile.read()
test1 ='This is a test of the emergency text system'
print(test1 == test2)
if __name__ == '__main__':
main()
| def main():
with open('test.txt', 'rt') as infile:
test2 = infile.read()
test1 = 'This is a test of the emergency text system'
print(test1 == test2)
if __name__ == '__main__':
main() |
# Enter your code here. Read input from STDIN. Print output to STDOUT
testCases = int(input())
for i in range(testCases):
word = input()
for j in range(len(word)):
if j%2 == 0:
print(word[j], end='')
print(" ", end="")
for j in range(len(word)):
if j%2 !=... | test_cases = int(input())
for i in range(testCases):
word = input()
for j in range(len(word)):
if j % 2 == 0:
print(word[j], end='')
print(' ', end='')
for j in range(len(word)):
if j % 2 != 0:
print(word[j], end='')
print('') |
#
# gambit
#
# This file contains the information to make the mesh for a subset of the original point data set.
#
#
# The original data sets are in csv format and are for 6519 observation points.
# 1. `Grav_MeasEs.csv` contains the cartesian coordinates of the observation points (m).
# 2. `Grav_gz.csv` contains the Bou... | big_gravity_data_file = 'Grav_gz.csv'
big_acc_data_file = 'Grav_acc.csv'
big_obs_pts_file = 'Grav_MeasEs.csv'
pick = 4
gravity_data_file = 'Grav_small_gz.csv'
accuracy_data_file = 'Grav_small_acc.csv'
obs_pts_file = 'Grav_small_MeasEs.csv'
min_dist_file = 'Grav_small_minDist.csv'
max_dist = 5000
mindist1 = 500
mindist2... |
"""
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:... | """
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
class Solution:
def sort_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
... |
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
continue
i += 1
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "ba... | i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
continue
i += 1
fruits = ['apple', 'banana', 'cherry']
for x in fruits:
print(x)
if x == 'banana':
break
fruits = ['apple', 'banana', 'cherry']
for x... |
def config():
return None
def watch():
return None | def config():
return None
def watch():
return None |
"""
This file contains all of the display functions for model management
"""
def display_init_model_root(root):
"""display function for creating new model folder"""
print("Created model directory at %s" % (root))
def display_init_model_db(db_root):
"""display function for initializing the model db"""
... | """
This file contains all of the display functions for model management
"""
def display_init_model_root(root):
"""display function for creating new model folder"""
print('Created model directory at %s' % root)
def display_init_model_db(db_root):
"""display function for initializing the model db"""
pr... |
"""Class implementation for type name interface.
"""
class TypeNameInterface:
_type_name: str
@property
def type_name(self) -> str:
"""
Get this instance expression's type name.
Returns
-------
type_name : str
This instance expression'... | """Class implementation for type name interface.
"""
class Typenameinterface:
_type_name: str
@property
def type_name(self) -> str:
"""
Get this instance expression's type name.
Returns
-------
type_name : str
This instance expression's type name.
... |
def transposition(key, order, order_name):
new_key = ""
for pos in order:
new_key += key[pos-1]
print("Permuted "+ order_name +" = "+ new_key)
return new_key
def P10(key):
P10_order = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P10_key = transposition(key, P10_order, "P10")
return P10_key
... | def transposition(key, order, order_name):
new_key = ''
for pos in order:
new_key += key[pos - 1]
print('Permuted ' + order_name + ' = ' + new_key)
return new_key
def p10(key):
p10_order = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
p10_key = transposition(key, P10_order, 'P10')
return P10_key
... |
"""
Add a counter at a iterable and return the this
counter .
"""
# teste
fruits = ["apple", "pineapple", "lemon", "watermelon", "grapes"]
enumerate_list = enumerate(fruits)
# print(list(enumerate_list))
for index, element in enumerate_list:
filename = f"file{index}.jpg"
print(filename)
| """
Add a counter at a iterable and return the this
counter .
"""
fruits = ['apple', 'pineapple', 'lemon', 'watermelon', 'grapes']
enumerate_list = enumerate(fruits)
for (index, element) in enumerate_list:
filename = f'file{index}.jpg'
print(filename) |
class laptop:
brand=[]
year=[]
ram=[]
def __init__(self,brand,year,ram,cost):
self.brand.append(brand)
self.year.append(year)
self.ram.append(ram)
self.cost.append(cost)
| class Laptop:
brand = []
year = []
ram = []
def __init__(self, brand, year, ram, cost):
self.brand.append(brand)
self.year.append(year)
self.ram.append(ram)
self.cost.append(cost) |
"""uVoyeur Application Bus"""
class PublishFailures(Exception):
delimiter = '\n'
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self._exceptions = list()
def capture_exception(self):
self._exceptions.append(sys.exc_info()[1])
def get_instance... | """uVoyeur Application Bus"""
class Publishfailures(Exception):
delimiter = '\n'
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self._exceptions = list()
def capture_exception(self):
self._exceptions.append(sys.exc_info()[1])
def get_instances(... |
dataset_type = 'TextDetDataset'
data_root = 'data/synthtext'
train = dict(
type=dataset_type,
ann_file=f'{data_root}/instances_training.lmdb',
loader=dict(
type='AnnFileLoader',
repeat=1,
file_format='lmdb',
parser=dict(
type='LineJsonParser',
keys=['... | dataset_type = 'TextDetDataset'
data_root = 'data/synthtext'
train = dict(type=dataset_type, ann_file=f'{data_root}/instances_training.lmdb', loader=dict(type='AnnFileLoader', repeat=1, file_format='lmdb', parser=dict(type='LineJsonParser', keys=['file_name', 'height', 'width', 'annotations'])), img_prefix=f'{data_root... |
class Solution:
def judgeSquareSum(self, c: int) -> bool:
left = 0
right = int(c ** 0.5)
while left <= right:
cur = left ** 2 + right ** 2
if cur < c:
left += 1
elif cur > c:
right -= 1
else:
retu... | class Solution:
def judge_square_sum(self, c: int) -> bool:
left = 0
right = int(c ** 0.5)
while left <= right:
cur = left ** 2 + right ** 2
if cur < c:
left += 1
elif cur > c:
right -= 1
else:
r... |
#!/usr/bin/env python3
def score_word(word):
score = 0
for letter in word:
# add code here
pass
return score
| def score_word(word):
score = 0
for letter in word:
pass
return score |
"""
Advent of Code 2021: Day 02 Part 1
tldr: Find two dimensional ending position
"""
input_file = "input.solution"
totals = {
"forward": 0,
"down": 0,
"up": 0,
}
with open(input_file, "r") as file:
for line in file:
direction, magnitude = line.split()
totals[direction] += int(magn... | """
Advent of Code 2021: Day 02 Part 1
tldr: Find two dimensional ending position
"""
input_file = 'input.solution'
totals = {'forward': 0, 'down': 0, 'up': 0}
with open(input_file, 'r') as file:
for line in file:
(direction, magnitude) = line.split()
totals[direction] += int(magnitude)
result = (to... |
#!/bin/python3
# https://www.hackerrank.com/challenges/alphabet-rangoli/problem
#ll=limitting letter
#sl=starting letter
#df=deduction factor
#cd=character difference
#rl=resulting letter
while True:
ll=ord(input("Enter the limitting letter in the pattern:> "))
sl=65 if ll in range(65,91) else (97 if ll in ran... | while True:
ll = ord(input('Enter the limitting letter in the pattern:> '))
sl = 65 if ll in range(65, 91) else 97 if ll in range(97, 123) else None
if sl:
break
print('Enter a valid input.')
print('See the alphabet pattern:>\n')
for df in range(sl - ll, ll - sl + 1):
for cd in range(sl - ll... |
# initialize step_end
step_end = 25
with plt.xkcd():
# initialize the figure
plt.figure()
# loop for step_end steps
for step in range(step_end):
t = step * dt
i = i_mean * (1 + np.sin((t * 2 * np.pi) / 0.01))
plt.plot(t, i, 'ko')
plt.title('Synaptic Input $I(t)$')
plt.xlabel('time (s)')
pl... | step_end = 25
with plt.xkcd():
plt.figure()
for step in range(step_end):
t = step * dt
i = i_mean * (1 + np.sin(t * 2 * np.pi / 0.01))
plt.plot(t, i, 'ko')
plt.title('Synaptic Input $I(t)$')
plt.xlabel('time (s)')
plt.ylabel('$I$ (A)')
plt.show() |
S = list(map(str, input()))
for i in range(len(S)):
if S[i] == '6':
S[i] = '9'
elif S[i] == '9':
S[i] = '6'
S = reversed(S)
print("".join(S)) | s = list(map(str, input()))
for i in range(len(S)):
if S[i] == '6':
S[i] = '9'
elif S[i] == '9':
S[i] = '6'
s = reversed(S)
print(''.join(S)) |
global_variable = "global_variable"
print(global_variable + " printed at the module level.")
class GeoPoint():
class_attribute = "class_attribute"
print(class_attribute + " printed at the class level.")
def __init__(self):
global global_variable
print(global_variable + " printed at th... | global_variable = 'global_variable'
print(global_variable + ' printed at the module level.')
class Geopoint:
class_attribute = 'class_attribute'
print(class_attribute + ' printed at the class level.')
def __init__(self):
global global_variable
print(global_variable + ' printed at the metho... |
#!/usr/bin/env python3
#!/usr/bin/python
str1 = 'test1'
if str1 == 'test1' or str1 == 'test2':
print('1 or 2')
elif str1 == 'test3' or str1 == 'test4':
print("3 or 4")
else:
print("else")
str1 = ''
if str1:
print(("'%s' is True" % str1))
else:
print(("'%s' is False" % str1))
str1 = ' '
if str1:
... | str1 = 'test1'
if str1 == 'test1' or str1 == 'test2':
print('1 or 2')
elif str1 == 'test3' or str1 == 'test4':
print('3 or 4')
else:
print('else')
str1 = ''
if str1:
print("'%s' is True" % str1)
else:
print("'%s' is False" % str1)
str1 = ' '
if str1:
print("'%s' is True" % str1)
else:
print(... |
"""This module handles numbers"""
class NAN(ValueError):
def __init__(self, value):
super().__init__(f"NAN: {value}")
def _eval(value, kind, default=None):
try:
return kind(value)
except (ValueError, TypeError):
# if default is None:
# raise NAN(value)
if isinstan... | """This module handles numbers"""
class Nan(ValueError):
def __init__(self, value):
super().__init__(f'NAN: {value}')
def _eval(value, kind, default=None):
try:
return kind(value)
except (ValueError, TypeError):
if isinstance(value, (str, type(None))):
return default
... |
# Python Class 1
# variable <-- Left
# = <-- Assign
# data = int, String, char, boolean, float
name = "McGill University"
age = 10
is_good = False
height = 5.6
print("Name is :" + name)
print("Age is :" + str(age))
print("He is good :" +str(is_good))
| name = 'McGill University'
age = 10
is_good = False
height = 5.6
print('Name is :' + name)
print('Age is :' + str(age))
print('He is good :' + str(is_good)) |
# -*- coding: utf-8 -*-
"""Utility exception classes."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
class AlreadyExists(Exception):
"""Exception for adding an item to a col... | """Utility exception classes."""
class Alreadyexists(Exception):
"""Exception for adding an item to a collection it is already in."""
def __init__(self, key, old, new=None):
self.key = key
self.old = old
self.new = new
class Servershutdown(Exception):
"""Exception to signal that t... |
e,f,c = map(int,input().split())
bottle = (e+f)//c
get = (e+f)%c + bottle
while 1:
if get < c: break
bottle += get//c
get = get//c + get%c
print(bottle) | (e, f, c) = map(int, input().split())
bottle = (e + f) // c
get = (e + f) % c + bottle
while 1:
if get < c:
break
bottle += get // c
get = get // c + get % c
print(bottle) |
TESTING = True
HOST = "127.0.0.1"
PORT = 8000
| testing = True
host = '127.0.0.1'
port = 8000 |
def to_star(word):
vowels = ['a', 'e' ,'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in vowels:
word = word.replace(char,"*")
return word
word = input("Enter a word: ")
print(to_star(word)) | def to_star(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in vowels:
word = word.replace(char, '*')
return word
word = input('Enter a word: ')
print(to_star(word)) |
"""
Constants for 'skills' table
"""
table_ = "skillsScores"
timestamp = "timestamp"
team_num = "teamNum"
skills_type = "type"
skills_type_driving = 1
skills_type_programming = 2
red_balls = "redBalls"
blue_balls = "blueBalls"
owned_goals = "ownedGoals"
score = "score"
stop_time = "stopTime"
referee = "refere... | """
Constants for 'skills' table
"""
table_ = 'skillsScores'
timestamp = 'timestamp'
team_num = 'teamNum'
skills_type = 'type'
skills_type_driving = 1
skills_type_programming = 2
red_balls = 'redBalls'
blue_balls = 'blueBalls'
owned_goals = 'ownedGoals'
score = 'score'
stop_time = 'stopTime'
referee = 'referee'
create_... |
"""
To create a cli command add a new file appended by the command
for example:
if I want to create a command called test:
- I will create a file cmd_test
- create a function cli and run my command
To run command on cli:
with docker: docker-compose exec your-image yourapp your-... | """
To create a cli command add a new file appended by the command
for example:
if I want to create a command called test:
- I will create a file cmd_test
- create a function cli and run my command
To run command on cli:
with docker: docker-compose exec your-image yourapp your-... |
print ("Welcome to the mad lib generator. Please follow along and type your input to each statement or question.")
print ("Name an object")
obj1 = input()
print ("Name the plural of your previous object")
obj3 = input()
print ("Name a different plural object")
obj2 = input()
print ("Name a color")
color1 = i... | print('Welcome to the mad lib generator. Please follow along and type your input to each statement or question.')
print('Name an object')
obj1 = input()
print('Name the plural of your previous object')
obj3 = input()
print('Name a different plural object')
obj2 = input()
print('Name a color')
color1 = input()
print('W... |
students = {
"ivan": 5.50,
"alex": 3.50,
"maria": 5.50,
"georgy": 5.50,
}
for k,v in students.items():
if v > 4.50:
print( "{} - {}".format(k, v) ) | students = {'ivan': 5.5, 'alex': 3.5, 'maria': 5.5, 'georgy': 5.5}
for (k, v) in students.items():
if v > 4.5:
print('{} - {}'.format(k, v)) |
#!/usr/bin/python
# pylint: disable=W0223
"""
Utilities for formatting html pages
"""
def wrap(headr, data):
"""
Input:
headr -- text of html field
data -- text to be wrapped.
Returns a corresponding portion of an html file.
"""
return '<%s>%s</%s>' % (headr, data, headr)
def fmt_... | """
Utilities for formatting html pages
"""
def wrap(headr, data):
"""
Input:
headr -- text of html field
data -- text to be wrapped.
Returns a corresponding portion of an html file.
"""
return '<%s>%s</%s>' % (headr, data, headr)
def fmt_table(tbl_info):
"""
Format a table.... |
# This script will track two lists through a 3-D printing process
# Source code/inspiration/software
# Python Crash Course by Eric Matthews, Chapter 8, example 8+
# Made with Mu 1.0.3 in October 2021
# Start with a list of unprinted_designs to be 3-D printed
unprinted_designs = ['iphone case', 'robot pend... | unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
for unprinted_design in unprinted_designs:
print('The following model will be printed: ' + unprinted_design)
completed_models = []
print('\n ')
while unprinted_designs:
current_design = unprinted_designs.pop()
print('Printing model: ' + cu... |
# from typing import Counter
# counter={}
words=input().split(" ")
counter ={ x:words.count(x) for x in set(words)}
print('max: ', max(counter))
print('min: ', min(counter))
# a = input().split()
# d = {}
# for x in a:
# try:
# d[x] += 1
# except:
# d[x] = 1
# print('max: ', max(d))
# prin... | words = input().split(' ')
counter = {x: words.count(x) for x in set(words)}
print('max: ', max(counter))
print('min: ', min(counter)) |
# This file is part of the Extra-P software (http://www.scalasca.org/software/extra-p)
#
# Copyright (c) 2020, Technical University of Darmstadt, Germany
#
# This software may be modified and distributed under the terms of a BSD-style license.
# See the LICENSE file in the base directory for details.
class Recoverable... | class Recoverableerror(RuntimeError):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class Fileformaterror(RecoverableError):
name = 'File Format Error'
def __init__(self, *args: object) -> None:
super().__init__(*args)
class Invalidexperimenterror(RecoverableError):
... |
"""
Examples will be published soon ...
"""
| """
Examples will be published soon ...
""" |
def greet(first_name, last_name):
print(f"Hi {first_name} {last_name}")
greet("Tom", "Hill")
| def greet(first_name, last_name):
print(f'Hi {first_name} {last_name}')
greet('Tom', 'Hill') |
"""
This script takes two input strings and compare them to check if they are anagrams or not.
"""
def mysort(s): #function that splits the letters
d=sorted(s)
s=''.join(d)
return s
s1=input("enter first word ")
n1=mysort(s1) #function invocation /calling the function
s2=input("enter second word ")
n2=mysort(s... | """
This script takes two input strings and compare them to check if they are anagrams or not.
"""
def mysort(s):
d = sorted(s)
s = ''.join(d)
return s
s1 = input('enter first word ')
n1 = mysort(s1)
s2 = input('enter second word ')
n2 = mysort(s2)
if n1.lower() == n2.lower():
print(s1, ' and ', s2, ' ... |
# Copyright (c) 2022, INRIA
# Copyright (c) 2022, University of Lille
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, t... | class Cputopology:
"""
This class stores the necessary information about the CPU topology.
"""
def __init__(self, tdp, freq_bclk, ratio_min, ratio_base, ratio_max):
"""
Create a new CPU topology object.
:param tdp: TDP of the CPU in Watt
:param freq_bclk: Base clock in M... |
print()
print("--- Math ---")
print(1+1)
print(1*3)
print(1/2)
print(3**2)
print(4%2)
print(4%2 == 0)
print(type(1))
print(type(1.0)) | print()
print('--- Math ---')
print(1 + 1)
print(1 * 3)
print(1 / 2)
print(3 ** 2)
print(4 % 2)
print(4 % 2 == 0)
print(type(1))
print(type(1.0)) |
directions = [(-1,0), (0,1), (1,0), (0,-1), (0,0)]
dirs = ["North", "East", "South", "West", "Stay"]
def add(a, b):
return tuple(map(lambda a, b: a + b, a, b))
def sub(a,b):
return tuple(map(lambda a, b: a - b, a, b))
def manhattan_dist(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def direction_t... | directions = [(-1, 0), (0, 1), (1, 0), (0, -1), (0, 0)]
dirs = ['North', 'East', 'South', 'West', 'Stay']
def add(a, b):
return tuple(map(lambda a, b: a + b, a, b))
def sub(a, b):
return tuple(map(lambda a, b: a - b, a, b))
def manhattan_dist(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def directi... |
def even_fibo():
a =1
b = 1
even_sum = 0
c =0
while(c<= 4000000):
c = a + b
a = b
b = c
if(c %2 == 0):
even_sum = c + even_sum
print(even_sum)
if __name__ == "__main__":
print("Project Euler Problem 1")
even_fibo()
| def even_fibo():
a = 1
b = 1
even_sum = 0
c = 0
while c <= 4000000:
c = a + b
a = b
b = c
if c % 2 == 0:
even_sum = c + even_sum
print(even_sum)
if __name__ == '__main__':
print('Project Euler Problem 1')
even_fibo() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 16:18:39 2018
@author: pamelaanderson
"""
def clean_ad_ev_table(df):
""" This function cleans the adverse event reporting data- correcting for drug labeling information
using CMS database as the 'truth' to correct to """
df['dru... | """
Created on Mon Sep 24 16:18:39 2018
@author: pamelaanderson
"""
def clean_ad_ev_table(df):
""" This function cleans the adverse event reporting data- correcting for drug labeling information
using CMS database as the 'truth' to correct to """
df['drug_generic_name'] = df['drug_generic_name'].str.... |
MULTI_ERRORS_HTTP_RESPONSE = {
"errors": [
{
"code": 403,
"message": "access denied, authorization failed"
},
{
"code": 401,
"message": "test error #1"
},
{
"code": 402,
"message": "test error #2"
... | multi_errors_http_response = {'errors': [{'code': 403, 'message': 'access denied, authorization failed'}, {'code': 401, 'message': 'test error #1'}, {'code': 402, 'message': 'test error #2'}], 'meta': {'powered_by': 'crowdstrike-api-gateway', 'query_time': 0.000654734, 'trace_id': '39f1573c-7a51-4b1a-abaa-92d29f704afd'... |
name = 'shell_proc'
version = '1.1.1'
description = 'Continuous shell process'
url = 'https://github.com/justengel/shell_proc'
author = 'Justin Engel'
author_email = 'jtengel08@gmail.com'
| name = 'shell_proc'
version = '1.1.1'
description = 'Continuous shell process'
url = 'https://github.com/justengel/shell_proc'
author = 'Justin Engel'
author_email = 'jtengel08@gmail.com' |
def open_input():
with open("input.txt") as fd:
array = fd.read().splitlines()
array = list(map(int, array))
return array
def part_one(array):
lenght = len(array)
increased = 0
for i in range(0, lenght - 1):
if array[i] < array[i + 1]:
increased += 1
print("part... | def open_input():
with open('input.txt') as fd:
array = fd.read().splitlines()
array = list(map(int, array))
return array
def part_one(array):
lenght = len(array)
increased = 0
for i in range(0, lenght - 1):
if array[i] < array[i + 1]:
increased += 1
print('part ... |
# ===========================================================================
# dictionary.py -----------------------------------------------------------
# ===========================================================================
# function ----------------------------------------------------------------
# -----... | def update_dict(a, b):
if a and b and isinstance(a, dict):
a.update(b)
return a
def get_dict_element(dict_list, field, query):
for item in dict_list:
if item[field] == query:
return item
return dict()
def get_dict_elements(dict_list, field, query, update=False):
if not ... |
# selectionsort() method
def selectionSort(arr):
arraySize = len(arr)
for i in range(arraySize):
min = i
for j in range(i+1, arraySize):
if arr[j] < arr[min]:
min = j
#swap values
arr[i], arr[min] = arr[min], arr[i]
# method to print an array
def printList(arr):
for i in rang... | def selection_sort(arr):
array_size = len(arr)
for i in range(arraySize):
min = i
for j in range(i + 1, arraySize):
if arr[j] < arr[min]:
min = j
(arr[i], arr[min]) = (arr[min], arr[i])
def print_list(arr):
for i in range(len(arr)):
print(arr[i], ... |
# -*- coding: utf-8 -*-
"""Exceptions used in this module"""
class CoincError(Exception):
"""Base Class used to declare other errors for Coinc
Extends:
Exception
"""
pass
class ConfigError(CoincError):
"""Raised when there are invalid value filled in Configuration Sheet
Extends:
... | """Exceptions used in this module"""
class Coincerror(Exception):
"""Base Class used to declare other errors for Coinc
Extends:
Exception
"""
pass
class Configerror(CoincError):
"""Raised when there are invalid value filled in Configuration Sheet
Extends:
CoincError
"""
... |
logo = '''
______ __ __ _ __ __
/ ____/__ __ ___ _____ _____ / /_ / /_ ___ / | / /__ __ ____ ___ / /_ ___ _____
/ / __ / / / // _ \ / ___// ___/ / __// __ \ / _ \ / |/ // / / // __ `__ \ / __ \ / _ \ / ___/
/ /_/ // ... | logo = '\n ______ __ __ _ __ __ \n / ____/__ __ ___ _____ _____ / /_ / /_ ___ / | / /__ __ ____ ___ / /_ ___ _____\n / / __ / / / // _ \\ / ___// ___/ / __// __ \\ / _ \\ / |/ // / / // __ `__ \\ / __ \\ / _ \\ / ___/\n/... |
class AzureBlobUrlModel(object):
def __init__(self, storage_name, container_name, blob_name):
"""
:param storage_name: (str) Azure storage name
:param container_name: (str) Azure container name
:param blob_name: (str) Azure Blob name
"""
self.storage_name = storage_n... | class Azurebloburlmodel(object):
def __init__(self, storage_name, container_name, blob_name):
"""
:param storage_name: (str) Azure storage name
:param container_name: (str) Azure container name
:param blob_name: (str) Azure Blob name
"""
self.storage_name = storage_n... |
'''https://leetcode.com/problems/symmetric-tree/'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isMirror(self, left, right):
if left is None and right is None:
... | """https://leetcode.com/problems/symmetric-tree/"""
class Solution:
def is_mirror(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val == right.val:
return self.isMirror(left.left, ... |
def convert_to_bool(string):
"""
Converts string to bool
:param string: String
:str string: str
:return: True or False
"""
if isinstance(string, bool):
return string
return string in ['true', 'True', '1'] | def convert_to_bool(string):
"""
Converts string to bool
:param string: String
:str string: str
:return: True or False
"""
if isinstance(string, bool):
return string
return string in ['true', 'True', '1'] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 27 10:49:39 2020
@author: Arthur Donizeti Rodrigues Dias
"""
class Category:
def __init__(self, categories):
self.ledger=[]
self.categories = categories
self.listaDeposito=[]
self.listaRetirada=[]
self.total_entr... | """
Created on Mon Jul 27 10:49:39 2020
@author: Arthur Donizeti Rodrigues Dias
"""
class Category:
def __init__(self, categories):
self.ledger = []
self.categories = categories
self.listaDeposito = []
self.listaRetirada = []
self.total_entrada = 0
self.total_saida... |
def defaults():
return dict(
actor='mlp',
ac_kwargs={
'pi': {'hidden_sizes': (64, 64),
'activation': 'tanh'},
'val': {'hidden_sizes': (64, 64),
'activation': 'tanh'}
},
adv_estimation_method='gae',
epochs=300, # ... | def defaults():
return dict(actor='mlp', ac_kwargs={'pi': {'hidden_sizes': (64, 64), 'activation': 'tanh'}, 'val': {'hidden_sizes': (64, 64), 'activation': 'tanh'}}, adv_estimation_method='gae', epochs=300, gamma=0.99, lam_c=0.95, steps_per_epoch=64 * 1000, target_kl=0.0001, use_exploration_noise_anneal=True)
def ... |
class INestedContainer(IContainer,IDisposable):
""" Provides functionality for nested containers,which logically contain zero or more other components and are owned by a parent component. """
def __enter__(self,*args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation of __ent... | class Inestedcontainer(IContainer, IDisposable):
""" Provides functionality for nested containers,which logically contain zero or more other components and are owned by a parent component. """
def __enter__(self, *args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.