content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Fibonacci
Fibonacci.py
# Fibonacci numbers module
#n = int(input('Please enter a number: '))
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
# Go to fibonacci Powerpoint
def fib2(n): # return Fibonacci series
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b... | Fibonacci.py
def fib(n):
(a, b) = (0, 1)
while a < n:
print(a, end=' ')
(a, b) = (b, a + b)
print()
def fib2(n):
result = []
(a, b) = (0, 1)
while a < n:
result.append(a)
(a, b) = (b, a + b)
return result |
#Parameters given at the beginning of the APP
zid_min = 1E06 #1Mohm
zic_min = 10E06 #10Mohm
GM_min = 10 #dB
PM_min = 30 #deg
CL_min = 0 #0uF
CL_max = 1E-06 #1uF
Rl = 10 #10ohm
Fc_low = 0 #DC
Fc_high = 100E03 #100kHz
CMRR_min = 100 ... | zid_min = 1000000.0
zic_min = 10000000.0
gm_min = 10
pm_min = 30
cl_min = 0
cl_max = 1e-06
rl = 10
fc_low = 0
fc_high = 100000.0
cmrr_min = 100
av_cl = 10
thd = 0.01
dyn_range = 10
cm_min = -2
cm_max = 2 |
#
# PySNMP MIB module IPFIX-SELECTOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPFIX-SELECTOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:44:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
grid_view_field_options_schema = {
'type': 'object',
'description': 'An object containing the field id as key and the '
'properties related to view as value.',
'properties': {
'1': {
'type': 'object',
'description': 'Properties of field with id 1 of the rel... | grid_view_field_options_schema = {'type': 'object', 'description': 'An object containing the field id as key and the properties related to view as value.', 'properties': {'1': {'type': 'object', 'description': 'Properties of field with id 1 of the related view.', 'properties': {'width': {'type': 'integer', 'example': 2... |
#!/usr/bin/env python3
# vim: set ai et ts=4 sw=4:
def gen(arg, begin, pixels, arr):
for i in range(0, int(2**len(arr))):
if i > 0:
print("else");
if i != int(2**len(arr)) - 1:
print("if({} < ({} + ({}/{})*{}))".format(
arg, begin, pixels, int(2**len(arr)), ... | def gen(arg, begin, pixels, arr):
for i in range(0, int(2 ** len(arr))):
if i > 0:
print('else')
if i != int(2 ** len(arr)) - 1:
print('if({} < ({} + ({}/{})*{}))'.format(arg, begin, pixels, int(2 ** len(arr)), i + 1))
print('begin')
for j in range(0, len(arr)... |
# Time: O(m * nlogn)
# Space: O(n)
class Solution(object):
def longestCommonSubpath(self, n, paths):
"""
:type n: int
:type paths: List[List[int]]
:rtype: int
"""
def RabinKarp(arr, x): # double hashing
hashes = tuple([reduce(lambda h,x: (h*p+x)%MOD, (a... | class Solution(object):
def longest_common_subpath(self, n, paths):
"""
:type n: int
:type paths: List[List[int]]
:rtype: int
"""
def rabin_karp(arr, x):
hashes = tuple([reduce(lambda h, x: (h * p + x) % MOD, (arr[i] for i in xrange(x)), 0) for p in P])
... |
class Song:
def __init__(self, json):
# playlist tracks not queryable over API
if not json:
raise LookupError
self.name = json['name']
self.artists = list(map(lambda artist: artist['name'], json['artists']))
self.album = json['album']['name']
def __str__(se... | class Song:
def __init__(self, json):
if not json:
raise LookupError
self.name = json['name']
self.artists = list(map(lambda artist: artist['name'], json['artists']))
self.album = json['album']['name']
def __str__(self) -> str:
return self.name + ' - ' + ', ... |
# test with
with open("test.txt") as f:
f.write("hello worlds")
f.read()
| with open('test.txt') as f:
f.write('hello worlds')
f.read() |
class Solution:
"""
@param numbers : An array of Integer
@param target : target = numbers[index1] + numbers[index2]
@return : [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, numbers, target):
# Hash map
# map = {}
# for i, n in enumerate(numbers):
... | class Solution:
"""
@param numbers : An array of Integer
@param target : target = numbers[index1] + numbers[index2]
@return : [index1 + 1, index2 + 1] (index1 < index2)
"""
def two_sum(self, numbers, target):
sorted_numbers = sorted(numbers)
l = 0
r = len(numbers) - 1
... |
class File(object):
def __init__(self):
self.filename = ''
self.server_filename = ''
self.rotate = 0
self.password = None
# file_encryption_key TBD
self.file_encryption_key = None
self.metas = {}
@property
def metas_values(self):
return "... | class File(object):
def __init__(self):
self.filename = ''
self.server_filename = ''
self.rotate = 0
self.password = None
self.file_encryption_key = None
self.metas = {}
@property
def metas_values(self):
return ('Title', 'Author', 'Subject', 'Keyword... |
windowWidth = 500
windowHeight = 500
ellipseSize = 200
def setup():
size(windowWidth , windowHeight)
smooth()
background(255)
fill(50, 80)
stroke(100)
strokeWeight(3)
noLoop()
def draw():
ellipse(windowWidth/2, windowHeight/2 - ellipseSize/2,
ellipseSize , ellipseSize);
ellipse(windowWidth/2 - ellipseSize/2, ... | window_width = 500
window_height = 500
ellipse_size = 200
def setup():
size(windowWidth, windowHeight)
smooth()
background(255)
fill(50, 80)
stroke(100)
stroke_weight(3)
no_loop()
def draw():
ellipse(windowWidth / 2, windowHeight / 2 - ellipseSize / 2, ellipseSize, ellipseSize)
ell... |
# Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
# Example 1:
# Input: n = 3
# Output: 5
#FORMULA is 2nCn/ n+1 catelon number
class Solution:
def numTrees(self, n: int) -> int:
res = 1
... | class Solution:
def num_trees(self, n: int) -> int:
res = 1
x = 2 * n
for i in range(n):
res = res * (x - 1)
res = res // (i + 1)
return res // (n + 1)
if __name__ == '__main__':
n = 3
print(solution().numTrees(n)) |
'''Constants used by TRender.
:copyright: 2015, Jeroen van der Heijden (Cesbit)
'''
LINE_IF = 1
LINE_ELSE = 2
LINE_ELIF = 4
LINE_END = 8
LINE_MACRO = 16
LINE_COMMENT = 32
LINE_BLOCK = 64
LINE_FOR = 128
LINE_PASTE = 256
LINE_TEXT = 512
LINE_INCLUDE = 1024
LINE_EXTEND = 2048
LINE_EMPTY = 4096
EOF_TEXT = 8192
ALWAYS_A... | """Constants used by TRender.
:copyright: 2015, Jeroen van der Heijden (Cesbit)
"""
line_if = 1
line_else = 2
line_elif = 4
line_end = 8
line_macro = 16
line_comment = 32
line_block = 64
line_for = 128
line_paste = 256
line_text = 512
line_include = 1024
line_extend = 2048
line_empty = 4096
eof_text = 8192
always_allo... |
test_cases = int(input())
sol = []
for test in range(test_cases):
budget = int(input())
useless = input()
prices = list(map(int,input().split()))
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if prices[i]+prices[j] == budget:
sol.append(str(i+1)+' '+st... | test_cases = int(input())
sol = []
for test in range(test_cases):
budget = int(input())
useless = input()
prices = list(map(int, input().split()))
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[i] + prices[j] == budget:
sol.append(str(i + 1... |
def pytest_assertrepr_compare(config, op, left, right):
"""Hook for PyCharm full diff
References:
https://stackoverflow.com/a/50625086/4249707"""
if op in ("==", "!="):
return ["{0} {1} {2}".format(left, op, right)]
| def pytest_assertrepr_compare(config, op, left, right):
"""Hook for PyCharm full diff
References:
https://stackoverflow.com/a/50625086/4249707"""
if op in ('==', '!='):
return ['{0} {1} {2}'.format(left, op, right)] |
n = int(input())
t = 0
a = 0
for _ in range(n):
s = input()
t += s.count('R')
a += s.count('B')
if t > a:
print('TAKAHASHI')
elif a > t:
print('AOKI')
else:
print('DRAW')
| n = int(input())
t = 0
a = 0
for _ in range(n):
s = input()
t += s.count('R')
a += s.count('B')
if t > a:
print('TAKAHASHI')
elif a > t:
print('AOKI')
else:
print('DRAW') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 14:55:39 2017
@author: ishxiao
~Email~: me@ishxiao.com
"""
| """
Created on Fri Oct 20 14:55:39 2017
@author: ishxiao
~Email~: me@ishxiao.com
""" |
ledger = {n: idx + 1 for idx, n in enumerate([1, 17, 0, 10, 18, 11, 6])}
spoken_number = list(ledger)[-1]
for turn in range(len(ledger), 30000000):
ledger[spoken_number], spoken_number = turn, turn - ledger.get(spoken_number, turn)
if turn == 2020 - 1:
print(f"Part 1: {spoken_number}") # 595
print(f"P... | ledger = {n: idx + 1 for (idx, n) in enumerate([1, 17, 0, 10, 18, 11, 6])}
spoken_number = list(ledger)[-1]
for turn in range(len(ledger), 30000000):
(ledger[spoken_number], spoken_number) = (turn, turn - ledger.get(spoken_number, turn))
if turn == 2020 - 1:
print(f'Part 1: {spoken_number}')
print(f'Par... |
n = int(input())
arr = map(int, input().split())
list1 = list(arr)
print(list1)
new_list = set(list1)
print(new_list)
new_list.remove(max(new_list))
print(max(new_list))
| n = int(input())
arr = map(int, input().split())
list1 = list(arr)
print(list1)
new_list = set(list1)
print(new_list)
new_list.remove(max(new_list))
print(max(new_list)) |
MODEL_FOLDER_NAME = 'models'
FASTTEXT_MODEL_NAME = 'fasttext.magnitude'
GLOVE_MODEL_NAME = 'glove.magnitude'
WORD2VEC_MODEL_NAME = 'word2vec.magnitude'
ELMO_MODEL_NAME = 'elmo.magnitude'
BERT_MODEL_NAME = ''
FLAIR_MODEL_NAME = 'news-forward'
COVE_MODEL_NAME = ''
UNIVERSAL_SENTENCE_ENCODER_MODEL_NAME = 'https://tfhub.de... | model_folder_name = 'models'
fasttext_model_name = 'fasttext.magnitude'
glove_model_name = 'glove.magnitude'
word2_vec_model_name = 'word2vec.magnitude'
elmo_model_name = 'elmo.magnitude'
bert_model_name = ''
flair_model_name = 'news-forward'
cove_model_name = ''
universal_sentence_encoder_model_name = 'https://tfhub.d... |
# coding=utf-8
class App:
TESTING = True
HOST_URL = "http://pay.lvye.com"
PAYEE = '169658002'
class PayClientConfig:
CHANNEL_NAME = 'lvye_pay_test'
ROOT_URL = "http://pay.lvye.com/api/__"
CHECKOUT_URL = 'http://pay.lvye.com/__/checkout/{sn}'
| class App:
testing = True
host_url = 'http://pay.lvye.com'
payee = '169658002'
class Payclientconfig:
channel_name = 'lvye_pay_test'
root_url = 'http://pay.lvye.com/api/__'
checkout_url = 'http://pay.lvye.com/__/checkout/{sn}' |
def calc_gc(sequence):
sequence = sequence.upper() # make all chars uppercase
n = sequence.count('T') + sequence.count('A') # count only A, T,
m = sequence.count('G') + sequence.count('C') # C, and G -- nothing else (no Ns, Rs, Ws, etc.)
return float(m) / float(n + m) if n+m else 0
... | def calc_gc(sequence):
sequence = sequence.upper()
n = sequence.count('T') + sequence.count('A')
m = sequence.count('G') + sequence.count('C')
return float(m) / float(n + m) if n + m else 0
def test_1():
result = round(calc_gc('NATGC'), 2)
assert result == 0.5, result
def test_2():
result ... |
# Use this to take notes on the Edpuzzle video. Try each example rather than just watching it - you will get much more out of it!
#
student = {'name': 'John', 'age': 25, 'courses': ['math', 'CompSci']}
for key, value in student.items():
print(key, value) | student = {'name': 'John', 'age': 25, 'courses': ['math', 'CompSci']}
for (key, value) in student.items():
print(key, value) |
PARSING_SCHEME = {
'name': 'a',
'games_played': 'td[data-stat="g"]:first',
'minutes_played': 'td[data-stat="mp"]:first',
'field_goals': 'td[data-stat="fg"]:first',
'field_goal_attempts': 'td[data-stat="fga"]:first',
'field_goal_percentage': 'td[data-stat="fg_pct"]:first',
'three_point_field_... | parsing_scheme = {'name': 'a', 'games_played': 'td[data-stat="g"]:first', 'minutes_played': 'td[data-stat="mp"]:first', 'field_goals': 'td[data-stat="fg"]:first', 'field_goal_attempts': 'td[data-stat="fga"]:first', 'field_goal_percentage': 'td[data-stat="fg_pct"]:first', 'three_point_field_goals': 'td[data-stat="fg3"]:... |
class NuGetPackage(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self,
'mono', 'nuget',
'2.8.5',
'ea1d244b066338c9408646afdcf8acae6299f7fb',
configure = '')
def build(self):
self.sh ('%{make} PREFIX=%{package_prefix}')
def install(self):
self.sh ('%{makeinstall} PREFIX... | class Nugetpackage(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self, 'mono', 'nuget', '2.8.5', 'ea1d244b066338c9408646afdcf8acae6299f7fb', configure='')
def build(self):
self.sh('%{make} PREFIX=%{package_prefix}')
def install(self):
self.sh('%{makeinst... |
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
... | class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f'I am a cat. My name is {self.name}. I am {self.age} years old.')
def make_sound(self):
print('Meow')
class Dog:
def __init__(self, name, age):
self.name = name
... |
#!/usr/bin/python
# Copyright 2015 Neuhold Markus and Kleinsasser Mario
#
# 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 ... | smsgatewayabspath = None
watchdog_thread = None
watchdog_thread_notify = None
watchdog_route_thread = {}
watchdog_route_thread_notify = {}
watchdog_route_thread_queue = {}
router_thread = None
rdb = None
cleanupseconds = None
wisid = None
wisport = None
wisipaddress = None
pissendtimeout = None
ldapenabled = None
ldaps... |
class DistributedRouter:
def allow_migrate(self, db, app_label, model_name=None, **hints):
if model_name in ['user', 'settings']:
return db == 'parser'
if model_name in ['search', 'betdata']:
return db == 'betdata'
return True | class Distributedrouter:
def allow_migrate(self, db, app_label, model_name=None, **hints):
if model_name in ['user', 'settings']:
return db == 'parser'
if model_name in ['search', 'betdata']:
return db == 'betdata'
return True |
contador_externo = 0
contador_interno = 0
while contador_externo < 5:
while contador_interno < 6:
print(contador_externo, contador_interno)
contador_interno += 1
contador_externo += 1
contador_interno = 0
| contador_externo = 0
contador_interno = 0
while contador_externo < 5:
while contador_interno < 6:
print(contador_externo, contador_interno)
contador_interno += 1
contador_externo += 1
contador_interno = 0 |
# Python: QuickSort
def quick_sort(arr):
start = 0
end = len(arr) - 1
__quick_sort(arr, start, end)
def __quick_sort(arr, start, end):
if start < end:
pertition_index = __pertition(arr, start, end)
__quick_sort(arr, start, pertition_index - 1)
__quick_sort(arr, pertition_inde... | def quick_sort(arr):
start = 0
end = len(arr) - 1
__quick_sort(arr, start, end)
def __quick_sort(arr, start, end):
if start < end:
pertition_index = __pertition(arr, start, end)
__quick_sort(arr, start, pertition_index - 1)
__quick_sort(arr, pertition_index + 1, end)
def __pert... |
def heapify(array, size, index):
largest = index
left = 2 * index + 1
right = 2 * index + 2
if left < size and array[index] < array[left]:
largest = left
if right < size and array[largest] < array[right]:
largest = right
if largest != index:
array[index], array[largest] ... | def heapify(array, size, index):
largest = index
left = 2 * index + 1
right = 2 * index + 2
if left < size and array[index] < array[left]:
largest = left
if right < size and array[largest] < array[right]:
largest = right
if largest != index:
(array[index], array[largest])... |
'''
Description : Use Of Local Scope
Function Date : 05 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
'''
x = 50
def func(x):
print ('x is', x)
x = 2
print ('Changed local x to', x)
func(x)
print ('x is still', x) | """
Description : Use Of Local Scope
Function Date : 05 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
"""
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x) |
"""
321. Create Maximum Number
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits.
Note: You should try to optimize yo... | """
321. Create Maximum Number
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits.
Note: You should try to optimize yo... |
catName1 = input()
print('Enter the name of cat 2:')
catName2 = input()
print('Enter the name of cat 3:')
catName3 = input()
print('Enter the name of cat 4:')
catName4 = input()
print('Enter the name of cat 5:')
catName5 = input()
print('Enter the name of cat 6:')
catName6 = input()
print(catName1 + ' ' + catName2 + ' ... | cat_name1 = input()
print('Enter the name of cat 2:')
cat_name2 = input()
print('Enter the name of cat 3:')
cat_name3 = input()
print('Enter the name of cat 4:')
cat_name4 = input()
print('Enter the name of cat 5:')
cat_name5 = input()
print('Enter the name of cat 6:')
cat_name6 = input()
print(catName1 + ' ' + catName... |
# -*- coding: utf-8 -*-
#
# __init__.py
#
# This module is part of skxtend.
#
"""
Initializer of skxtend tests.
"""
__author__ = 'Severin E. R. Langberg'
__email__ = 'Langberg91@gmail.no'
__status__ = 'Operational'
| """
Initializer of skxtend tests.
"""
__author__ = 'Severin E. R. Langberg'
__email__ = 'Langberg91@gmail.no'
__status__ = 'Operational' |
TYPE_NAME = "mock"
def handler(value, **kwargs):
return "mock"
| type_name = 'mock'
def handler(value, **kwargs):
return 'mock' |
# ETA represents the learning rate. Higher values penalize feature weights more strongly
# Create your housing DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary for each tree (boosting round)
params = {"objective":"reg:linear", "max_depth":3}
# Create list of e... | housing_dmatrix = xgb.DMatrix(data=X, label=y)
params = {'objective': 'reg:linear', 'max_depth': 3}
eta_vals = [0.001, 0.01, 0.1]
best_rmse = []
for curr_val in eta_vals:
params['eta'] = curr_val
cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=3, num_boost_round=10, early_stopping_rounds=5, met... |
class ProjectAttributes:
def __init__(self, project_instance):
self.project_instance = project_instance
self.proj_name = project_instance.get_project_name()
self.proj_loc = project_instance.get_project_loc()
self.source_file_count = len(project_instance.get_project_source_files().g... | class Projectattributes:
def __init__(self, project_instance):
self.project_instance = project_instance
self.proj_name = project_instance.get_project_name()
self.proj_loc = project_instance.get_project_loc()
self.source_file_count = len(project_instance.get_project_source_files().ge... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Solution1: No more to say.
class Solution:
"""
@param inorder: A list of integers that inorder traversal of a tree
@param postorder: A list of integers that posto... | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param inorder: A list of integers that inorder traversal of a tree
@param postorder: A list of integers that postorder traversal of a tree
... |
#
# PySNMP MIB module NBASE-EXP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBASE-EXP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
#
# PySNMP MIB module EXTREME-LACP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-LACP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:54:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is used as the top-level gyp file for building WebView in the Android
# tree. It should depend only on native code, as we cannot currently generat... | {'targets': [{'target_name': 'All', 'type': 'none', 'dependencies': ['android_webview.gyp:libwebviewchromium', '../base/base.gyp:base_java_activity_state', '../base/base.gyp:base_java_memory_pressure_level_list', '../content/content.gyp:page_transition_types_java', '../content/content.gyp:result_codes_java', '../conten... |
class Solution:
# @param {integer[]} nums
# @return {integer}
def majorityElement(self, nums):
candidate = None
count = 0
for num in nums:
if num == candidate:
count += 1
elif count == 0:
candidate = num
count = ... | class Solution:
def majority_element(self, nums):
candidate = None
count = 0
for num in nums:
if num == candidate:
count += 1
elif count == 0:
candidate = num
count = 1
else:
count -= 1
... |
class Sql:
custlist = "SELECT * FROM cust";
custlistone = "SELECT * FROM cust WHERE id= '%s' ";
custinsert = "INSERT INTO cust VALUES ('%s','%s','%s')";
custdelete = "DELETE FROM cust WHERE id= '%s' ";
custupdate = "UPDATE cust SET pwd='%s',name='%s' WHERE id='%s' ";
itemlist = "SELECT * FROM i... | class Sql:
custlist = 'SELECT * FROM cust'
custlistone = "SELECT * FROM cust WHERE id= '%s' "
custinsert = "INSERT INTO cust VALUES ('%s','%s','%s')"
custdelete = "DELETE FROM cust WHERE id= '%s' "
custupdate = "UPDATE cust SET pwd='%s',name='%s' WHERE id='%s' "
itemlist = 'SELECT * FROM item'
... |
'''
@author: Tibor Hercz // Tiboonn
@Link: https://github.com/Tiboonn/AWS-DeepRacer
@License: N/D
'''
def reward_function(params):
'''
Example of rewarding the agent to follow center line
'''
# Read input parameters
track_width = params['track_width']
distance_from_center = params[... | """
@author: Tibor Hercz // Tiboonn
@Link: https://github.com/Tiboonn/AWS-DeepRacer
@License: N/D
"""
def reward_function(params):
"""
Example of rewarding the agent to follow center line
"""
track_width = params['track_width']
distance_from_center = params['distance_from_center']
a... |
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
punc = set(['.', '!', '?', ' '])
while True:
sIn = input().strip()
lis = []
last = 0
for i, char in enumerate(sIn):
if char in punc:
if i - last > 0:
lis.append(sIn[last: i])
last =... | vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
punc = set(['.', '!', '?', ' '])
while True:
s_in = input().strip()
lis = []
last = 0
for (i, char) in enumerate(sIn):
if char in punc:
if i - last > 0:
lis.append(sIn[last:i])
last = i + 1
... |
"""
Defines two dictionaries for converting
between text and integer sequences.
"""
char_map_str = """
' 0
<SPACE> 1
a 2
b 3
c 4
d 5
e 6
f 7
g 8
h 9
i 10
j 11
k 12
l 13
m 14
n 15
o 16
p 17
q 18
r 19
s 20
t 21
u 22
v 23
w 24
x 25
y 26
z 27
"""
# the "blank" character is mapped to 28
char_map = {}
index_map = {}
for l... | """
Defines two dictionaries for converting
between text and integer sequences.
"""
char_map_str = "\n' 0\n<SPACE> 1\na 2\nb 3\nc 4\nd 5\ne 6\nf 7\ng 8\nh 9\ni 10\nj 11\nk 12\nl 13\nm 14\nn 15\no 16\np 17\nq 18\nr 19\ns 20\nt 21\nu 22\nv 23\nw 24\nx 25\ny 26\nz 27\n"
char_map = {}
index_map = {}
for line in char_map_s... |
@graph
def context_from_path():
sg = Shotgun()
sgfs = SGFS(root=sandbox, shotgun=sg)
fix = Fixture(sg)
proj = fix.Project('Example Project')
seq = proj.Sequence("AA")
shot = seq.Shot('AA_001')
step = fix.Step('Anm')
task = shot.Task('Do Work', id=123, step=step)
task2 = sho... | @graph
def context_from_path():
sg = shotgun()
sgfs = sgfs(root=sandbox, shotgun=sg)
fix = fixture(sg)
proj = fix.Project('Example Project')
seq = proj.Sequence('AA')
shot = seq.Shot('AA_001')
step = fix.Step('Anm')
task = shot.Task('Do Work', id=123, step=step)
task2 = shot.Task('Do... |
# -*- coding: utf-8 -*-
def command():
return "create-farm"
def init_argument(parser):
parser.add_argument("--farm-name", required=True)
parser.add_argument("--template-no", required=True)
parser.add_argument("--comment")
def execute(requester, args):
farm_name = args.farm_name
template_no = ... | def command():
return 'create-farm'
def init_argument(parser):
parser.add_argument('--farm-name', required=True)
parser.add_argument('--template-no', required=True)
parser.add_argument('--comment')
def execute(requester, args):
farm_name = args.farm_name
template_no = args.template_no
comm... |
#!/usr/bin/env python
print("This is example file 3")
| print('This is example file 3') |
#!/usr/bin/env python
#####################################
# Installation module for empire
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="Ian Smith"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update Empire - post exploitation python/powershell for windows and nix/os... | author = 'Ian Smith'
description = 'This module will install/update Empire - post exploitation python/powershell for windows and nix/osx'
install_type = 'GIT'
repository_location = 'https://github.com/BC-SECURITY/Empire'
install_location = 'empire3'
debian = 'git'
fedora = 'git'
after_commands = 'cd {INSTALL_LOCATION},... |
def imosh_test(
name,
srcs=[],
data=[],
**kargs):
if len(srcs) != 1:
fail("Exactly one source file must be given.")
native.genrule(
name = name + "_genrule_sh",
srcs = ["//bin:imosh_test_generate"],
outs = [name + "_genrule.sh"],
cmd = "$(BINDIR)/bin/imosh_test_generate "... | def imosh_test(name, srcs=[], data=[], **kargs):
if len(srcs) != 1:
fail('Exactly one source file must be given.')
native.genrule(name=name + '_genrule_sh', srcs=['//bin:imosh_test_generate'], outs=[name + '_genrule.sh'], cmd='$(BINDIR)/bin/imosh_test_generate ' + PACKAGE_NAME + '/' + srcs[0] + ' >$@')
... |
# -*- coding: utf-8 -*-
name = 'usdview'
version = '20.05'
requires = [
'pyside-1.2',
'usd-20.05',
'ocio_configs',
'turret_usd'
]
def commands():
env.DEFAULT_USD.set('{root}/bin/DefaultUSD.usda')
| name = 'usdview'
version = '20.05'
requires = ['pyside-1.2', 'usd-20.05', 'ocio_configs', 'turret_usd']
def commands():
env.DEFAULT_USD.set('{root}/bin/DefaultUSD.usda') |
def make_ends(nums):
first = nums[0]
last = nums[len(nums)-1]
newArr = []
newArr.append(first)
newArr.append(last)
return newArr
| def make_ends(nums):
first = nums[0]
last = nums[len(nums) - 1]
new_arr = []
newArr.append(first)
newArr.append(last)
return newArr |
class EnumBase(object):
class Meta:
allowed_types = tuple()
zero_value = None
@classmethod
def names(klass, with_zero_value=True):
def _get_names():
names = []
for n in dir(klass):
if '__' not in n and n != 'Meta':
value = getattr(klass, n)
if isinstance(value,... | class Enumbase(object):
class Meta:
allowed_types = tuple()
zero_value = None
@classmethod
def names(klass, with_zero_value=True):
def _get_names():
names = []
for n in dir(klass):
if '__' not in n and n != 'Meta':
value ... |
# intro to function
def my_function():
print("Hello, this is function")
# calling function
my_function() | def my_function():
print('Hello, this is function')
my_function() |
class Solution:
def numDifferentIntegers(self, word: str) -> int:
stripped = {}
i = 0
for c in word:
if c in {"0":1, "1":1, "2":1, "3":1, "4":1, "5":1, "6":1, "7":1, "8":1, "9":1}:
if i in stripped:
if stripped[i] == "0":
... | class Solution:
def num_different_integers(self, word: str) -> int:
stripped = {}
i = 0
for c in word:
if c in {'0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1}:
if i in stripped:
if stripped[i] == '0':
... |
"""
Illustrates how to embed Beaker cache functionality within
the Query object, allowing full cache control as well as the
ability to pull "lazy loaded" attributes from long term cache
as well.
In this demo, the following techniques are illustrated:
* Using custom subclasses of Query
* Basic technique of circumvent... | """
Illustrates how to embed Beaker cache functionality within
the Query object, allowing full cache control as well as the
ability to pull "lazy loaded" attributes from long term cache
as well.
In this demo, the following techniques are illustrated:
* Using custom subclasses of Query
* Basic technique of circumvent... |
## @package serde
# Module caffe2.python.predictor.serde
def serialize_protobuf_struct(protobuf_struct):
return protobuf_struct.SerializeToString()
def deserialize_protobuf_struct(serialized_protobuf, struct_type):
deser = struct_type()
deser.ParseFromString(serialized_protobuf)
r... | def serialize_protobuf_struct(protobuf_struct):
return protobuf_struct.SerializeToString()
def deserialize_protobuf_struct(serialized_protobuf, struct_type):
deser = struct_type()
deser.ParseFromString(serialized_protobuf)
return deser |
# You can import and use this in a DAG in the parent folder like usual in
# Python, i.e. `import python_callables.compliance`
def check_port_22_open():
pass
| def check_port_22_open():
pass |
#!/usr/bin/python
with open("vita.md") as fp:
lines = fp.readlines()
lines2 = lines[6:]
lines3 = lines[8:]
# print lines2
with open("vita_noyaml.md", "w") as fp:
fp.writelines(lines2)
# print lines3
with open("vita_noyaml_nocvaspdf.md", "w") as fp:
fp.writelines(lines3)
# onepage
with open("vita_onepa... | with open('vita.md') as fp:
lines = fp.readlines()
lines2 = lines[6:]
lines3 = lines[8:]
with open('vita_noyaml.md', 'w') as fp:
fp.writelines(lines2)
with open('vita_noyaml_nocvaspdf.md', 'w') as fp:
fp.writelines(lines3)
with open('vita_onepage.md') as fp:
lines = fp.readlines()
lines2 = lines[5:]
lin... |
__author__ = 'nikaashpuri'
'''
TCP_SERVER_IP = '162.251.84.104'
SYSTEM_PATH_TO_APPEND = '/public_html/aquabrim_project'
LOG_FILE_LOCATION = '/logs/django_log'
TCP_SERVER_FILE_PATH = '/public_html/aquabrim_project/machine/tcp_ip_server.py'
DATABASE_PATH = '/sites_database/dev.db'
'''
TCP_SERVER_IP = 'localhost'
LOG_FI... | __author__ = 'nikaashpuri'
"\nTCP_SERVER_IP = '162.251.84.104'\nSYSTEM_PATH_TO_APPEND = '/public_html/aquabrim_project'\nLOG_FILE_LOCATION = '/logs/django_log'\nTCP_SERVER_FILE_PATH = '/public_html/aquabrim_project/machine/tcp_ip_server.py'\nDATABASE_PATH = '/sites_database/dev.db'\n"
tcp_server_ip = 'localhost'
log_fi... |
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
if not candidates:
return []
candidates.sort()
n = len(candidates)
res = []
def solve... | class Solution:
def combination_sum(self, candidates, target):
if not candidates:
return []
candidates.sort()
n = len(candidates)
res = []
def solve(start, target, tmp):
if target < 0:
return
if target == 0:
... |
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2018 Datadog, Inc.
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD L... | basic_metrics = {'cpu.extra': {'s_type': 'delta', 'unit': 'millisecond', 'rollup': 'summation', 'entity': ['VirtualMachine']}, 'cpu.ready': {'s_type': 'delta', 'unit': 'millisecond', 'rollup': 'summation', 'entity': ['VirtualMachine', 'HostSystem']}, 'cpu.usage': {'s_type': 'rate', 'unit': 'percent', 'rollup': 'average... |
# !/usr/bin/env python3
# -*- cosing: utf-8 -*-
fileptr = open("file2.txt", "a")
fileptr.write("Python has an easy syntax and user-friendly interaction.")
fileptr.close() | fileptr = open('file2.txt', 'a')
fileptr.write('Python has an easy syntax and user-friendly interaction.')
fileptr.close() |
main_menu = [
["1", "Spam Tools", "Amino-Tools"],
["2", "Chat Tools"],
["3", "Activity Tools"],
["4", "profile Tools"],
["5", "raid Tools"],
["0", "Exit"]
]
spam_tools_menu = [
["1", "Spam Bot", "Amino-Tools"],
["2", "Wiki Spam Bot"],
["3", "Wall Spam Bot"],
["4", "Blog Spam Bot"]
]
chat_tools_menu = [
[... | main_menu = [['1', 'Spam Tools', 'Amino-Tools'], ['2', 'Chat Tools'], ['3', 'Activity Tools'], ['4', 'profile Tools'], ['5', 'raid Tools'], ['0', 'Exit']]
spam_tools_menu = [['1', 'Spam Bot', 'Amino-Tools'], ['2', 'Wiki Spam Bot'], ['3', 'Wall Spam Bot'], ['4', 'Blog Spam Bot']]
chat_tools_menu = [['1', 'ChatId Finder'... |
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Google.
# A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
# Given the root to a binary tree, count the number of unival subtrees.
# For example, the following tree has 5... | class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def print(self):
print(self.left, '<--', self.value, '-->', self.right)
tree = node(False, node(True), node(False, node(True, node(True), node(True)), node(False... |
"""
By default, Disco looks at an input URL and extracts its scheme in order to figure out which input stream to use.
When Disco determines the URL scheme, it tries to import the name `input_stream` from `disco.schemes.scheme_[SCHEME]`, where `[SCHEME]` is replaced by the scheme identified.
For instance, an input URL ... | """
By default, Disco looks at an input URL and extracts its scheme in order to figure out which input stream to use.
When Disco determines the URL scheme, it tries to import the name `input_stream` from `disco.schemes.scheme_[SCHEME]`, where `[SCHEME]` is replaced by the scheme identified.
For instance, an input URL ... |
# Natural Language Toolkit: Shoebox Errors
#
# Copyright (C) 2001-2006 NLTK Project
# Author: Stuart Robinson <Stuart.Robinson@mpi.nl>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
This module provides Shoebox exceptions.
"""
# -----------------------------------------------------------... | """
This module provides Shoebox exceptions.
"""
class Shoeboxerror(Exception):
"""
This is the base class for all Shoebox errors.
"""
def __init__(self):
self._msg = ''
class Nonuniqueentryerror(ShoeboxError):
"""
???
"""
def __init__(self):
pass
class Validationerr... |
#Declare variables to hold the file name and access mode
fileName = "GuestList.txt"
accessMode = "w"
#Open the file for writing
myFile = open(fileName, accessMode)
#Write the guest names and ages to the file
#I can write an entire record in one write statement
myFile.write("Doyle McCarty,27\n")
myFile.write("Jodi M... | file_name = 'GuestList.txt'
access_mode = 'w'
my_file = open(fileName, accessMode)
myFile.write('Doyle McCarty,27\n')
myFile.write('Jodi Mills,25\n')
myFile.write('Nicholas Rose,32\n')
myFile.write('Kian Goddard')
myFile.write(',36\n')
myFile.write('Zuha Hanania')
myFile.write(',26\n')
myFile.close() |
""" fizzbuzz for 1 to 100
fizz on 3
buzz on 5
fiizzbuzz on 15
"""
for i in range(1, 101):
if i % 15 == 0:
print("fizzbuzz")
continue
if i % 3 == 0:
print('fizz')
continue
if i % 5 == 0:
print('buzz')
continue
print(i)
| """ fizzbuzz for 1 to 100
fizz on 3
buzz on 5
fiizzbuzz on 15
"""
for i in range(1, 101):
if i % 15 == 0:
print('fizzbuzz')
continue
if i % 3 == 0:
print('fizz')
continue
if i % 5 == 0:
print('buzz')
continue
print(i) |
#Date: 033122
#Difficulty: Medium
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
start=end=0
for i in range(len(s)):
length1=self.expandFromMiddle(s,i,i)
length2=self.expandFromMiddle(s,i,i+1)
... | class Solution(object):
def longest_palindrome(self, s):
"""
:type s: str
:rtype: str
"""
start = end = 0
for i in range(len(s)):
length1 = self.expandFromMiddle(s, i, i)
length2 = self.expandFromMiddle(s, i, i + 1)
max_length = ma... |
def set_dimensions(dimensions):
"""
Set properly dimensions that we want to load
@dimensions: list
"""
result = []
for i in dimensions:
d = {
'name': i
}
result.append(d)
return result
def set_metrics(metrics):
"""
Set properly metrics that we wa... | def set_dimensions(dimensions):
"""
Set properly dimensions that we want to load
@dimensions: list
"""
result = []
for i in dimensions:
d = {'name': i}
result.append(d)
return result
def set_metrics(metrics):
"""
Set properly metrics that we want to load
@metrics... |
# based on: https://github.com/tigertv/secretpy/blob/master/secretpy/ciphers/autokey.py
class cipher_autokey:
def process(self, alphabet, key, text, isEncrypt):
ans = ""
for i in range(len(text)):
m = text[i]
if i < len(key):
k = key[i]
else:
... | class Cipher_Autokey:
def process(self, alphabet, key, text, isEncrypt):
ans = ''
for i in range(len(text)):
m = text[i]
if i < len(key):
k = key[i]
elif isEncrypt == 1:
k = text[i - len(key)]
else:
k = ... |
class Settings:
"""
The Settings class offer a convenient method to child class to attribute
values from a dictionary to the class variables for which name and key match
"""
def setProperties(self, settings: dict):
"""
set variable value with dictionary value if the key is the same ... | class Settings:
"""
The Settings class offer a convenient method to child class to attribute
values from a dictionary to the class variables for which name and key match
"""
def set_properties(self, settings: dict):
"""
set variable value with dictionary value if the key is the same... |
class User:
user_list =[]
user_list = []
def __init__(self, user_name, email, password):
'''
saving user credentials into user_list for login
'''
self.user_name = user_name
self.email = email
self.password = password
def sav... | class User:
user_list = []
user_list = []
def __init__(self, user_name, email, password):
"""
saving user credentials into user_list for login
"""
self.user_name = user_name
self.email = email
self.password = password
def save_user(self):
"""
... |
init_config = {
'username': 'email@gmail.com',
'pwd': 'password',
'mongodb': {
'host': 'mongodb://localhost:27017/'
}
} | init_config = {'username': 'email@gmail.com', 'pwd': 'password', 'mongodb': {'host': 'mongodb://localhost:27017/'}} |
#!/usr/bin/env python
__all__ = ["dendrogram", "dotplot", "drawable", "letter", "logo"]
__copyright__ = "Copyright 2007-2020, The Cogent Project"
__contributors__ = [
"Peter Maxwell",
"Gavin Huttley",
"Rob Knight",
"Zongzhi Liu",
"Matthew Wakefield",
"Stephanie Wilson",
"Rahul Ghangas",
... | __all__ = ['dendrogram', 'dotplot', 'drawable', 'letter', 'logo']
__copyright__ = 'Copyright 2007-2020, The Cogent Project'
__contributors__ = ['Peter Maxwell', 'Gavin Huttley', 'Rob Knight', 'Zongzhi Liu', 'Matthew Wakefield', 'Stephanie Wilson', 'Rahul Ghangas', 'Sheng Han Moses Koh']
__license__ = 'BSD-3'
__version_... |
#
# PySNMP MIB module Dell-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:55:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, constraints_intersection, single_value_constraint, value_range_constraint) ... |
description = 'setup for the cache server'
group = 'special'
devices = dict(
DB=device('nicos.services.cache.server.FlatfileCacheDatabase',
description='On disk storage for Cache Server',
storepath=configdata('config.DATA_PATH') + 'cache',
loglevel='info', ),
Server=de... | description = 'setup for the cache server'
group = 'special'
devices = dict(DB=device('nicos.services.cache.server.FlatfileCacheDatabase', description='On disk storage for Cache Server', storepath=configdata('config.DATA_PATH') + 'cache', loglevel='info'), Server=device('nicos.services.cache.server.CacheServer', db='DB... |
# 1.5 Find One Missing Number from 1 to 10
def find_missing_number(list_numbers):
list_sum = 0
for number in list_numbers:
list_sum += number
return 55 - list_sum
| def find_missing_number(list_numbers):
list_sum = 0
for number in list_numbers:
list_sum += number
return 55 - list_sum |
## Prime number is divide by 1 and itself
## Display 50 prime numbers in 5 lines, each containing 10 numbers
NUMBER_OF_PRIMES = 50 # Number of primes to display
NUMBER_OF_PRIMES_PER_LINE = 10 # Display 10 per line
count = 0 # Count number of prime numbers
number = 2 # a number to test prime number
while count < NUMB... | number_of_primes = 50
number_of_primes_per_line = 10
count = 0
number = 2
while count < NUMBER_OF_PRIMES:
is_prime = True
divisor = 2
while divisor <= number / 2:
if number % divisor == 0:
is_prime = False
break
divisor += 1
if isPrime:
count += 1
... |
"""
C++ FOREVER
"""
def hello():
"""
UNREACHABLE GNU Lesser General Public License v3.0
http://opensource.org/licenses/MIT-LICENSE
"""
print("Haskell TOP") | """
C++ FOREVER
"""
def hello():
"""
UNREACHABLE GNU Lesser General Public License v3.0
http://opensource.org/licenses/MIT-LICENSE
"""
print('Haskell TOP') |
a =[72,73,75,84,85,87,104,105,107,116,117,119]
b =[97,98,99,100,101,102,103]
c =[97,98,99,100,101,103,106]
d =[65,72,74,75,77,79,90,97,104,106,107,109,111,122]
e =[66,67,78,79,84,85,88,89,98,99,110,111,116,117,120,121]
f =[104,105,106,107,108,109,110,111]
g =[112,113,114,117,118,119]
res = [bytearray([a1, b1, ... | a = [72, 73, 75, 84, 85, 87, 104, 105, 107, 116, 117, 119]
b = [97, 98, 99, 100, 101, 102, 103]
c = [97, 98, 99, 100, 101, 103, 106]
d = [65, 72, 74, 75, 77, 79, 90, 97, 104, 106, 107, 109, 111, 122]
e = [66, 67, 78, 79, 84, 85, 88, 89, 98, 99, 110, 111, 116, 117, 120, 121]
f = [104, 105, 106, 107, 108, 109, 110, 111]
... |
class AttnDecoderRNN(nn.Module):
def __init__(self, dec_hidden_size, enc_hidden_size, dec_output_size, dropout_p=0):
super(AttnDecoderRNN, self).__init__()
self.hidden_size = dec_hidden_size
self.output_size = dec_output_size
self.dropout_p = dropout_p
self.lin_decoder = nn... | class Attndecoderrnn(nn.Module):
def __init__(self, dec_hidden_size, enc_hidden_size, dec_output_size, dropout_p=0):
super(AttnDecoderRNN, self).__init__()
self.hidden_size = dec_hidden_size
self.output_size = dec_output_size
self.dropout_p = dropout_p
self.lin_decoder = nn.... |
class FailureMessageAccessor(object,IDisposable):
""" Restricted accessor for FailureMessage. """
def CloneFailureMessage(self):
"""
CloneFailureMessage(self: FailureMessageAccessor) -> FailureMessage
Creates a copy of the FailureMessage.
Returns: Copy of the FailureMesassge.
"""
pass
d... | class Failuremessageaccessor(object, IDisposable):
""" Restricted accessor for FailureMessage. """
def clone_failure_message(self):
"""
CloneFailureMessage(self: FailureMessageAccessor) -> FailureMessage
Creates a copy of the FailureMessage.
Returns: Copy of the FailureMesassge.
"""
... |
"""
This module provides the Status class, which encapsulates
a status code for Icinga.
"""
class Status(object):
"""
Encapsulates an Icinga status, which holds a name and
an exit code.
"""
def __init__(self, name, exit_code):
"""
Creates a new status object for Icinga with the gi... | """
This module provides the Status class, which encapsulates
a status code for Icinga.
"""
class Status(object):
"""
Encapsulates an Icinga status, which holds a name and
an exit code.
"""
def __init__(self, name, exit_code):
"""
Creates a new status object for Icinga with the giv... |
_base_ = [
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
type='FasterRCNN',
backbone=dict(
type='SwinTransformer',
embed_dims=128,
depths=[2, 2, 18, 2],
num_heads=[4, 8, 16, 32],
window_size=7,
mlp_ratio=4,
qkv_bias=True,
... | _base_ = ['../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
model = dict(type='FasterRCNN', backbone=dict(type='SwinTransformer', embed_dims=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, mlp_ratio=4, qkv_bias=True, qk_scale=None, drop_rat... |
#!/usr/bin/env python3
# '+=' for variables, this operator adds a value to,
# then sets variable name to new value.
# this formula shortcut can be used with any
# mathmatical operator.
# string example
y = 'one'
y += 'two' # adding to and equaling
print(y)
# int example
x = 1 # x has value of one
x += 2 # same as x... | y = 'one'
y += 'two'
print(y)
x = 1
x += 2
print(x) |
class SimpleButton(object):
"""Represents a single button that is connected to the ESP32"""
def __init__(self, pin):
self.pin = pin
def read_pressed(self):
print("Reading button on pin {}".format(self.pin))
# TODO: Actually call MicroPython code to get the value
return Fa... | class Simplebutton(object):
"""Represents a single button that is connected to the ESP32"""
def __init__(self, pin):
self.pin = pin
def read_pressed(self):
print('Reading button on pin {}'.format(self.pin))
return False |
def execute(fn, *args):
return fn(*args)
def say_hello(name, my_name):
print(f"Hello, {name}, I am {my_name}")
def say_bye(name):
print(f"Bye, {name}")
execute(say_hello, "Peter", "George")
execute(say_bye, "Peter")
| def execute(fn, *args):
return fn(*args)
def say_hello(name, my_name):
print(f'Hello, {name}, I am {my_name}')
def say_bye(name):
print(f'Bye, {name}')
execute(say_hello, 'Peter', 'George')
execute(say_bye, 'Peter') |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 25 11:35:11 2021
@author: shangfr
"""
def ui_prediction():
pass
if __name__ == "__main__":
ui_prediction()
| """
Created on Mon Oct 25 11:35:11 2021
@author: shangfr
"""
def ui_prediction():
pass
if __name__ == '__main__':
ui_prediction() |
#Write a function that finds if a given string argument is Palindrome. A Palindrome string is equal to its reverse, that is its reading is the same backward as forward.
#For example: efe, hannah, ava, anna are palindromes.
#Test your function with above examples and test with at least 3 different
# non-Palindrome exa... | def check_palindrome(str_to_test):
reverse_str = str_to_test[::-1]
if reverse_str == str_to_test:
print(f'{str_to_test} is a palindrome')
else:
print(f'{str_to_test} is NOT a palindrome')
check_palindrome('efe')
check_palindrome('hannah')
check_palindrome('ava')
check_palindrome('anna')
chec... |
c_keyword_set = {
'auto',
'break',
'case',
'char',
'const',
'continue',
'default',
'define',
'do',
'double',
'elif',
'else',
'endif',
'enum',
'error',
'extern',
'float',
'for',
'goto',
'if',
'ifdef',
'ifndef',
'include',
'in... | c_keyword_set = {'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'define', 'do', 'double', 'elif', 'else', 'endif', 'enum', 'error', 'extern', 'float', 'for', 'goto', 'if', 'ifdef', 'ifndef', 'include', 'inline', 'int', 'line', 'long', 'noalias', 'pragma', 'register', 'restrict', 'return', 'short', 'si... |
# Copyright 2017 The Forseti Security Authors. 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 ap... | """Fake groups data.
TODO: consolidate with other fake group test data.
"""
fake_groups_db_rows = [{'group_id': '1111aaaa1', 'member_role': 'OWNER', 'member_type': 'USER', 'member_email': 'owneruser@foo.xyz'}, {'group_id': '2222bbbb2', 'member_role': 'MEMBER', 'member_type': 'GROUP', 'member_email': 'group2@foo.xyz'},... |
__version_tuple__ = (0, 6, 0, 'alpha.5')
__version__ = '0.6.0-alpha.5'
__version_tuple_js__ = (0, 6, 0, 'alpha.4')
__version_js__ = '0.6.0-alpha.4'
# kept for embedding in offline mode, we don't care about the patch version since it should be compatible
__version_threejs__ = '0.97'
| __version_tuple__ = (0, 6, 0, 'alpha.5')
__version__ = '0.6.0-alpha.5'
__version_tuple_js__ = (0, 6, 0, 'alpha.4')
__version_js__ = '0.6.0-alpha.4'
__version_threejs__ = '0.97' |
def read():
for dx in [1, 3, 5, 7]:
x = 0
tree = 0
with open('input.txt') as fh:
first_line = True
for line in fh.readlines():
if first_line:
first_line = False
continue
x = (x + dx) % len(line.s... | def read():
for dx in [1, 3, 5, 7]:
x = 0
tree = 0
with open('input.txt') as fh:
first_line = True
for line in fh.readlines():
if first_line:
first_line = False
continue
x = (x + dx) % len(line.st... |
""" dict functions """
def flatten_dict(nested: dict) -> dict:
"""Take a nested dictionary and flatten it. For example:
{'a': {'b': 'c'}} will be flattened to {'a_b': c}
Args:
nested: a dictionary to be flattened
Returns:
Dict. flattened version of the original dictionary
"""
... | """ dict functions """
def flatten_dict(nested: dict) -> dict:
"""Take a nested dictionary and flatten it. For example:
{'a': {'b': 'c'}} will be flattened to {'a_b': c}
Args:
nested: a dictionary to be flattened
Returns:
Dict. flattened version of the original dictionary
"""
a... |
class Solution:
def dfs(self, s):
if(s == len(self.graph) - 1):
self.path.append(len(self.graph)-1)
self.res.append(self.path[::])
self.path.pop()
return;
self.path.append(s)
for i in range(len(self.graph[s])):
sel... | class Solution:
def dfs(self, s):
if s == len(self.graph) - 1:
self.path.append(len(self.graph) - 1)
self.res.append(self.path[:])
self.path.pop()
return
self.path.append(s)
for i in range(len(self.graph[s])):
self.dfs(self.graph[s... |
"""
# REPEATED DNA SEQUENCES
All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more... | """
# REPEATED DNA SEQUENCES
All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.