content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
dictionary unpacking => It unpacks a dictionary as named arguments to a function.
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
@classmethod
def from_dict(cls, data):
return cls(data['username'], data['password'])
def __repr__(self)... | """
dictionary unpacking => It unpacks a dictionary as named arguments to a function.
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
@classmethod
def from_dict(cls, data):
return cls(data['username'], data['password'])
... |
# an ex. of how you might use a list in practice
colors = ["green", "red", "blue"]
guess = input("Please guess a color:")
if guess in colors:
print ("You guessed correctly!")
else:
print ("Negative! Try again please.")
| colors = ['green', 'red', 'blue']
guess = input('Please guess a color:')
if guess in colors:
print('You guessed correctly!')
else:
print('Negative! Try again please.') |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def backwardCpp():
http_archive(
name="backward_cpp" ,
build_file="//bazel/deps/backward_cpp:build.BUILD" ,
sha256... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def backward_cpp():
http_archive(name='backward_cpp', build_file='//bazel/deps/backward_cpp:build.BUILD', sha256='16ea32d5337735ed3e7eacd71d90596a89bc648c557bb6007c521a2cb6b073cc', strip_prefix='backward-cpp-aa3f253efc7281148e9159eda52b851339fe94... |
print('~'*30)
print('BANCOS AVORIK')
print('~'*30)
nt50 = nt20 = nt10 = nt1 = 0
saque = int(input('Quantos R$ deseja sacar?\n'))
resto = saque
while True:
if resto > 50:
nt50 = resto // 50
resto = resto % 50
print(f'{nt50} nota(s) de R$ 50.')
if resto > 20:
nt20 = resto // 20
... | print('~' * 30)
print('BANCOS AVORIK')
print('~' * 30)
nt50 = nt20 = nt10 = nt1 = 0
saque = int(input('Quantos R$ deseja sacar?\n'))
resto = saque
while True:
if resto > 50:
nt50 = resto // 50
resto = resto % 50
print(f'{nt50} nota(s) de R$ 50.')
if resto > 20:
nt20 = resto // 20... |
s = set(r"""~!@#$%^&*()_+|`-=\{}[]:";'<>?,./ """)
while True:
up = True
low = True
digit = True
special = True
a = input()
b = input()
t = len(a)
if a != b:
print('Password settings are not consistent.')
elif a == 'END':
break
else:
if not 8 <= t <= 12:
... | s = set('~!@#$%^&*()_+|`-=\\{}[]:";\'<>?,./ ')
while True:
up = True
low = True
digit = True
special = True
a = input()
b = input()
t = len(a)
if a != b:
print('Password settings are not consistent.')
elif a == 'END':
break
else:
if not 8 <= t <= 12:
... |
"""Modules for integration between Sans-I/O protocols and I/O drivers.
Modules:
_trio: integration between Sans-I/O protocols and trio I/O.
"""
| """Modules for integration between Sans-I/O protocols and I/O drivers.
Modules:
_trio: integration between Sans-I/O protocols and trio I/O.
""" |
ButtonA, ButtonB, ButtonSelect, ButtonStart, ButtonUp, ButtonDown, ButtonLeft, ButtonRight = range(8)
class Controller:
def __init__(self):
self.buttons = [False for _ in range(8)]
self.index = 0
self.strobe = 0
def set_buttons(self, buttons):
self.buttons = buttons
def... | (button_a, button_b, button_select, button_start, button_up, button_down, button_left, button_right) = range(8)
class Controller:
def __init__(self):
self.buttons = [False for _ in range(8)]
self.index = 0
self.strobe = 0
def set_buttons(self, buttons):
self.buttons = buttons
... |
# wordCalculator.py
# A program to calculate the number of words in a sentence
# by Tung Nguyen
def main():
# declare program function:
print("This program calculates the number of words in a sentence.")
print()
# prompt user to input the sentence:
sentence = input("Enter a phrase: ")
... | def main():
print('This program calculates the number of words in a sentence.')
print()
sentence = input('Enter a phrase: ')
list_word = sentence.split()
count_word = len(listWord)
print()
print('Number of words:', countWord)
main() |
"""Result - Data structure for a result."""
# Is prediction before game is played, then actual once game ahs been played
# Return the outcome Briers score, home/away goals scored, Predictions if available, and actual
# result if game has been played
class Result:
"""Result - Data structure for a result."""
d... | """Result - Data structure for a result."""
class Result:
"""Result - Data structure for a result."""
def __init__(self, status='SCHEDULED', home_team_goals_scored=0, away_team_goals_scored=0):
"""
Construct a Result object.
Parameters
----------
status : str, optional... |
"""
Author: Ao Wang
Date: 08/12/19
Description: Caesar cipher encryption and decryption, also a reverse encryption
"""
# The function reverses the string parameter
def reverse(plain_text):
cipher_text = ""
for letter in range(len(plain_text)):
# starts at the end of the string, -1 and moves its... | """
Author: Ao Wang
Date: 08/12/19
Description: Caesar cipher encryption and decryption, also a reverse encryption
"""
def reverse(plain_text):
cipher_text = ''
for letter in range(len(plain_text)):
cipher_text += plain_text[-1 - letter]
return cipher_text
def caesar_cipher(plain_text, key):
c... |
class LexHelper:
offset = 0
def get_max_linespan(self, p):
defSpan = [1e60, -1]
mSpan = [1e60, -1]
for sp in range(0, len(p)):
csp = p.linespan(sp)
if csp[0] == 0 and csp[1] == 0:
if hasattr(p[sp], "linespan"):
csp = p[sp].line... | class Lexhelper:
offset = 0
def get_max_linespan(self, p):
def_span = [1e+60, -1]
m_span = [1e+60, -1]
for sp in range(0, len(p)):
csp = p.linespan(sp)
if csp[0] == 0 and csp[1] == 0:
if hasattr(p[sp], 'linespan'):
csp = p[sp].... |
settings = {}
settings['version'] = "0.1"
settings['port'] = 36000
settings['product'] = "MOPIDY-PLEX"
settings['debug_registration'] = False
settings['debug_httpd'] = False
settings['host'] = ""
settings['token'] = None
| settings = {}
settings['version'] = '0.1'
settings['port'] = 36000
settings['product'] = 'MOPIDY-PLEX'
settings['debug_registration'] = False
settings['debug_httpd'] = False
settings['host'] = ''
settings['token'] = None |
def is_leap(year):
if year >= 1900 and year <= pow(10,5):
leap = False
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leap = True
else:
leap = False
else:
leap = True
return l... | def is_leap(year):
if year >= 1900 and year <= pow(10, 5):
leap = False
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap = True
else:
leap = False
else:
leap = True
r... |
# Copyright 2017 The Bazel 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 applicable la... | """Rule for bundling Docker images into a tarball."""
load(':label.bzl', _string_to_label='string_to_label')
load(':layers.bzl', _assemble_image='assemble', _get_layers='get_from_target', _incr_load='incremental_load', _layer_tools='tools')
load(':list.bzl', 'reverse')
def _docker_bundle_impl(ctx):
"""Implementati... |
def test_load_case(case_obj, adapter):
## GIVEN a database with no cases
assert adapter.case_collection.find_one() is None
## WHEN loading a case
adapter._add_case(case_obj)
## THEN assert that the case have been loaded with correct info
assert adapter.case_collection.find_one()
def test_lo... | def test_load_case(case_obj, adapter):
assert adapter.case_collection.find_one() is None
adapter._add_case(case_obj)
assert adapter.case_collection.find_one()
def test_load_case_rank_model_version(case_obj, adapter):
assert adapter.case_collection.find_one() is None
adapter._add_case(case_obj)
... |
def threshold_distance_mask(r, h):
return r < h
| def threshold_distance_mask(r, h):
return r < h |
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
_default_server_urls = ["https://repo.maven.apache.org/maven2/",
"https://mvnrepository.com/artifact",
"https://maven-central.storage.googleapis.com",
"http://gitblit... | load('@bazel_tools//tools/build_defs/repo:jvm.bzl', 'jvm_maven_import_external')
_default_server_urls = ['https://repo.maven.apache.org/maven2/', 'https://mvnrepository.com/artifact', 'https://maven-central.storage.googleapis.com', 'http://gitblit.github.io/gitblit-maven', 'https://repository.mulesoft.org/nexus/content... |
#!/usr/bin/env python
"""
Definitions of classes to work with molecular data.
The mol_info_table class is used to store and manipulated
information about a molecule.
The mol_xyz_table class is used to store and manipulated
the xyz coodinate of a molecule.
The functions defined here are basically wrappers to
MySQL e... | """
Definitions of classes to work with molecular data.
The mol_info_table class is used to store and manipulated
information about a molecule.
The mol_xyz_table class is used to store and manipulated
the xyz coodinate of a molecule.
The functions defined here are basically wrappers to
MySQL execution lines.
Each f... |
class OptionsStub(object):
def __init__(self):
self.debug = True
self.guess_summary = False
self.guess_description = False
self.tracking = None
self.username = None
self.password = None
self.repository_url = None
self.disable_proxy = False
self... | class Optionsstub(object):
def __init__(self):
self.debug = True
self.guess_summary = False
self.guess_description = False
self.tracking = None
self.username = None
self.password = None
self.repository_url = None
self.disable_proxy = False
sel... |
# Copyright 2019 AUI, Inc. Washington DC, USA
#
# 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 ... | def ddijoin(xds1, xds2):
"""
.. todo::
This function is not yet implemented
Concatenate together two Visibility Datasets of compatible shape
Parameters
----------
xds1 : xarray.core.dataset.Dataset
first Visibility Dataset to join
xds2 : xarray.core.dataset.Dataset
... |
"""__init__.py - A command-line utility that checks for best practices in Jinja2.
"""
NAME = 'j2lint'
VERSION = '0.1'
DESCRIPTION = __doc__
__author__ = "Arista Networks"
__license__ = "MIT"
__version__ = VERSION
| """__init__.py - A command-line utility that checks for best practices in Jinja2.
"""
name = 'j2lint'
version = '0.1'
description = __doc__
__author__ = 'Arista Networks'
__license__ = 'MIT'
__version__ = VERSION |
def binary_search(S, left, right, key):
# Find smallest element that's >= key
while left <= right:
# find midpoint
mid = left + (right - left) // 2
# if element found move lower.
if S[mid] >= key:
right = mid - 1
else:
left = mid + 1
# smallest... | def binary_search(S, left, right, key):
while left <= right:
mid = left + (right - left) // 2
if S[mid] >= key:
right = mid - 1
else:
left = mid + 1
return left
def len_of_lis(A):
"""
Computing the Longest Increasing Subsequence
O(nlogn) Time
O(n... |
service_dict = {
'NetworkService':{
'getTargetsWithRelationshipTypeForResourceById':{},
'getTargetsByRelationshipForSourceId':{},
'getSourcesWithThisTargetByRelationshipCount':{},
'deleteResource':{},
'getSourceURIWithThisTargetByRelatiobnshipForResourceId':{},
'getAl... | service_dict = {'NetworkService': {'getTargetsWithRelationshipTypeForResourceById': {}, 'getTargetsByRelationshipForSourceId': {}, 'getSourcesWithThisTargetByRelationshipCount': {}, 'deleteResource': {}, 'getSourceURIWithThisTargetByRelatiobnshipForResourceId': {}, 'getAllAttachmentOnlyResourceIDs': {}, 'getNamesAndAli... |
def test_a_cohama_adb(style_checker):
"""Style check test against a-cohama.adb."""
style_checker.set_year(2006)
p = style_checker.run_style_checker('trunk/gnat', 'a-cohama.adb')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_a_cohamb_adb(style_checke... | def test_a_cohama_adb(style_checker):
"""Style check test against a-cohama.adb."""
style_checker.set_year(2006)
p = style_checker.run_style_checker('trunk/gnat', 'a-cohama.adb')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_a_cohamb_adb(style_checker... |
### Stupid, but extensible spam detector
STOP_SPAM_WORDS = ["Loan", "Lender", ".trade", ".bid", ".men", ".win"]
def is_spam(request):
if 'email' in request.form:
if any(
[ word.upper() in request.form['email'].upper()
for word in STOP_SPAM_WORDS]):
return True
if 'username' in request.f... | stop_spam_words = ['Loan', 'Lender', '.trade', '.bid', '.men', '.win']
def is_spam(request):
if 'email' in request.form:
if any([word.upper() in request.form['email'].upper() for word in STOP_SPAM_WORDS]):
return True
if 'username' in request.form:
if any([word.upper() in request.fo... |
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'findadoctor2@gmail.com'
EMAIL_HOST_PASSWORD = 'Qwerty1@'
EMAIL_USE_TLS = True | email_host = 'smtp.gmail.com'
email_port = 587
email_host_user = 'findadoctor2@gmail.com'
email_host_password = 'Qwerty1@'
email_use_tls = True |
#! /usr/bin/env Python3
list_of_tuples = []
list_of_tuples_comprehension = ([(i, j, i * j) for i in range(1, 11) for j in range(1, 11)])
for i in range(1, 11):
for j in range(1, 11):
list_of_tuples.append((i, j, i * j))
print(list_of_tuples)
print('************')
print(list_of_tuples_comprehension)
| list_of_tuples = []
list_of_tuples_comprehension = [(i, j, i * j) for i in range(1, 11) for j in range(1, 11)]
for i in range(1, 11):
for j in range(1, 11):
list_of_tuples.append((i, j, i * j))
print(list_of_tuples)
print('************')
print(list_of_tuples_comprehension) |
TARGET_BAG = 'shiny gold'
def get_data(filepath):
return [line.strip() for line in open(filepath).readlines()]
def parse_rule(rule):
rule = rule.split(' ')
adj, color = rule[0], rule[1]
container_bag = '%s %s' % (adj, color)
bags_contained = {}
if rule[4:] == ['no', 'other', 'bags.']:
... | target_bag = 'shiny gold'
def get_data(filepath):
return [line.strip() for line in open(filepath).readlines()]
def parse_rule(rule):
rule = rule.split(' ')
(adj, color) = (rule[0], rule[1])
container_bag = '%s %s' % (adj, color)
bags_contained = {}
if rule[4:] == ['no', 'other', 'bags.']:
... |
class Instance:
def __init__ (self, alloyfp):
self.bitwidth = '4'
self.maxseq = '4'
self.mintrace = '-1'
self.maxtrace = '-1'
self.filename = alloyfp
self.tracel = '1'
self.backl = '0'
self.sigs = []
self.fields = []
def add_sig(self, sig... | class Instance:
def __init__(self, alloyfp):
self.bitwidth = '4'
self.maxseq = '4'
self.mintrace = '-1'
self.maxtrace = '-1'
self.filename = alloyfp
self.tracel = '1'
self.backl = '0'
self.sigs = []
self.fields = []
def add_sig(self, sig)... |
# Find square root using newton raphson
num = 987
eps = 1e-6
iteration = 0
sroot = num/2
while abs(sroot**2-num)>eps:
iteration+=1
if sroot**2==num:
print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}')
break
sroot = sroot - (sroot**2-num)/(2*sroot)
print(f'... | num = 987
eps = 1e-06
iteration = 0
sroot = num / 2
while abs(sroot ** 2 - num) > eps:
iteration += 1
if sroot ** 2 == num:
print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}')
break
sroot = sroot - (sroot ** 2 - num) / (2 * sroot)
print(f'At Iteration {iter... |
"""
https://www.practicepython.org
Exercise 14: List Remove Duplicates
2 chilis
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
- Write two different functions to do this - one using a loop and constructing
a li... | """
https://www.practicepython.org
Exercise 14: List Remove Duplicates
2 chilis
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
- Write two different functions to do this - one using a loop and constructing
a li... |
HEADLINE = "time_elapsed\tsystem_time\tyear\tmonth\tday\tseasonal_factor\ttreatment_coverage_0_1\ttreatment_coverage_0_10\tpopulation\tsep\teir\tsep\tbsp_2_10\tbsp_0_5\tblood_slide_prevalence\tsep\tmonthly_new_infection\tsep\tmonthly_new_treatment\tsep\tmonthly_clinical_episode\tsep\tmonthly_ntf_raw\tsep\tKNY--C1x\tKNY... | headline = 'time_elapsed\tsystem_time\tyear\tmonth\tday\tseasonal_factor\ttreatment_coverage_0_1\ttreatment_coverage_0_10\tpopulation\tsep\teir\tsep\tbsp_2_10\tbsp_0_5\tblood_slide_prevalence\tsep\tmonthly_new_infection\tsep\tmonthly_new_treatment\tsep\tmonthly_clinical_episode\tsep\tmonthly_ntf_raw\tsep\tKNY--C1x\tKNY... |
# -*- coding: utf-8 -*-
"""
mongoop.default_settings
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Lujeni.
:license: BSD, see LICENSE for more details.
"""
mongodb_host = 'localhost'
mongodb_port = 27017
mongodb_credentials = None
mongodb_options = None
frequency = 10
threshold_timeout = 60
o... | """
mongoop.default_settings
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Lujeni.
:license: BSD, see LICENSE for more details.
"""
mongodb_host = 'localhost'
mongodb_port = 27017
mongodb_credentials = None
mongodb_options = None
frequency = 10
threshold_timeout = 60
op_triggers = None
balancer_trig... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
a, b = headA, headB
while a != b:
a = a.next if a else headB
b =... | class Solution(object):
def get_intersection_node(self, headA, headB):
(a, b) = (headA, headB)
while a != b:
a = a.next if a else headB
b = b.next if b else headA
return a |
class DriverMeta(type):
def __instancecheck__(cls, __instance) -> bool:
return cls.__subclasscheck__(type(__instance))
def __subclasscheck__(cls, __subclass: type) -> bool:
return (
hasattr(__subclass, 'create') and callable(__subclass.create)
) and (
... | class Drivermeta(type):
def __instancecheck__(cls, __instance) -> bool:
return cls.__subclasscheck__(type(__instance))
def __subclasscheck__(cls, __subclass: type) -> bool:
return (hasattr(__subclass, 'create') and callable(__subclass.create)) and (hasattr(__subclass, 'logs') and callable(__su... |
# Simple example using ifs
cars = ['volks', 'ford', 'audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Comparing Values
#
# requested_toppings = 'mushrooms'
# if requested_toppings != 'anchovies':
# print('Hold the Anchovies')
#
#
# ... | cars = ['volks', 'ford', 'audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
age = 18
if age >= 18:
print('OK to vote') |
class Squad():
def __init__(self, handler, role, hold_point):
self.handler = handler
if len(handler.squads[role]) > 0:
self.id = handler.squads[role][-1].id + 1
else:
self.id = 1
self.units = {
handler.unit.MARINE: [],
handler... | class Squad:
def __init__(self, handler, role, hold_point):
self.handler = handler
if len(handler.squads[role]) > 0:
self.id = handler.squads[role][-1].id + 1
else:
self.id = 1
self.units = {handler.unit.MARINE: [], handler.unit.SIEGETANK: []}
self.ro... |
# https://leetcode.com/problems/unique-binary-search-trees-ii/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generate_trees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
return self.... |
infile=open('pairin.txt','r')
n=int(infile.readline().strip())
dic={}
for i in range(2*n):
sn=int(infile.readline().strip())
if sn not in dic:
dic[sn]=i
else:
dic[sn]-=i
maxkey=min(dic,key=dic.get)
outfile=open('pairout.txt','w')
outfile.write(str(abs(dic[maxkey])))
outfile.close... | infile = open('pairin.txt', 'r')
n = int(infile.readline().strip())
dic = {}
for i in range(2 * n):
sn = int(infile.readline().strip())
if sn not in dic:
dic[sn] = i
else:
dic[sn] -= i
maxkey = min(dic, key=dic.get)
outfile = open('pairout.txt', 'w')
outfile.write(str(abs(dic[maxkey])))
outf... |
"""
Queue via Stacks
Implement a MyQueue class which implements a queue using two stacks.
Questions and Assumptions:
Model 1: Back to Back ArrayStacks
MyQ
stack1 stack2
t2 t1
[ ][ x1 x2 x3 x4]
f ? b
1. Interface:
... | """
Queue via Stacks
Implement a MyQueue class which implements a queue using two stacks.
Questions and Assumptions:
Model 1: Back to Back ArrayStacks
MyQ
stack1 stack2
t2 t1
[ ][ x1 x2 x3 x4]
f ? b
1. Interface:
... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
workingset = set()
for n in nums:
if n not in workingset:
workingset.add(n)
else:
workingset.remove(n)
... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
workingset = set()
for n in nums:
if n not in workingset:
workingset.add(n)
else:
workingset.remove(n)
... |
'''
Created on Dec 4, 2017
@author: atip
'''
def getAdjSquareSum():
global posX, posY, valMatrix
adjSquareSum = 0
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY]
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY + 1]
adjSquareSum += valMatrix[maxRange + posX][maxRange ... | """
Created on Dec 4, 2017
@author: atip
"""
def get_adj_square_sum():
global posX, posY, valMatrix
adj_square_sum = 0
adj_square_sum += valMatrix[maxRange + posX + 1][maxRange + posY]
adj_square_sum += valMatrix[maxRange + posX + 1][maxRange + posY + 1]
adj_square_sum += valMatrix[maxRange + posX... |
#
# @lc app=leetcode id=77 lang=python3
#
# [77] Combinations
#
# @lc code=start
class Solution:
def combine(self, n, k):
self.ans = []
nums = [num for num in range(1, n + 1)]
if n == k:
self.ans.append(nums)
return self.ans
else:
ls = []
... | class Solution:
def combine(self, n, k):
self.ans = []
nums = [num for num in range(1, n + 1)]
if n == k:
self.ans.append(nums)
return self.ans
else:
ls = []
self.helper(nums, k, ls)
return self.ans
def helper(self, ar... |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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 restriction, including
# without limitation the rights to use, copy,... | def get(prop, choices=None):
prompt = prop.verbose_name
if not prompt:
prompt = prop.name
if choices:
if callable(choices):
choices = choices()
else:
choices = prop.get_choices()
valid = False
while not valid:
if choices:
min = 1
... |
"""
Linear search is used on a collections of items. It relies on the technique of traversing a list from
start to end by exploring properties of all the elements that are found on the way.
The time complexity of the linear search is O(N) because each element in an array is compared only once.
"""
def linear_search(... | """
Linear search is used on a collections of items. It relies on the technique of traversing a list from
start to end by exploring properties of all the elements that are found on the way.
The time complexity of the linear search is O(N) because each element in an array is compared only once.
"""
def linear_search(a... |
METR_LA_DATASET_NAME = 'metr_la'
PEMS_BAY_DATASET_NAME = 'pems_bay'
IN_MEMORY = 'mem'
ON_DISK = 'disk'
| metr_la_dataset_name = 'metr_la'
pems_bay_dataset_name = 'pems_bay'
in_memory = 'mem'
on_disk = 'disk' |
class Token(object):
def __init__(self, access_token, refresh_token, lifetime):
self.access_token = access_token # Access token value
self.refresh_token = refresh_token # Token needed for refreshing access token
self.lifetime = lifetime # Access token lifetime
| class Token(object):
def __init__(self, access_token, refresh_token, lifetime):
self.access_token = access_token
self.refresh_token = refresh_token
self.lifetime = lifetime |
def main():
print(hi)
if __name__ == '__main__': main()
| def main():
print(hi)
if __name__ == '__main__':
main() |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self):
self.front = None
self.rear = None
def __repr__(self):
current = self.front
nodes = []
wh... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class Linkedlist:
def __init__(self):
self.front = None
self.rear = None
def __repr__(self):
current = self.front
nodes = []
w... |
def f():
a = 10
result = 0
result = sum_squares(a, result)
print("Sum of squares: " + result)
def sum_squares(a_new, result_new):
while a_new < 10:
result_new += a_new * a_new
a_new += 1
return result_new
| def f():
a = 10
result = 0
result = sum_squares(a, result)
print('Sum of squares: ' + result)
def sum_squares(a_new, result_new):
while a_new < 10:
result_new += a_new * a_new
a_new += 1
return result_new |
m = float(input('Digite um tamanho (em metros): '))
dm = m * 10
cm = m * 100
mm = m * 1000
dam = m / 10
hm = m / 100
km = m / 1000
print('convertendo...')
print('[dm] =', dm)
print('[cm] =', cm)
print('[mm] =', mm)
print('[dam] =', dam)
print('[hm] =', hm)
print('[km] =', km)
| m = float(input('Digite um tamanho (em metros): '))
dm = m * 10
cm = m * 100
mm = m * 1000
dam = m / 10
hm = m / 100
km = m / 1000
print('convertendo...')
print('[dm] =', dm)
print('[cm] =', cm)
print('[mm] =', mm)
print('[dam] =', dam)
print('[hm] =', hm)
print('[km] =', km) |
#Input, arguments
def add(x,y):
z = x + y
b = 'I am here'
a = 'hello'
return z,b,a
x = 20
y = 5
# Calling function
print(add(x,y))
z = add(x,y) #same thing
print(z)
print(add(10,5)) #same thing | def add(x, y):
z = x + y
b = 'I am here'
a = 'hello'
return (z, b, a)
x = 20
y = 5
print(add(x, y))
z = add(x, y)
print(z)
print(add(10, 5)) |
def main(request, response):
referrer = request.headers.get("referer", "")
response_headers = [("Content-Type", "text/javascript")];
return (200, response_headers, "window.referrer = '" + referrer + "'")
| def main(request, response):
referrer = request.headers.get('referer', '')
response_headers = [('Content-Type', 'text/javascript')]
return (200, response_headers, "window.referrer = '" + referrer + "'") |
#
# PySNMP MIB module IANA-ADDRESS-FAMILY-NUMBERS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-ADDRESS-FAMILY-NUMBERS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:50:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ... |
# regular assignment
foo = 7
print(foo)
# annotated assignmnet
bar: number = 9
print(bar)
| foo = 7
print(foo)
bar: number = 9
print(bar) |
VERSION = "0.7.0"
LICENSE = "MIT - Copyright (c) 2021 Alex Vellone"
MOTORS_CHECK_PER_SECOND = 20
MOTORS_POINT_TO_POINT_CHECK_PER_SECOND = 10
WEB_SOCKET_SEND_PER_SECOND = 10
SOCKET_SEND_PER_SECOND = 20
SOCKET_INCOMING_LIMIT = 5
SLEEP_AVOID_CPU_WASTE = 0.80
| version = '0.7.0'
license = 'MIT - Copyright (c) 2021 Alex Vellone'
motors_check_per_second = 20
motors_point_to_point_check_per_second = 10
web_socket_send_per_second = 10
socket_send_per_second = 20
socket_incoming_limit = 5
sleep_avoid_cpu_waste = 0.8 |
def sumoftwo(a, b):
"""
This is an sumoftwo function to add two number
:param int a: first number to add
:param int b: first number to add
:return: return addition of the integer
:rtype: int
:example:
>>> r = sumoftwo(2, 3)
>>> r
5
"""
return a + b
| def sumoftwo(a, b):
"""
This is an sumoftwo function to add two number
:param int a: first number to add
:param int b: first number to add
:return: return addition of the integer
:rtype: int
:example:
>>> r = sumoftwo(2, 3)
>>> r
5
"""
return a + b |
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=init_checkpoint,
layer_indexes=layer_indexes,
use_tpu=False,
use_one_hot_embeddings=False)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEsti... | model_fn = model_fn_builder(bert_config=bert_config, init_checkpoint=init_checkpoint, layer_indexes=layer_indexes, use_tpu=False, use_one_hot_embeddings=False)
estimator = tf.contrib.tpu.TPUEstimator(use_tpu=False, model_fn=model_fn, config=run_config, predict_batch_size=batch_size)
input_fn = input_fn_builder(features... |
# Exercico 1 - listas
# Escreva program que leia a nome de 10 alunos
# Armezene os nomes em uma lista
# Imprema a lista
nomes =[]
for i in range(1,11):
nome = [input(f'Informe o {i} Nome')]
nomes.append(nome)
for d in nomes:
print(f' Nomes informados {d}') | nomes = []
for i in range(1, 11):
nome = [input(f'Informe o {i} Nome')]
nomes.append(nome)
for d in nomes:
print(f' Nomes informados {d}') |
"""
We consider a string programmer string if some subset of its letters can be rearranged to form the word programmer.
They are anagrams.
Given a long string determine the number of indices within the string that are in between two programmer strings.
The character 'x' inside an anagram are considered redundant and no... | """
We consider a string programmer string if some subset of its letters can be rearranged to form the word programmer.
They are anagrams.
Given a long string determine the number of indices within the string that are in between two programmer strings.
The character 'x' inside an anagram are considered redundant and no... |
class Solution:
def XXX(self, x: int) -> int:
if x == 0:
return 0
res = str(x)
sign = 1
if res[0] == '-':
res = res[1:]
sign = -1
res = res[::-1]
if res[0] == '0':
res = res[1:]
resint = int(res)*sign
... | class Solution:
def xxx(self, x: int) -> int:
if x == 0:
return 0
res = str(x)
sign = 1
if res[0] == '-':
res = res[1:]
sign = -1
res = res[::-1]
if res[0] == '0':
res = res[1:]
resint = int(res) * sign
... |
#Making a nice litte x o o o x o o o x tic tac toe board
def printer(board):
for i in range(3):
for j in range (3):
print(board[i][j], end="")
if j<2:
print(" | ", end="")
print()
if i<2:
print("--+----+--")
def main():
tictactoe=[[... | def printer(board):
for i in range(3):
for j in range(3):
print(board[i][j], end='')
if j < 2:
print(' | ', end='')
print()
if i < 2:
print('--+----+--')
def main():
tictactoe = [[' ' for i in range(3)] for j in range(3)]
for i in ... |
#!/usr/bin/python
# create_dict.py
weekend = { "Sun": "Sunday", "Mon": "Monday" }
vals = dict(one=1, two=2)
capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
d = { i: object() for i in range(4) }
print (weekend)
print (vals)
print (capitals)
print (d)
| weekend = {'Sun': 'Sunday', 'Mon': 'Monday'}
vals = dict(one=1, two=2)
capitals = {}
capitals['svk'] = 'Bratislava'
capitals['deu'] = 'Berlin'
capitals['dnk'] = 'Copenhagen'
d = {i: object() for i in range(4)}
print(weekend)
print(vals)
print(capitals)
print(d) |
# to jest komentarz
WIDTH = 550
HEIGHT = 550
| width = 550
height = 550 |
#
# @lc app=leetcode.cn id=617 lang=python3
#
# [617] merge-two-binary-trees
#
None
# @lc code=end | None |
class Solution:
def generatePossibleNextMoves(self, s: str) -> List[str]:
results = []
for i in range(len(s) - 1):
if s[i: i + 2] == "++":
results.append(s[:i] + "--" + s[i + 2:])
return results | class Solution:
def generate_possible_next_moves(self, s: str) -> List[str]:
results = []
for i in range(len(s) - 1):
if s[i:i + 2] == '++':
results.append(s[:i] + '--' + s[i + 2:])
return results |
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
q = [x]
while self.data:
q.... | class Mystack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
q = [x]
while self.data:
q.... |
heatmap_1_r = imresize(heatmap_1, (50,80)).astype("float32")
heatmap_2_r = imresize(heatmap_2, (50,80)).astype("float32")
heatmap_3_r = imresize(heatmap_3, (50,80)).astype("float32")
heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333)
display_img_and_heatmap("dog.jpg", heatmap_geom_avg)
| heatmap_1_r = imresize(heatmap_1, (50, 80)).astype('float32')
heatmap_2_r = imresize(heatmap_2, (50, 80)).astype('float32')
heatmap_3_r = imresize(heatmap_3, (50, 80)).astype('float32')
heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333)
display_img_and_heatmap('dog.jpg', heatmap_geom_avg) |
quantidade, menor, maior, soma = 0,0,0,0
quantidade = int(input())
while(quantidade>0):
menor, maior, soma, final= 10,0,0,0
nome = input()
dificuldade = float(input())
notas = input().split()
notas = list(notas)
for i in range(len(notas)):
notas[i] = float(notas[i])
notas.sort()
cont = 0
for i in range(len(n... | (quantidade, menor, maior, soma) = (0, 0, 0, 0)
quantidade = int(input())
while quantidade > 0:
(menor, maior, soma, final) = (10, 0, 0, 0)
nome = input()
dificuldade = float(input())
notas = input().split()
notas = list(notas)
for i in range(len(notas)):
notas[i] = float(notas[i])
n... |
ALLERGIES_SCORE = ['eggs', 'peanuts', 'shellfish', 'strawberries',
'tomatoes', 'chocolate', 'pollen', 'cats']
class Allergies:
def __init__(self, score: int):
self.score = score
self.lst = self.list_of_allergies()
def allergic_to(self, item: str) -> bool:
retur... | allergies_score = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats']
class Allergies:
def __init__(self, score: int):
self.score = score
self.lst = self.list_of_allergies()
def allergic_to(self, item: str) -> bool:
return item in self.lst
... |
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return Number(self.data - other)
class Indexer:
data = [5, 6, 7, 8, 9]
def __getitem__(self, item):
print('getitem:', item)
return self.data[item]
def __setitem__(self, index, va... | class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return number(self.data - other)
class Indexer:
data = [5, 6, 7, 8, 9]
def __getitem__(self, item):
print('getitem:', item)
return self.data[item]
def __setitem__(self, index, va... |
# This helper file, setups the rules and rewards for the mouse grid system
# State = 1, start point
# Action - 1: Top, 2:Left, 3:Right, 4:Down
def transition_rules(state, action):
# For state 1
if state == 1 and (action == 3 or action == 4):
state = 1
elif state == 1 and action == 1:
state... | def transition_rules(state, action):
if state == 1 and (action == 3 or action == 4):
state = 1
elif state == 1 and action == 1:
state = 5
elif state == 1 and action == 2:
state = 2
elif state == 2 and action == 4:
state = 2
elif state == 2 and action == 1:
sta... |
#
# PySNMP MIB module HUAWEI-BRAS-SBC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-BRAS-SBC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:31:26 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_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
description = 'Aircontrol PLC devices'
group = 'optional'
tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_'
devices = dict(
spare_motor_x2 = device('nicos.devices.entangle.Motor',
description = 'spare motor',
tangodevice = tango_base + 'spare_mot_x2',
fmtstr = '%... | description = 'Aircontrol PLC devices'
group = 'optional'
tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_'
devices = dict(spare_motor_x2=device('nicos.devices.entangle.Motor', description='spare motor', tangodevice=tango_base + 'spare_mot_x2', fmtstr='%.4f', visibility=()), shutter=device('ni... |
def make_prime_table(n):
sieve = list(range(n + 1))
sieve[0] = -1
sieve[1] = -1
for i in range(4, n + 1, 2):
sieve[i] = 2
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i] != i:
continue
for j in range(i * i, n + 1, i * 2):
if sieve[j] == j:
... | def make_prime_table(n):
sieve = list(range(n + 1))
sieve[0] = -1
sieve[1] = -1
for i in range(4, n + 1, 2):
sieve[i] = 2
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i] != i:
continue
for j in range(i * i, n + 1, i * 2):
if sieve[j] == j:
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'publics',
'USER': 'publics_read_only',
'PASSWORD': r'read-only',
'HOST': '5.153.9.51',
'PORT': '5432',
}
}
INSTALLED_APPS = (
'contracts',
'law',
'deputies'
)
# ... | databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'publics', 'USER': 'publics_read_only', 'PASSWORD': 'read-only', 'HOST': '5.153.9.51', 'PORT': '5432'}}
installed_apps = ('contracts', 'law', 'deputies')
secret_key = 'not-secret' |
body_max_width = 15
body_max_height = 15
def validate_body_str_profile(body: str):
body_lines = body.splitlines()
width = len(body_lines[0])
height = len(body_lines)
if width > body_max_width or height > body_max_height:
raise ValueError("Body string is too big")
| body_max_width = 15
body_max_height = 15
def validate_body_str_profile(body: str):
body_lines = body.splitlines()
width = len(body_lines[0])
height = len(body_lines)
if width > body_max_width or height > body_max_height:
raise value_error('Body string is too big') |
# -*- coding: utf-8 -*-
def userinfo( authority, otherwise='' ):
"""Extracts the user info (user:pass)."""
end = authority.find('@')
if -1 == end:
return otherwise
return authority[0:end]
def location( authority ):
"""Extracts the location (host:port)."""
end = authority.find('@')
... | def userinfo(authority, otherwise=''):
"""Extracts the user info (user:pass)."""
end = authority.find('@')
if -1 == end:
return otherwise
return authority[0:end]
def location(authority):
"""Extracts the location (host:port)."""
end = authority.find('@')
if -1 == end:
return ... |
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a... | class Trienode:
def __init__(self):
self.children = {}
self.isEnd = False
class Worddictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = trie_node()
def add_word(self, word: str) -> None:
"""
Adds a word ... |
n, x = map(int, input().split())
if (x > n // 2 and n % 2 == 0) or (x > (n + 1) // 2 and n % 2 == 1):
x = n - x
A = n - x
B = x
k = 0
m = -1
ans = n
while m != 0:
k = A // B
m = A % B
ans += B * k * 2
if m == 0:
ans -= B
A = B
B = m
print(ans) | (n, x) = map(int, input().split())
if x > n // 2 and n % 2 == 0 or (x > (n + 1) // 2 and n % 2 == 1):
x = n - x
a = n - x
b = x
k = 0
m = -1
ans = n
while m != 0:
k = A // B
m = A % B
ans += B * k * 2
if m == 0:
ans -= B
a = B
b = m
print(ans) |
string_1 = input("String 1? ")
string_2 = input("String 2? ")
string_3 = input("String 3? ")
print(string_1 + string_2 + string_3)
| string_1 = input('String 1? ')
string_2 = input('String 2? ')
string_3 = input('String 3? ')
print(string_1 + string_2 + string_3) |
'''
URL: https://leetcode.com/problems/slowest-key/
Difficulty: Easy
Description: Slowest Key
A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a so... | """
URL: https://leetcode.com/problems/slowest-key/
Difficulty: Easy
Description: Slowest Key
A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a so... |
# Copyright 2015 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.
class Shell(object):
"""Represents an abstract Mojo shell."""
def serve_local_directories(self, mappings, port, reuse_servers=False):
"""Serves the... | class Shell(object):
"""Represents an abstract Mojo shell."""
def serve_local_directories(self, mappings, port, reuse_servers=False):
"""Serves the content of the local (host) directories, making it available
to the shell under the url returned by the function.
The server will run on a separat... |
# LeetCode #437 - Path Sum III
# https://leetcode.com/problems/path-sum-iii/
# Prefix-sum hashing solution. Runs in linear time.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = righ... | class Solution:
@staticmethod
def path_sum(root: TreeNode, targetSum: int) -> int:
history = collections.Counter((0,))
def dfs(node, acc):
if not node:
return 0
acc += node.val
count = history[acc - targetSum]
history[acc] += 1
... |
class SearchToursData:
def __init__(self, destination, tour_type, start_year, start_month, start_day, adults_num):
self.destination = destination
self.tour_type = tour_type
self.start_year = start_year
self.start_month = start_month
self.start_day = start_day
self.ad... | class Searchtoursdata:
def __init__(self, destination, tour_type, start_year, start_month, start_day, adults_num):
self.destination = destination
self.tour_type = tour_type
self.start_year = start_year
self.start_month = start_month
self.start_day = start_day
self.ad... |
def first_non_repeating_letter(string):
lowercase_string = string.lower()
result = []
for i in lowercase_string:
if (lowercase_string.count(i) == 1):
result.append(i)
if (len(result) == 0):
return ""
else:
if (string.find(result[0]) == -1 ):
return re... | def first_non_repeating_letter(string):
lowercase_string = string.lower()
result = []
for i in lowercase_string:
if lowercase_string.count(i) == 1:
result.append(i)
if len(result) == 0:
return ''
elif string.find(result[0]) == -1:
return result[0].upper()
else... |
datasets = ('source',)
def synthesis(job):
d = {}
agg = 0
for dt, x in datasets.source.iterate('roundrobin', ('DATE_OF_INTEREST', 'CASE_COUNT')):
agg += x
d[dt] = agg
return d
| datasets = ('source',)
def synthesis(job):
d = {}
agg = 0
for (dt, x) in datasets.source.iterate('roundrobin', ('DATE_OF_INTEREST', 'CASE_COUNT')):
agg += x
d[dt] = agg
return d |
'''
Created on 16 ago 2017
@author: Hamza
'''
class MyClass(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
| """
Created on 16 ago 2017
@author: Hamza
"""
class Myclass(object):
"""
classdocs
"""
def __init__(self, params):
"""
Constructor
""" |
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
working = 0
for i, stu in enumerate(startTime):
if stu <= queryTime and endTime[i] >= queryTime:
working += 1
return working | class Solution:
def busy_student(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
working = 0
for (i, stu) in enumerate(startTime):
if stu <= queryTime and endTime[i] >= queryTime:
working += 1
return working |
#!/usr/bin/python
# -*-coding:utf-8-*-
"""
@author: smartgang
@contact: zhangxingang92@qq.com
@file: data_analyse_nba.py
@time: 2017/12/5 11:02
""" | """
@author: smartgang
@contact: zhangxingang92@qq.com
@file: data_analyse_nba.py
@time: 2017/12/5 11:02
""" |
class Solution:
def makeEqual(self, words: List[str]) -> bool:
n = len(words)
words = ''.join(words)
letterCounter = Counter(words)
print(letterCounter )
for letter in letterCounter:
if letterCounter[letter] % n !=0:
return False
... | class Solution:
def make_equal(self, words: List[str]) -> bool:
n = len(words)
words = ''.join(words)
letter_counter = counter(words)
print(letterCounter)
for letter in letterCounter:
if letterCounter[letter] % n != 0:
return False
return ... |
EARTH = 6371000
MOON = 1737100
MARS = 3389500
JUPITER = 69911000
| earth = 6371000
moon = 1737100
mars = 3389500
jupiter = 69911000 |
#===============================================================================
# Created: 22 May 2019
# @author: AP (adapated from Jesse Wilson)
# Description: Class to contain Anaplan connection details required for all API calls
# Input: Authorization header string, workspace ID string, an... | class Anaplanconnection(object):
"""
classdocs
"""
def __init__(self, authorization, workspaceGuid, modelGuid):
"""
:param authorization: Authorization header string
:param workspaceGuid: ID of the Anaplan workspace
:param modelGuid: ID of the Anaplan model
"... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
if root is None:
return 0
sum = 0
def plusAllLeaves(... | class Solution:
def sum_root_to_leaf(self, root: TreeNode) -> int:
if root is None:
return 0
sum = 0
def plus_all_leaves(node, parentPath):
nonlocal sum
curr_path = parentPath + str(node.val)
if node.left is None and node.right is None:
... |
"""Utility module that defines the :class:`Singleton` class."""
class Singleton:
"""
Singleton class.
The :class:`Singleton` class is used to force a unique instantiation.
"""
_instance = None
def __new__(cls, *args) -> "Singleton":
"""Control single instance creation."""
if... | """Utility module that defines the :class:`Singleton` class."""
class Singleton:
"""
Singleton class.
The :class:`Singleton` class is used to force a unique instantiation.
"""
_instance = None
def __new__(cls, *args) -> 'Singleton':
"""Control single instance creation."""
if c... |
DEFAULT_POSTGREST_CLIENT_HEADERS = {
"Accept": "application/json",
"Content-Type": "application/json",
}
DEFAULT_POSTGREST_CLIENT_TIMEOUT = 5
| default_postgrest_client_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
default_postgrest_client_timeout = 5 |
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'Tr... | class Treenode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
res = None
def find_lca(node):
if... |
# buildifier: disable=module-docstring
def _provider_text(symbols):
return """
WRAPPER = provider(
doc = "Wrapper to hold imported methods",
fields = [{}]
)
""".format(", ".join(["\"%s\"" % symbol_ for symbol_ in symbols]))
def _getter_text():
return """
def id_from_file(file_name):
(before, middle, af... | def _provider_text(symbols):
return '\nWRAPPER = provider(\n doc = "Wrapper to hold imported methods",\n fields = [{}]\n)\n'.format(', '.join(['"%s"' % symbol_ for symbol_ in symbols]))
def _getter_text():
return '\ndef id_from_file(file_name):\n (before, middle, after) = file_name.partition(".")\n ret... |
class Solution(object):
def searchMatrix(self, matrix, target):
if not matrix or target is None:
return False
rows, cols = len(matrix), len(matrix[0])
low, high = 0, rows* cols - 1
while low <= high:
mid = (low + high) / 2
num = matrix[mid / cols... | class Solution(object):
def search_matrix(self, matrix, target):
if not matrix or target is None:
return False
(rows, cols) = (len(matrix), len(matrix[0]))
(low, high) = (0, rows * cols - 1)
while low <= high:
mid = (low + high) / 2
num = matrix[m... |
class SWTestCase:
def __init__(self):
pass
@classmethod
def configure(cls):
pass
def setUp(self):
pass
def tearDown(self):
pass
def run_all_test_case(self):
for test in self.test_to_run:
self.setUp()
test()
self.te... | class Swtestcase:
def __init__(self):
pass
@classmethod
def configure(cls):
pass
def set_up(self):
pass
def tear_down(self):
pass
def run_all_test_case(self):
for test in self.test_to_run:
self.setUp()
test()
self.t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.