content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
LeetCode LinkedList Q.876 Middle of the Linked List
Recusion and Slow/Fast Pointer Solution
'''
def middleNode(self, head: ListNode) -> ListNode:
def rec(slow, fast):
if not fast:
return slow
elif not fast.next:
return slow
return rec(slow.next, fast.next.nex... | """
LeetCode LinkedList Q.876 Middle of the Linked List
Recusion and Slow/Fast Pointer Solution
"""
def middle_node(self, head: ListNode) -> ListNode:
def rec(slow, fast):
if not fast:
return slow
elif not fast.next:
return slow
return rec(slow.next, fast.next.nex... |
class ParameterDefinition(object):
def __init__(self, name, param_type=None, value=None):
self.name = name
self.param_type = param_type
self.value = value
class Parameter(object):
def __init__(self, definition):
self.definition = definition
self.value = definition.val... | class Parameterdefinition(object):
def __init__(self, name, param_type=None, value=None):
self.name = name
self.param_type = param_type
self.value = value
class Parameter(object):
def __init__(self, definition):
self.definition = definition
self.value = definition.valu... |
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Tests if the input `**kwargs` are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input values.
allowed_kwargs : `list`
List with the allowed keys.
raise_error : `bool... | def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Tests if the input `**kwargs` are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input values.
allowed_kwargs : `list`
List with the allowed keys.
raise_error : `bool... |
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_apache_httpcomponents_client5_httpclient5",
artifact = "org.apache.httpcomponents.client5:httpclient5:5.1",
artifact_sha256 = "b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4... | load(':import_external.bzl', import_external='import_external')
def dependencies():
import_external(name='org_apache_httpcomponents_client5_httpclient5', artifact='org.apache.httpcomponents.client5:httpclient5:5.1', artifact_sha256='b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4111591b61b50935', srcjar_sha256='... |
class Solution:
def imageSmoother(self, M: list) -> list:
l = len(M)
if l == 0:
return M
m = len(M[0])
res = []
for i in range(l):
res.append([0] * m)
# print(res)
for x in range(l):
for y in range(m):
summ =... | class Solution:
def image_smoother(self, M: list) -> list:
l = len(M)
if l == 0:
return M
m = len(M[0])
res = []
for i in range(l):
res.append([0] * m)
for x in range(l):
for y in range(m):
summ = 0
... |
#!/usr/bin/env python3
# pylint: disable=invalid-name,missing-docstring
def test_get_arns(oa, shared_datadir):
with open("%s/saml_assertion.txt" % shared_datadir) as fh:
assertion = fh.read()
arns = oa.get_arns(assertion)
# Principal
assert arns[0] == 'arn:aws:iam::012345678901:saml-provider/... | def test_get_arns(oa, shared_datadir):
with open('%s/saml_assertion.txt' % shared_datadir) as fh:
assertion = fh.read()
arns = oa.get_arns(assertion)
assert arns[0] == 'arn:aws:iam::012345678901:saml-provider/OKTA'
assert arns[1] == 'arn:aws:iam::012345678901:role/Okta_AdministratorAccess' |
__all__ = [
"cart_factory",
"cart",
"environment",
"job_factory",
"job",
"location",
"trace",
]
| __all__ = ['cart_factory', 'cart', 'environment', 'job_factory', 'job', 'location', 'trace'] |
TITLE = "The World of Light and Shadow"
ALPHABET = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
ALPHABET += ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", ... | title = 'The World of Light and Shadow'
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphabet += ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', ... |
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(r, c, val):
grid[r][c] = val
for nr, nc in (r-1, c), (r+1, c), (r, c-1), (r, c+1):
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != val:
dfs(nr, nc, ... | class Solution:
def closed_island(self, grid: List[List[int]]) -> int:
def dfs(r, c, val):
grid[r][c] = val
for (nr, nc) in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and (grid[nr][nc] != val):
... |
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
# write your code in Python 2.7
N = len(A)
counter = []
leader = -1
leader_count = 0
left_leader_count = 0
equi_count = 0
for i in xrange(N):
if not counter:
... | def solution(A):
n = len(A)
counter = []
leader = -1
leader_count = 0
left_leader_count = 0
equi_count = 0
for i in xrange(N):
if not counter:
counter.append((A[i], 1))
elif counter[0][0] == A[i]:
counter[0] = (counter[0][0], counter[0][1] + 1)
... |
# this py file will be strictly dedicated to "Boolean Logic"
# Boolean Logic is best defined as the combination of phrases that can result in printing different values
# define two variables
a = True
b = False
# if-statement... output: True
# the if condition prints, if the "if statement" evaluates to True
i... | a = True
b = False
if a:
print('True')
else:
print('False')
if b:
print('True')
else:
print('False')
' \nand: both clauses must be True \nor: one of the clauses must be True\n'
if a and b:
print('Both')
else:
print('Neither')
if a or b:
print('Both')
else:
print('Neither')
x = True
y = T... |
class Solution(object):
def robot(self, command, obstacles, x, y):
"""
:type command: str
:type obstacles: List[List[int]]
:type x: int
:type y: int
:rtype: bool
"""
# zb = [0, 0]
# ind = 0
# while True:
# if command[ind] ==... | class Solution(object):
def robot(self, command, obstacles, x, y):
"""
:type command: str
:type obstacles: List[List[int]]
:type x: int
:type y: int
:rtype: bool
"""
xi = 0
yi = 0
zb = [0, 0]
for c in command:
if c ... |
"""Contains the ItemManager class, used to manage items.txt"""
class ItemManager:
"""A class to manage items.txt."""
def __init__(self):
self.items_file = 'txt_files/items.txt'
def clear_items(self):
with open(self.items_file, 'w') as File:
File.write("Items:\n")
prin... | """Contains the ItemManager class, used to manage items.txt"""
class Itemmanager:
"""A class to manage items.txt."""
def __init__(self):
self.items_file = 'txt_files/items.txt'
def clear_items(self):
with open(self.items_file, 'w') as file:
File.write('Items:\n')
print... |
words = set(
(
"scipy",
"Combinatorics",
"rhs",
"lhs",
"df",
"AttributeError",
"Cymru",
"FiniteSet",
"Jupyter",
"LaTeX",
"Modularisation",
"NameError",
"PyCons",
"allclose",
"ax",
"bc",
... | words = set(('scipy', 'Combinatorics', 'rhs', 'lhs', 'df', 'AttributeError', 'Cymru', 'FiniteSet', 'Jupyter', 'LaTeX', 'Modularisation', 'NameError', 'PyCons', 'allclose', 'ax', 'bc', 'boolean', 'docstring', 'dtype', 'dx', 'dy', 'expr', 'frisbee', 'inv', 'ipynb', 'isclose', 'itertools', 'jupyter', 'len', 'nbs', 'nd', '... |
#Booleans are operators that allow you to convey True or False statements
print(True)
print(False)
type(False)
print(1>2)
print(1==1)
b= None #None is used as a placeholder for an object that has not been assigned , so that object unassigned errors can be avoided
type(b)
print(b)
type(True)
| print(True)
print(False)
type(False)
print(1 > 2)
print(1 == 1)
b = None
type(b)
print(b)
type(True) |
class ServerState:
"""Class for server state"""
def __init__(self):
self.history = set()
self.requests = 0
def register(self, pickup_line):
self.requests += 1
self.history.add(pickup_line)
def get_status(self):
return "<table> " + \
wrap_in_row(... | class Serverstate:
"""Class for server state"""
def __init__(self):
self.history = set()
self.requests = 0
def register(self, pickup_line):
self.requests += 1
self.history.add(pickup_line)
def get_status(self):
return '<table> ' + wrap_in_row('<b>Pickup lines ... |
def for_g():
for row in range(6):
for col in range(3):
if row-col==2 or col-row==1 or row+col==4 or col==2 and row>0 or row==5 and col==1 or row==1 and col==0:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_g():
row=... | def for_g():
for row in range(6):
for col in range(3):
if row - col == 2 or col - row == 1 or row + col == 4 or (col == 2 and row > 0) or (row == 5 and col == 1) or (row == 1 and col == 0):
print('*', end=' ')
else:
print(' ', end=' ')
print()
... |
ERR_SVR_NOT_FOUND = 1
ERR_CLSTR_NOT_FOUND = 2
ERR_IMG_NOT_FOUND = 3
ERR_SVR_EXISTS = 4
ERR_CLSTR_EXISTS = 5
ERR_IMG_EXISTS = 6
ERR_IMG_TYPE_INVALID = 7
ERR_OPR_ERROR = 8
ERR_GENERAL_ERROR = 9
ERR_MATCH_KEY_NOT_PRESENT = 10
ERR_MATCH_VALUE_NOT_PRESENT = 11
ERR_INVALID_MATCH_KEY = 12
| err_svr_not_found = 1
err_clstr_not_found = 2
err_img_not_found = 3
err_svr_exists = 4
err_clstr_exists = 5
err_img_exists = 6
err_img_type_invalid = 7
err_opr_error = 8
err_general_error = 9
err_match_key_not_present = 10
err_match_value_not_present = 11
err_invalid_match_key = 12 |
def swap_case(s):
# sWAP cASE in Python - HackerRank Solution START
Output = ''
for char in s:
if(char.isupper()==True):
Output += (char.lower())
elif(char.islower()==True):
Output += (char.upper())
else:
Output += char
return Output | def swap_case(s):
output = ''
for char in s:
if char.isupper() == True:
output += char.lower()
elif char.islower() == True:
output += char.upper()
else:
output += char
return Output |
a=10
b=1.5
c= 'Arpan'
print (c,"is of type",type(c) )
| a = 10
b = 1.5
c = 'Arpan'
print(c, 'is of type', type(c)) |
KNOWN_BINARIES = [
"*.avi", # video
"*.bin", # binary
"*.bmp", # image
"*.docx", # ms-word
"*.eot", # font
"*.exe", # binary
"*.gif", # image
"*.gz", # compressed
"*.heic", # image
"*.heif", #... | known_binaries = ['*.avi', '*.bin', '*.bmp', '*.docx', '*.eot', '*.exe', '*.gif', '*.gz', '*.heic', '*.heif', '*.ico', '*.jpeg', '*.jpg', '*.m1v', '*.m2a', '*.mov', '*.mp2', '*.mp3', '*.mp4', '*.mpa', '*.mpe', '*.mpeg', '*.mpg', '*.opus', '*.otf', '*.pdf', '*.png', '*.pptx', '*.qt', '*.rar', '*.tar', '*.tif', '*.tiff',... |
ecc_fpga_constants_v128 = [
[
# Parameter name
"p192",
# base word size
16,
# extended word size
128,
# number of bits added
9,
# number of words
2,
# prime
6277101735386680763835789423207666416083908700390324961279,
# prime size in bits
192,
# prime+1
6277101735386680763835789423207666416083908700390324961280,... | ecc_fpga_constants_v128 = [['p192', 16, 128, 9, 2, 6277101735386680763835789423207666416083908700390324961279, 192, 6277101735386680763835789423207666416083908700390324961280, 340282366920938463444927863358058659841, 0, 12554203470773361527671578846415332832167817400780649922558, 340282366920938463481821351505477763072... |
OpenVZ_EXIT_STATUS = {
'vzctl': {0: 'Command executed successfully',
1: 'Failed to set a UBC parameter',
2: 'Failed to set a fair scheduler parameter',
3: 'Generic system error',
5: 'The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not lo... | open_vz_exit_status = {'vzctl': {0: 'Command executed successfully', 1: 'Failed to set a UBC parameter', 2: 'Failed to set a fair scheduler parameter', 3: 'Generic system error', 5: 'The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)', 6: 'Not enough system resources', 7: 'ENV_CREATE ioc... |
# -*- coding: utf-8 -*-
""" Parameters """
"""
Annotated transcript filtering
Setting TSL threshold to 1 excludes some Uniprot canonical transcripts, e.g.,
DDP8_HUMAN with the first 18 amino acids.
"""
tsl_threshold = 2 # the transcript levels below which (lower is better) to consider
"""
Stop codon forced trans... | """ Parameters """
'\nAnnotated transcript filtering\n\nSetting TSL threshold to 1 excludes some Uniprot canonical transcripts, e.g.,\nDDP8_HUMAN with the first 18 amino acids.\n\n'
tsl_threshold = 2
'\nStop codon forced translation\n\nThis threshold may be set to allow some stop codon transcripts to be translated to T... |
"""
Provide help messages for command line interface's receipt commands.
"""
RECEIPT_TRANSACTION_IDENTIFIERS_ARGUMENT_HELP_MESSAGE = 'Identifiers to get a list of transaction\'s receipts by.'
| """
Provide help messages for command line interface's receipt commands.
"""
receipt_transaction_identifiers_argument_help_message = "Identifiers to get a list of transaction's receipts by." |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/16 13:02
# @Author : Yunhao Cao
# @File : exceptions.py
__author__ = 'Yunhao Cao'
__all__ = [
'CrawlerBaseException',
'RuleManyMatchedError',
]
class CrawlerBaseException(Exception):
pass
class RuleManyMatchedError(CrawlerBaseExcep... | __author__ = 'Yunhao Cao'
__all__ = ['CrawlerBaseException', 'RuleManyMatchedError']
class Crawlerbaseexception(Exception):
pass
class Rulemanymatchederror(CrawlerBaseException):
pass |
"""
Permutation where the order the way the elements are arranged matters
Using a back tracking we print all the permutations
E.g.
abc
There are total 3! permutations
abc
acb
acb
bac
bca
cab
cba
"""
def calculate_permutations(element_list, result_list, pos, r=None):
n = len(element_list)
if pos == n:
i... | """
Permutation where the order the way the elements are arranged matters
Using a back tracking we print all the permutations
E.g.
abc
There are total 3! permutations
abc
acb
acb
bac
bca
cab
cba
"""
def calculate_permutations(element_list, result_list, pos, r=None):
n = len(element_list)
if pos == n:
i... |
class Cat:
name = ''
age = 0
color = ''
def __init__(self, name, age=0, color ='White'):
self.name = name
self.age = age
self.color = color
def meow(self):
print(f'{self.name} meow')
def sleep(self):
print(f' {self.name} zzz')
def hungry(self):
... | class Cat:
name = ''
age = 0
color = ''
def __init__(self, name, age=0, color='White'):
self.name = name
self.age = age
self.color = color
def meow(self):
print(f'{self.name} meow')
def sleep(self):
print(f' {self.name} zzz')
def hungry(self):
... |
"""
Creating a custom error by extending the TypeError class
"""
class MyCustomError(TypeError):
"""
Raising a custom error by extending the TypeError class
"""
def __init__(self, error_message, error_code):
super().__init__(f'Error code: {error_code}, Error Message: {error_message}')
... | """
Creating a custom error by extending the TypeError class
"""
class Mycustomerror(TypeError):
"""
Raising a custom error by extending the TypeError class
"""
def __init__(self, error_message, error_code):
super().__init__(f'Error code: {error_code}, Error Message: {error_message}')
... |
######################################################################
#
# File: b2/sync/file.py
#
# Copyright 2018 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
class File(object):
"""
Hold... | class File(object):
"""
Holds information about one file in a folder.
The name is relative to the folder in all cases.
Files that have multiple versions (which only happens
in B2, not in local folders) include information about
all of the versions, most recent first.
"""
def __init__(... |
def ascending_order(arr):
if(len(arr) == 1):
return 0
else:
count = 0
for i in range(0, len(arr)-1):
if(arr[i+1]<arr[i]):
diff = arr[i] - arr[i+1]
arr[i+1]+=diff
count+=diff
return count
if __name__=="__main__":
... | def ascending_order(arr):
if len(arr) == 1:
return 0
else:
count = 0
for i in range(0, len(arr) - 1):
if arr[i + 1] < arr[i]:
diff = arr[i] - arr[i + 1]
arr[i + 1] += diff
count += diff
return count
if __name__ == '__mai... |
class Products:
# Surface Reflectance 8-day 500m
modisRefl = 'MODIS/006/MOD09A1' # => NDDI
# Surface Temperature 8-day 1000m */
modisTemp = 'MODIS/006/MOD11A2' # => T/NDVI
# fAPAR 8-day 500m
modisFpar = 'MODIS/006/MOD15A2H' # => fAPAR
#Evapotranspiration 8-day 500m
modisEt = 'MODIS/006/MOD16A2' # =... | class Products:
modis_refl = 'MODIS/006/MOD09A1'
modis_temp = 'MODIS/006/MOD11A2'
modis_fpar = 'MODIS/006/MOD15A2H'
modis_et = 'MODIS/006/MOD16A2'
modis_evi = 'MODIS/006/MOD13A1' |
# 3. Longest Substring Without Repeating Characters
# Runtime: 60 ms, faster than 74.37% of Python3 online submissions for Longest Substring Without Repeating Characters.
# Memory Usage: 14.4 MB, less than 53.07% of Python3 online submissions for Longest Substring Without Repeating Characters.
class Solution:
#... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
idx = {}
max_len = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in idx:
left = max(left, idx[char])
max_len = max(max_len, right - left + 1)
... |
class MXWarmSpareSettings(object):
def __init__(self, session):
super(MXWarmSpareSettings, self).__init__()
self._session = session
def swapNetworkWarmSpare(self, networkId: str):
"""
**Swap MX primary and warm spare appliances**
https://developer.cisco.com/meraki/ap... | class Mxwarmsparesettings(object):
def __init__(self, session):
super(MXWarmSpareSettings, self).__init__()
self._session = session
def swap_network_warm_spare(self, networkId: str):
"""
**Swap MX primary and warm spare appliances**
https://developer.cisco.com/meraki/ap... |
# Party member and chosen four names
CHOSEN_FOUR = (
'NESS',
'PAULA',
'JEFF',
'POO',
)
PARTY_MEMBERS = (
'NESS',
'PAULA',
'JEFF',
'POO',
'POKEY',
'PICKY',
'KING',
'TONY',
'BUBBLE_MONKEY',
'DUNGEON_MAN',
'FLYING_MAN_1',
'FLYING_MAN_2',
'FLYING_MAN_3',... | chosen_four = ('NESS', 'PAULA', 'JEFF', 'POO')
party_members = ('NESS', 'PAULA', 'JEFF', 'POO', 'POKEY', 'PICKY', 'KING', 'TONY', 'BUBBLE_MONKEY', 'DUNGEON_MAN', 'FLYING_MAN_1', 'FLYING_MAN_2', 'FLYING_MAN_3', 'FLYING_MAN_4', 'FLYING_MAN_5', 'TEDDY_BEAR', 'SUPER_PLUSH_BEAR') |
# -*- coding: utf-8 -*-
def test_receiving_events(vim):
vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id)
event = vim.next_message()
assert event[1] == 'test-event'
assert event[2] == [1, 2, 3]
vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' %
... | def test_receiving_events(vim):
vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id)
event = vim.next_message()
assert event[1] == 'test-event'
assert event[2] == [1, 2, 3]
vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' % vim.channel_id)
vim.command('... |
"""
Constants for common property names
===================================
In order for different parts of the code to have got a common convention for
the names of properties of importance of data points, here in this module,
constants are defined for these names to facilitate the interoperability of
different parts... | """
Constants for common property names
===================================
In order for different parts of the code to have got a common convention for
the names of properties of importance of data points, here in this module,
constants are defined for these names to facilitate the interoperability of
different parts... |
#%% Imports and function declaration
class Node:
"""LinkedListNode class to be used for this problem"""
def __init__(self, data):
self.data = data
self.next = None
# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0]... | class Node:
"""LinkedListNode class to be used for this problem"""
def __init__(self, data):
self.data = data
self.next = None
def create_linked_list(arr):
if len(arr) == 0:
return None
head = node(arr[0])
tail = head
for data in arr[1:]:
tail.next = node(data)
... |
class PlotmanError(Exception):
"""An exception type for all plotman errors to inherit from. This is
never to be raised.
"""
pass
class UnableToIdentifyPlotterFromLogError(PlotmanError):
def __init__(self) -> None:
super().__init__("Failed to identify the plotter definition for parsing lo... | class Plotmanerror(Exception):
"""An exception type for all plotman errors to inherit from. This is
never to be raised.
"""
pass
class Unabletoidentifyplotterfromlogerror(PlotmanError):
def __init__(self) -> None:
super().__init__('Failed to identify the plotter definition for parsing log... |
class TreeError:
TYPE_ERROR = 'ERROR'
TYPE_ANOMALY = 'ANOMALY'
ON_INDI = 'INDIVIDUAL'
ON_FAM = 'FAMILY'
def __init__(self, err_type, err_on, err_us, err_on_id, err_msg):
self.err_type = err_type
self.err_on = err_on
self.err_us = err_us
self.err_on_id = err_on_id
... | class Treeerror:
type_error = 'ERROR'
type_anomaly = 'ANOMALY'
on_indi = 'INDIVIDUAL'
on_fam = 'FAMILY'
def __init__(self, err_type, err_on, err_us, err_on_id, err_msg):
self.err_type = err_type
self.err_on = err_on
self.err_us = err_us
self.err_on_id = err_on_id
... |
budget_header = 'Budget'
forecast_total_header = 'Forecast outturn'
variance_header = 'Variance -overspend/underspend'
variance_percentage_header = 'Variance %'
year_to_date_header = 'Year to Date Actuals'
budget_spent_percentage_header = '% of budget spent to date'
variance_outturn_header = "Forecast movement"
| budget_header = 'Budget'
forecast_total_header = 'Forecast outturn'
variance_header = 'Variance -overspend/underspend'
variance_percentage_header = 'Variance %'
year_to_date_header = 'Year to Date Actuals'
budget_spent_percentage_header = '% of budget spent to date'
variance_outturn_header = 'Forecast movement' |
'''
Commands: Basic module to handle all commands. Commands for mops are driven by one-line
exec statements; these exec statements are held in a dictionary.
Model Operations Processing System. Copyright Brian Fairbairn 2009-2010. Licenced under the EUPL.
You may not use this work except in compliance with the... | """
Commands: Basic module to handle all commands. Commands for mops are driven by one-line
exec statements; these exec statements are held in a dictionary.
Model Operations Processing System. Copyright Brian Fairbairn 2009-2010. Licenced under the EUPL.
You may not use this work except in compliance with the Lice... |
""" base.py: Base class for differentiable neural network layers."""
class Layer(object):
""" Abstract base class for differentiable layer."""
def forward_pass(self, input_):
""" Forward pass returning and storing outputs."""
raise NotImplementedError()
def backward_pass(self, err):
... | """ base.py: Base class for differentiable neural network layers."""
class Layer(object):
""" Abstract base class for differentiable layer."""
def forward_pass(self, input_):
""" Forward pass returning and storing outputs."""
raise not_implemented_error()
def backward_pass(self, err):
... |
def get_distance_matrix(orig, edited):
# initialize the matrix
orig_len = len(orig) + 1
edit_len = len(edited) + 1
distance_matrix = [[0] * edit_len for _ in range(orig_len)]
for i in range(orig_len):
distance_matrix[i][0] = i
for j in range(edit_len):
distance_matrix[0][j] = j
... | def get_distance_matrix(orig, edited):
orig_len = len(orig) + 1
edit_len = len(edited) + 1
distance_matrix = [[0] * edit_len for _ in range(orig_len)]
for i in range(orig_len):
distance_matrix[i][0] = i
for j in range(edit_len):
distance_matrix[0][j] = j
for i in range(1, orig_le... |
plural_suffixes = {
'ches': 'ch',
'shes': 'sh',
'ies': 'y',
'ves': 'fe',
'oes': 'o',
'zes': 'z',
's': ''
}
plural_words = {
'pieces': 'piece',
'bunches': 'bunch',
'haunches': 'haunch',
'flasks': 'flask',
'veins': 'vein',
'bowls': 'bowl'
} | plural_suffixes = {'ches': 'ch', 'shes': 'sh', 'ies': 'y', 'ves': 'fe', 'oes': 'o', 'zes': 'z', 's': ''}
plural_words = {'pieces': 'piece', 'bunches': 'bunch', 'haunches': 'haunch', 'flasks': 'flask', 'veins': 'vein', 'bowls': 'bowl'} |
__author__ = 'jwely'
__all__ = ["fetch_AVHRR"]
def fetch_AVHRR():
"""
fetches AVHRR-pathfinder data via ftp
server: ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/
"""
print("this function is an unfinished stub!")
return | __author__ = 'jwely'
__all__ = ['fetch_AVHRR']
def fetch_avhrr():
"""
fetches AVHRR-pathfinder data via ftp
server: ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/
"""
print('this function is an unfinished stub!')
return |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ============================================================================
# Erfr - One-time pad encryption tool
# Substitution-box core module
# Copyright (C) 2018 by Ralf Kilian
# Distributed under the MIT License (https://opensource.org/licenses/MIT)
#
# Website: h... | __version__ = '4.3.3'
fsb_rijndael = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235,... |
def insert_space(msg, idx):
msg = msg[:idx] + " " + msg[idx:]
print(msg)
return msg
def reverse(msg, substring):
if substring in msg:
msg = msg.replace(substring, "", 1)
msg += substring[::-1]
print(msg)
return msg
else:
print("error")
return msg
d... | def insert_space(msg, idx):
msg = msg[:idx] + ' ' + msg[idx:]
print(msg)
return msg
def reverse(msg, substring):
if substring in msg:
msg = msg.replace(substring, '', 1)
msg += substring[::-1]
print(msg)
return msg
else:
print('error')
return msg
def... |
class Evaluator(object):
"""
Evaluates a model on a Dataset, using metrics specific to the Dataset.
"""
def __init__(self, dataset_cls, model, embedding, data_loader, batch_size, device, keep_results=False):
self.dataset_cls = dataset_cls
self.model = model
self.embedding = embe... | class Evaluator(object):
"""
Evaluates a model on a Dataset, using metrics specific to the Dataset.
"""
def __init__(self, dataset_cls, model, embedding, data_loader, batch_size, device, keep_results=False):
self.dataset_cls = dataset_cls
self.model = model
self.embedding = embe... |
# Time: O(n)
# Space: O(h)
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.depth(root, 0)[1]
def depth(self, root, diameter):
if not root:
return 0, diameter
left, diame... | class Solution(object):
def diameter_of_binary_tree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.depth(root, 0)[1]
def depth(self, root, diameter):
if not root:
return (0, diameter)
(left, diameter) = self.depth(root.left... |
#
# Copyright (c) Members of the EGEE Collaboration. 2006-2009.
# See http://www.eu-egee.org/partners/ for details on the copyright holders.
#
# 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
#
... | commands_def = '<?xml version="1.0" encoding="UTF-8"?>\n<voms-commands>\n <command-group\n name="User management commands"\n shortname="user">\n <command\n name="list-users">\n <description>list-users</description>\n <help-string\n xml:space="preserve">\n Lists the VO users.</help... |
#!/usr/bin/env python
# coding: utf-8
# # Calculating protein mass, from [Rosalind.info](https://www.rosalind.info)
#
# (Specific exercise can be found at: http://rosalind.info/problems/prtm/)
#
# ## My personal interpretation
#
# 1. The exercise is about calculating the molecular weight of a protein
#
# 2. The pr... | def read_monoisotopic_mass_table(input_file):
"""
Given a tab-separatedd input file with amino acids (as capital letters)
in the first column, and molecular weights (as floating point numbers)
in the second column - create a dictionary with the amino acids as keys
and their respective weights as values.
"""
... |
class PokepayResponse(object):
def __init__(self, response, response_body):
self.body = response_body
self.elapsed = response.elapsed
self.status_code = response.status_code
self.ok = response.ok
self.headers = response.headers
self.url = response.url
def body(se... | class Pokepayresponse(object):
def __init__(self, response, response_body):
self.body = response_body
self.elapsed = response.elapsed
self.status_code = response.status_code
self.ok = response.ok
self.headers = response.headers
self.url = response.url
def body(s... |
str1=input("enter first string:")
str2=input("enter second string:")
new_a = str2[:2] + str1[2:]
new_b = str1[:2] + str2[2:]
print("the new string after swapping first two charaters of both string:",(new_a+' ' +new_b))
| str1 = input('enter first string:')
str2 = input('enter second string:')
new_a = str2[:2] + str1[2:]
new_b = str1[:2] + str2[2:]
print('the new string after swapping first two charaters of both string:', new_a + ' ' + new_b) |
a = int(input())
b = int(input())
if a > b:
print(1)
elif a == b:
print(0)
else:
print(2)
| a = int(input())
b = int(input())
if a > b:
print(1)
elif a == b:
print(0)
else:
print(2) |
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(list(zip(keys, values)))
# Lazily, Python 2.3+, not 3.x:
hash = dict(zip(keys, values))
| keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(list(zip(keys, values)))
hash = dict(zip(keys, values)) |
class Space():
"""
Common definitions for observations and actions.
"""
def sample(self, size=None, null=False):
"""
Uniformly randomly sample a random element(s) of this space.
"""
raise NotImplementedError
| class Space:
"""
Common definitions for observations and actions.
"""
def sample(self, size=None, null=False):
"""
Uniformly randomly sample a random element(s) of this space.
"""
raise NotImplementedError |
def main(request, response):
"""Send a response with the Origin-Policy header given in the query string.
"""
header = request.GET.first(b"header")
response.headers.set(b"Origin-Policy", header)
response.headers.set(b"Content-Type", b"text/html")
return u"""
<!DOCTYPE html>
<meta charse... | def main(request, response):
"""Send a response with the Origin-Policy header given in the query string.
"""
header = request.GET.first(b'header')
response.headers.set(b'Origin-Policy', header)
response.headers.set(b'Content-Type', b'text/html')
return u'\n <!DOCTYPE html>\n <meta charset=... |
description = 'Refsans 4 analog 1 GPIO on Raspberry'
group = 'optional'
tango_base = 'tango://%s:10000/test/ads/' % setupname
lowlevel = ()
devices = {
'%s_ch1' % setupname : device('nicos.devices.entangle.Sensor',
description = 'ADin0',
tangodevice = tango_base + 'ch1',
unit = 'V',
... | description = 'Refsans 4 analog 1 GPIO on Raspberry'
group = 'optional'
tango_base = 'tango://%s:10000/test/ads/' % setupname
lowlevel = ()
devices = {'%s_ch1' % setupname: device('nicos.devices.entangle.Sensor', description='ADin0', tangodevice=tango_base + 'ch1', unit='V', fmtstr='%.4f', visibility=lowlevel), '%s_ch2... |
class Solution:
"""
@param s: a string
@return: the number of segments in a string
"""
def countSegments(self, s):
# write yout code here
return len(s.split())
| class Solution:
"""
@param s: a string
@return: the number of segments in a string
"""
def count_segments(self, s):
return len(s.split()) |
file = open('JacobiMatrix.java', 'w')
for i in range(10):
for j in range(10):
file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n')
file.close()
| file = open('JacobiMatrix.java', 'w')
for i in range(10):
for j in range(10):
file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n')
file.close() |
#!/usr/bin/python2
lst = []
with open('lst.txt', 'r') as f:
lst = f.read().split('\n')
i=1
for img in lst:
if 'resized' in img:
with open(img, 'r') as rd:
with open("combined/%05d.%s.png" % (i, img.split('.')[1]), 'w') as wr:
wr.write(rd.read())
i+=1
| lst = []
with open('lst.txt', 'r') as f:
lst = f.read().split('\n')
i = 1
for img in lst:
if 'resized' in img:
with open(img, 'r') as rd:
with open('combined/%05d.%s.png' % (i, img.split('.')[1]), 'w') as wr:
wr.write(rd.read())
i += 1 |
class Task:
def __init__(self):
self.name = "";
self.active = False;
def activate(self):
pass
def update(self, dt):
pass
def is_complete(self):
pass
def close(self):
pass
| class Task:
def __init__(self):
self.name = ''
self.active = False
def activate(self):
pass
def update(self, dt):
pass
def is_complete(self):
pass
def close(self):
pass |
"""Generate AXT release artifacts."""
load("//build_extensions:remove_from_jar.bzl", "remove_from_jar")
load("//build_extensions:add_or_update_file_in_zip.bzl", "add_or_update_file_in_zip")
def axt_release_lib(
name,
deps,
custom_package = None,
proguard_specs = None,
proguard_library = None,
... | """Generate AXT release artifacts."""
load('//build_extensions:remove_from_jar.bzl', 'remove_from_jar')
load('//build_extensions:add_or_update_file_in_zip.bzl', 'add_or_update_file_in_zip')
def axt_release_lib(name, deps, custom_package=None, proguard_specs=None, proguard_library=None, multidex='off', jarjar_rules='//... |
'''
define some function to use.
'''
def bytes_to_int(bytes_string, order_type):
'''
the bind of the int.from_bytes function.
'''
return int.from_bytes(bytes_string, byteorder=order_type)
def bits_to_int(bit_string):
'''
the bind of int(string, 2) function.
'''
return int... | """
define some function to use.
"""
def bytes_to_int(bytes_string, order_type):
"""
the bind of the int.from_bytes function.
"""
return int.from_bytes(bytes_string, byteorder=order_type)
def bits_to_int(bit_string):
"""
the bind of int(string, 2) function.
"""
return int(bit_string, 2... |
"""dbcfg - Annon configuration
This is mutable object.
"""
dbcfg = {
"created_on": None
,"modified_on": None
,"timestamp": None
,"anndb_id": None
,"rel_id": None
,"dbname": None
,"dbid": None
,"allowed_file_type":['.txt','.csv','.yml','.json']
,"allowed_image_type":['.pdf','.png','.jpg','.jpeg','.gif'... | """dbcfg - Annon configuration
This is mutable object.
"""
dbcfg = {'created_on': None, 'modified_on': None, 'timestamp': None, 'anndb_id': None, 'rel_id': None, 'dbname': None, 'dbid': None, 'allowed_file_type': ['.txt', '.csv', '.yml', '.json'], 'allowed_image_type': ['.pdf', '.png', '.jpg', '.jpeg', '.gif'], 'allowe... |
def _calc_product(series, start_idx, end_idx):
product = 1
for digit in series[start_idx:end_idx + 1]:
product *= int(digit)
return product
def largest_product_in_series(num_digits, series):
largest_product = 0
for i in range(num_digits, len(series) + 1):
product = _calc_product(se... | def _calc_product(series, start_idx, end_idx):
product = 1
for digit in series[start_idx:end_idx + 1]:
product *= int(digit)
return product
def largest_product_in_series(num_digits, series):
largest_product = 0
for i in range(num_digits, len(series) + 1):
product = _calc_product(ser... |
class Solution:
def countOfAtoms(self, formula: str) -> str:
formula = "(" + formula + ")"
l = len(formula)
def mmerge(dst, src, xs):
for k, v in src.items():
t = dst.get(k, 0)
dst[k] = v * xs + t
def aux(st):
nonlocal formula... | class Solution:
def count_of_atoms(self, formula: str) -> str:
formula = '(' + formula + ')'
l = len(formula)
def mmerge(dst, src, xs):
for (k, v) in src.items():
t = dst.get(k, 0)
dst[k] = v * xs + t
def aux(st):
nonlocal fo... |
#Program to be tested
def boarding(seat_number):
if seat_number >= 1 and seat_number <= 25:
batch_no = 1
elif seat_number >= 26 and seat_number <= 100:
batch_no = 2
elif seat_number >= 101 and seat_number <= 200:
batch_no = 3
else:
batch_no = -1
return batch_no
| def boarding(seat_number):
if seat_number >= 1 and seat_number <= 25:
batch_no = 1
elif seat_number >= 26 and seat_number <= 100:
batch_no = 2
elif seat_number >= 101 and seat_number <= 200:
batch_no = 3
else:
batch_no = -1
return batch_no |
# PRE PROCESSING
def symmetric_NaN_replacement(dataset):
np_dataset = dataset.to_numpy()
for col in range(0,(np_dataset.shape[1])):
ss_idx = 0
for row in range(1,(dataset.shape[0]-1)):
if (np.isnan(np_dataset[row,col]) and (~np.isnan(np_dataset[row-1,col]))): # if a NaN is found, an... | def symmetric__na_n_replacement(dataset):
np_dataset = dataset.to_numpy()
for col in range(0, np_dataset.shape[1]):
ss_idx = 0
for row in range(1, dataset.shape[0] - 1):
if np.isnan(np_dataset[row, col]) and ~np.isnan(np_dataset[row - 1, col]):
ss_idx = row
... |
name0_0_1_0_0_2_0 = None
name0_0_1_0_0_2_1 = None
name0_0_1_0_0_2_2 = None
name0_0_1_0_0_2_3 = None
name0_0_1_0_0_2_4 = None | name0_0_1_0_0_2_0 = None
name0_0_1_0_0_2_1 = None
name0_0_1_0_0_2_2 = None
name0_0_1_0_0_2_3 = None
name0_0_1_0_0_2_4 = None |
# -*- coding: utf-8 -*-
__title__ = 'pyginx'
__version__ = '0.1.13.7.7'
__description__ = ''
__author__ = 'wrmsr'
__author_email__ = 'timwilloney@gmail.com'
__url__ = 'https://github.com/wrmsr/pyginx'
| __title__ = 'pyginx'
__version__ = '0.1.13.7.7'
__description__ = ''
__author__ = 'wrmsr'
__author_email__ = 'timwilloney@gmail.com'
__url__ = 'https://github.com/wrmsr/pyginx' |
"""
Exceptions declaration.
"""
__all__ = [
"PyCozmoException",
"PyCozmoConnectionError",
"ConnectionTimeout",
"Timeout",
]
class PyCozmoException(Exception):
""" Base class for all PyCozmo exceptions. """
class PyCozmoConnectionError(PyCozmoException):
""" Base class for all PyCozmo conn... | """
Exceptions declaration.
"""
__all__ = ['PyCozmoException', 'PyCozmoConnectionError', 'ConnectionTimeout', 'Timeout']
class Pycozmoexception(Exception):
""" Base class for all PyCozmo exceptions. """
class Pycozmoconnectionerror(PyCozmoException):
""" Base class for all PyCozmo connection exceptions. """... |
class InvalidMeasurement(Exception):
"""
Raised when a specified measurement is invalid.
"""
| class Invalidmeasurement(Exception):
"""
Raised when a specified measurement is invalid.
""" |
path = r'c:\users\raibows\desktop\emma.txt'
file = open(path, 'r')
s = file.readlines()
file.close()
r = [i.swapcase() for i in s]
file = open(path, 'w')
file.writelines(r)
file.close()
| path = 'c:\\users\\raibows\\desktop\\emma.txt'
file = open(path, 'r')
s = file.readlines()
file.close()
r = [i.swapcase() for i in s]
file = open(path, 'w')
file.writelines(r)
file.close() |
class Config(object):
def __init__(self):
# directories
self.save_dir = ''
self.log_dir = ''
self.train_data_file = ''
self.val_data_file = ''
# input
self.patch_size = [42, 42, 1]
self.N = self.patch_size[0]*self.patch_size[1]
... | class Config(object):
def __init__(self):
self.save_dir = ''
self.log_dir = ''
self.train_data_file = ''
self.val_data_file = ''
self.patch_size = [42, 42, 1]
self.N = self.patch_size[0] * self.patch_size[1]
self.pre_n_layers = 3
self.pregconv_n_layer... |
CAS_HEADERS = ('Host', 'Port', 'ID', 'Operator',
'NMEA', 'Country', 'Latitude', 'Longitude',
'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance')
NET_HEADERS = ('ID', 'Operator', 'Authentication',
'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Dis... | cas_headers = ('Host', 'Port', 'ID', 'Operator', 'NMEA', 'Country', 'Latitude', 'Longitude', 'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance')
net_headers = ('ID', 'Operator', 'Authentication', 'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Distance')
str_headers = ('Mountpoint', 'ID', 'Fo... |
"""
"""
def _impl(repository_ctx):
sdk_path = repository_ctx.os.environ.get("VULKAN_SDK", None)
if sdk_path == None:
print("VULKAN_SDK environment variable not found, using /usr")
sdk_path = "/usr"
repository_ctx.symlink(sdk_path, "vulkan_sdk_linux")
glslc_path = repository_ctx.which... | """
"""
def _impl(repository_ctx):
sdk_path = repository_ctx.os.environ.get('VULKAN_SDK', None)
if sdk_path == None:
print('VULKAN_SDK environment variable not found, using /usr')
sdk_path = '/usr'
repository_ctx.symlink(sdk_path, 'vulkan_sdk_linux')
glslc_path = repository_ctx.which('g... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 21:16:00 2020
@author: mints
"""
A_K = 0.306
BANDS = {
'AllWISE': ['W1mag', 'W2mag'],
'ATLAS': ['%sap3' % s for s in list('UGRIZ')],
'DES': ['mag_auto_%s' % s for s in list('grizy')],
'KIDS': ['%smag' % s for s in list('ugri')]... | """
Created on Sat Jun 27 21:16:00 2020
@author: mints
"""
a_k = 0.306
bands = {'AllWISE': ['W1mag', 'W2mag'], 'ATLAS': ['%sap3' % s for s in list('UGRIZ')], 'DES': ['mag_auto_%s' % s for s in list('grizy')], 'KIDS': ['%smag' % s for s in list('ugri')], 'LAS': ['p%smag' % s for s in ['y', 'j', 'h', 'k']], 'LS8': ['der... |
# -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | def unique(seq):
"""Yield unique elements from sequence of hashables, preserving order.
(New in 0.13)
"""
seen = set()
return (x for x in seq if x not in seen and (not seen.add(x))) |
__version__ = '0.1'
supported_aln_types = ('blast', 'sam', 'xml')
supported_db_types = ('nt', 'nr','cds', 'genome', 'none')
consensus_aln_types = ('xml',)
| __version__ = '0.1'
supported_aln_types = ('blast', 'sam', 'xml')
supported_db_types = ('nt', 'nr', 'cds', 'genome', 'none')
consensus_aln_types = ('xml',) |
def ordinal(n):
"""Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc.
:param int n: the index to be translated.
:return: (*str*) -- Ordinal.
"""
ord_dict = {1: "st", 2: "nd", 3: "rd"}
return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, "th")
| def ordinal(n):
"""Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc.
:param int n: the index to be translated.
:return: (*str*) -- Ordinal.
"""
ord_dict = {1: 'st', 2: 'nd', 3: 'rd'}
return str(n + 1) + ord_dict.get(n + 1 if n + 1 < 20 else (n + 1) % 10, 'th') |
def for_G():
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or ((row==0 or row==6) and (col>0)) or (row==3 and col>1) or (row>3 and col==4):
print("*",end=" ")
else:
print(end=" ")
print()
def while_G(... | def for_g():
for row in range(7):
for col in range(5):
if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0) or (row == 3 and col > 1) or (row > 3 and col == 4):
print('*', end=' ')
else:
print(end=' ')
print()
def w... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 00:07:09 2017
@author: Nadiar
"""
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
res = 1
for i in range(1,(exp + 1)):
res *= base
... | """
Created on Thu Jan 26 00:07:09 2017
@author: Nadiar
"""
def iter_power(base, exp):
"""
base: int or float.
exp: int >= 0
returns: int or float, base^exp
"""
res = 1
for i in range(1, exp + 1):
res *= base
return res |
def solution(A, K):
# if length is equal to K nothing changes
if K == len(A):
return A
# if all elements are the same, nothing change
if all([item == A[0] for item in A]):
return A
N = len(A)
_A = [0] * N
for ind in range(N):
transf_ind = ind + K
_A[... | def solution(A, K):
if K == len(A):
return A
if all([item == A[0] for item in A]):
return A
n = len(A)
_a = [0] * N
for ind in range(N):
transf_ind = ind + K
_A[transf_ind - transf_ind // N * N] = A[ind]
return _A |
#!/usr/bin/env python
#
# Azure Linux extension
#
# Copyright (c) Microsoft Corporation
# All rights reserved.
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the ""Software""), to deal in the Software without restr... | def get_diagnostics_monitor_configuration_element(ladCfg, elementName):
if ladCfg and 'diagnosticMonitorConfiguration' in ladCfg:
if elementName in ladCfg['diagnosticMonitorConfiguration']:
return ladCfg['diagnosticMonitorConfiguration'][elementName]
return None
def get_file_cfg_from_lad_cf... |
# *###################
# * SYMBOL TABLE
# *###################
class SymbolTable:
def __init__(self, parent=None):
self.symbols = {}
self.parent = parent
def get(self, name):
value = self.symbols.get(name, None)
if value is None and self.parent:
return self.parent.g... | class Symboltable:
def __init__(self, parent=None):
self.symbols = {}
self.parent = parent
def get(self, name):
value = self.symbols.get(name, None)
if value is None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
... |
#!/usr/bin/env python3
try:
print('If you provide a legal file name, this program will output the last two lines of the song to that file...')
print('\nMary had a little lamb,')
answersnow = input('With fleece as white as (enter your file name): ')
answersnowobj = open(answersnow, 'w')
except:
print... | try:
print('If you provide a legal file name, this program will output the last two lines of the song to that file...')
print('\nMary had a little lamb,')
answersnow = input('With fleece as white as (enter your file name): ')
answersnowobj = open(answersnow, 'w')
except:
print('Error with that file ... |
def solve_knapsack(profits, weights, capacity):
# basic checks
n = len(profits)
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [0 for x in range(capacity + 1)] # <<<<<<<<<<
# if we have only one weight, we will take it if it is not more than the capacity
for c in range... | def solve_knapsack(profits, weights, capacity):
n = len(profits)
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [0 for x in range(capacity + 1)]
for c in range(0, capacity + 1):
if weights[0] <= c:
dp[c] = profits[0]
for i in range(1, n):
for c in ... |
input1 = input("Insira a palavra #1")
input2 = input("Insira a palavra #2")
input3 = input("Insira a palavra #3")
input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '')
print(input1.upper())
print(input2.lower())
print(input3) | input1 = input('Insira a palavra #1')
input2 = input('Insira a palavra #2')
input3 = input('Insira a palavra #3')
input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '')
print(input1.upper())
print(input2.lower())
print(input3) |
# Define a simple function that prints x
def f(x):
x += 1
print(x)
# Set y
y = 10
# Call the function
f(y)
# Print y to see if it changed
print(y) | def f(x):
x += 1
print(x)
y = 10
f(y)
print(y) |
#
# @lc app=leetcode id=922 lang=python3
#
# [922] Sort Array By Parity II
#
# @lc code=start
class Solution:
def sortArrayByParityII(self, a: List[int]) -> List[int]:
i = 0 # pointer for even misplaced
j = 1 # pointer for odd misplaced
sz = len(a)
# invariant: for every mi... | class Solution:
def sort_array_by_parity_ii(self, a: List[int]) -> List[int]:
i = 0
j = 1
sz = len(a)
while i < sz and j < sz:
if a[i] % 2 == 0:
i += 2
elif a[j] % 2 == 1:
j += 2
else:
(a[i], a[j]) =... |
class StringUtil:
@staticmethod
def is_empty(string):
if string is None or string.strip() == "":
return True
else:
return False
@staticmethod
def is_not_empty(string):
return not StringUtil.is_empty(string)
| class Stringutil:
@staticmethod
def is_empty(string):
if string is None or string.strip() == '':
return True
else:
return False
@staticmethod
def is_not_empty(string):
return not StringUtil.is_empty(string) |
#!python3
#encoding:utf-8
class Json2Sqlite(object):
def __init__(self):
pass
def BoolToInt(self, bool_value):
if True == bool_value:
return 1
else:
return 0
def IntToBool(self, int_value):
if 0 == int_value:
return False
else:
... | class Json2Sqlite(object):
def __init__(self):
pass
def bool_to_int(self, bool_value):
if True == bool_value:
return 1
else:
return 0
def int_to_bool(self, int_value):
if 0 == int_value:
return False
else:
return True... |
INPUT = {
"google": {
"id_token": ""
},
"github": {
"code": "",
"state": ""
}
}
| input = {'google': {'id_token': ''}, 'github': {'code': '', 'state': ''}} |
"""Constants for the Kuna component."""
ATTR_NOTIFICATIONS_ENABLED = "notifications_enabled"
ATTR_SERIAL_NUMBER = "serial_number"
ATTR_VOLUME = "volume"
CONF_RECORDING_INTERVAL = "recording_interval"
CONF_STREAM_INTERVAL = "stream_interval"
CONF_UPDATE_INTERVAL = "update_interval"
DEFAULT_RECORDING_INTERVAL = 7200
D... | """Constants for the Kuna component."""
attr_notifications_enabled = 'notifications_enabled'
attr_serial_number = 'serial_number'
attr_volume = 'volume'
conf_recording_interval = 'recording_interval'
conf_stream_interval = 'stream_interval'
conf_update_interval = 'update_interval'
default_recording_interval = 7200
defa... |
base=10
height=5
area=1/2*(base*height)
print("Area of our triangle is : ", area)
file = open("/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv","r")
lines = []
with file as myFile:
for line in file:
feat = []
line = line.split(',')
for i in range(0, len... | base = 10
height = 5
area = 1 / 2 * (base * height)
print('Area of our triangle is : ', area)
file = open('/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv', 'r')
lines = []
with file as my_file:
for line in file:
feat = []
line = line.split(',')
for i in... |
def main():
A=input("Enter the string")
A1=A[0:2:1]
A2=A[-2::1]
print(A1)
print(A2)
A3=(A1+A2)
print("The new string is " ,A3)
if(__name__== '__main__'):
main()
| def main():
a = input('Enter the string')
a1 = A[0:2:1]
a2 = A[-2::1]
print(A1)
print(A2)
a3 = A1 + A2
print('The new string is ', A3)
if __name__ == '__main__':
main() |
'''
Kattis - memorymatch
Consider the 2 different corner cases and the rest is not too hard.
Time: O(num_opens), Space: O(n)
'''
n = int(input())
num_opens = int(input())
cards = {}
turned_off = set()
for i in range(num_opens):
x, y, cx, cy = input().split()
x, y = int(x), int(y)
if not cx in cards:
... | """
Kattis - memorymatch
Consider the 2 different corner cases and the rest is not too hard.
Time: O(num_opens), Space: O(n)
"""
n = int(input())
num_opens = int(input())
cards = {}
turned_off = set()
for i in range(num_opens):
(x, y, cx, cy) = input().split()
(x, y) = (int(x), int(y))
if not cx in cards:
... |
# Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | class Tensorforceconfig(object):
def __init__(self, *, buffer_observe=False, create_debug_assertions=False, create_tf_assertions=True, device='CPU', eager_mode=False, enable_int_action_masking=True, name='agent', seed=None, tf_log_level=40):
assert buffer_observe is False or buffer_observe == 'episode' or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.