content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Problem0019 - Counting Sundays
#
# https: // github.com/agileshaw/Project-Euler
def totalDays(month, year):
month_list = [4, 6, 9, 11]
if month == 2:
if year % 400 == 0 or ((year % 4 == 0) and year % 100 != 0):
return 29
else:
return 28
elif month in month_list:
... | def total_days(month, year):
month_list = [4, 6, 9, 11]
if month == 2:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return 29
else:
return 28
elif month in month_list:
return 30
return 31
if __name__ == '__main__':
count = 0
weekday =... |
def get_integer_input(message):
"""
This function will display the message to the user
and request that they input an integer.
If the user enters something that is not a number
then the input will be rejected
and an error message will be displayed.
The user will then be asked to try again.... | def get_integer_input(message):
"""
This function will display the message to the user
and request that they input an integer.
If the user enters something that is not a number
then the input will be rejected
and an error message will be displayed.
The user will then be asked to try again.... |
def lower_bound(arr, value, first, last):
"""Find the lower bound of the value in the array
lower bound: the first element in arr that is larger than or equal
to value
Args:
arr : input array
value : target value
first : starting point of the search, inclusi... | def lower_bound(arr, value, first, last):
"""Find the lower bound of the value in the array
lower bound: the first element in arr that is larger than or equal
to value
Args:
arr : input array
value : target value
first : starting point of the search, inclusi... |
class CraftParser:
@staticmethod
def calculate_mass(craft_filepath: str, masses: dict) -> int:
parts = []
craft_lines = []
with open(craft_filepath) as craft:
craft_lines = [line.strip() for line in craft.readlines()]
for index, line in enumerate(craft_lines):
if "part = " in line:
... | class Craftparser:
@staticmethod
def calculate_mass(craft_filepath: str, masses: dict) -> int:
parts = []
craft_lines = []
with open(craft_filepath) as craft:
craft_lines = [line.strip() for line in craft.readlines()]
for (index, line) in enumerate(craft_lines):
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 23:24:41 2019
@author: rocco
"""
#function to convert datetime to seconds
def datetime2seconds(date_time):
return time.mktime(date_time.timetuple())
#function to convert datetime to seconds
def dateinterv2date(interval):
return interval.left.to_pyd... | """
Created on Mon Feb 4 23:24:41 2019
@author: rocco
"""
def datetime2seconds(date_time):
return time.mktime(date_time.timetuple())
def dateinterv2date(interval):
return interval.left.to_pydatetime().date()
list1 = list(map(datetime2seconds, idx))
list3 = list(map(dateinterv2date, ser))
lat_min = [-90.0, -... |
"""
Author: Shengjia Yan
Date: 2018-05-11 Friday
Email: i@yanshengjia.com
Time Complexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split(' ')
res = []
for word in words:
... | """
Author: Shengjia Yan
Date: 2018-05-11 Friday
Email: i@yanshengjia.com
Time Complexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split(' ')
res = []
for word in words:
... |
"""You are given an integer n, the number of teams in a tournament that has strange rules:
If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
If the current number of teams is odd, one team randomly advances i... | """You are given an integer n, the number of teams in a tournament that has strange rules:
If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
If the current number of teams is odd, one team randomly advances i... |
# flake8: noqa
responses = {
"success": {
"status_code": 200,
"content": {
"resourceType":"Bundle",
"id":"389a548b-9c85-4491-9795-9306a957030b",
"meta":{
"lastUpdated":"2019-12-18T13:40:02.792-05:00"
},
"type":"searchset",
... | responses = {'success': {'status_code': 200, 'content': {'resourceType': 'Bundle', 'id': '389a548b-9c85-4491-9795-9306a957030b', 'meta': {'lastUpdated': '2019-12-18T13:40:02.792-05:00'}, 'type': 'searchset', 'total': 1, 'link': [{'relation': 'first', 'url': 'https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&... |
# Problem: https://leetcode.com/problems/range-sum-query-2d-immutable/submissions/
#["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
null_matrix= [[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]]
row1 = 1
col1 = 2
row2 = ... | null_matrix = [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]
row1 = 1
col1 = 2
row2 = 2
col2 = 4
prefix = null_matrix[:]
row = len(prefix)
col = len(prefix[0])
for i in range(row):
for j in range(1, col):
prefix[i][j] += prefix[i][j - 1]
for i in range(1, row):
for... |
__version__ = "3.0.0-beta"
VERSION = __version__
DOMAIN = "krisinfo"
BASE_URL = "https://api.krisinformation.se/v3/"
NEWS_PARAMETER = "news?format=json"
VMAS_PARAMETER = "vmas?format=json"
LANGUAGE_PARAMETER = "&language="
USER_AGENT = "homeassistant_krisinfo/" + VERSION
| __version__ = '3.0.0-beta'
version = __version__
domain = 'krisinfo'
base_url = 'https://api.krisinformation.se/v3/'
news_parameter = 'news?format=json'
vmas_parameter = 'vmas?format=json'
language_parameter = '&language='
user_agent = 'homeassistant_krisinfo/' + VERSION |
# Road of Regrets 2 (270020200) => Resting Spot of Regret
# The One Who Walks Down the Road of Regrets2
if sm.hasQuestCompleted(3509):
sm.warp(270020210, 3)
else:
sm.chat("Those who do not have the Goddess' permission may not move against the flow of time, and will be sent back to their previous location.")
... | if sm.hasQuestCompleted(3509):
sm.warp(270020210, 3)
else:
sm.chat("Those who do not have the Goddess' permission may not move against the flow of time, and will be sent back to their previous location.")
sm.warp(270020100) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created by tianhao.wang at 9/6/18
""" | """
Created by tianhao.wang at 9/6/18
""" |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return n
pre1 = 2
pre2 = 1
cur = 0
while(n>2):
cur = pre1 + pre2
pre2 = pre1
pre1 = cur
n ... | class Solution(object):
def climb_stairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return n
pre1 = 2
pre2 = 1
cur = 0
while n > 2:
cur = pre1 + pre2
pre2 = pre1
pre1 = cur
... |
"""Constants for the AlarmDecoder component."""
CONF_ALT_NIGHT_MODE = "alt_night_mode"
CONF_AUTO_BYPASS = "auto_bypass"
CONF_CODE_ARM_REQUIRED = "code_arm_required"
CONF_DEVICE_BAUD = "device_baudrate"
CONF_DEVICE_PATH = "device_path"
CONF_RELAY_ADDR = "zone_relayaddr"
CONF_RELAY_CHAN = "zone_relaychan"
CONF_ZONE_LOOP... | """Constants for the AlarmDecoder component."""
conf_alt_night_mode = 'alt_night_mode'
conf_auto_bypass = 'auto_bypass'
conf_code_arm_required = 'code_arm_required'
conf_device_baud = 'device_baudrate'
conf_device_path = 'device_path'
conf_relay_addr = 'zone_relayaddr'
conf_relay_chan = 'zone_relaychan'
conf_zone_loop ... |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
#
# Write a program that asks for the user's name and another piece of information.Then prints a response using both of the inputs.
x = input("What is your name?")
y = input("How old are you?")
print("Hello " + x + ", you ... | x = input('What is your name?')
y = input('How old are you?')
print('Hello ' + x + ', you are ' + y + ' years old.') |
_base_ = './upernet_vit-b16_mln_512x512_160k_ade20k.py'
model = dict(
pretrained='pretrain/deit_base_patch16_224-b5f2ef4d.pth',
backbone=dict(drop_path_rate=0.1),
)
| _base_ = './upernet_vit-b16_mln_512x512_160k_ade20k.py'
model = dict(pretrained='pretrain/deit_base_patch16_224-b5f2ef4d.pth', backbone=dict(drop_path_rate=0.1)) |
#!/usr/bin/env python3
"""Error exceptions."""
class InputError(Exception):
"""Raised on invalid user input."""
| """Error exceptions."""
class Inputerror(Exception):
"""Raised on invalid user input.""" |
#coding=utf-8
'''
Created on 2015-10-10
@author: Devuser
'''
class Tag(object):
def __init__(self,tagid,name,color):
self.tagid=tagid
self.tagname=name
self.tagcolor=color
| """
Created on 2015-10-10
@author: Devuser
"""
class Tag(object):
def __init__(self, tagid, name, color):
self.tagid = tagid
self.tagname = name
self.tagcolor = color |
def log(str):
ENABLED = False # Set False to disable loggin
if ENABLED:
print(str) | def log(str):
enabled = False
if ENABLED:
print(str) |
# add 6 _
name = 'Mark'
align_right = f'{name:_>10}'
print(align_right)
# '______Mark' | name = 'Mark'
align_right = f'{name:_>10}'
print(align_right) |
def main(n):
ret = 1
while 1:
if n == 1:
break
n = (n // 2, 3 * n + 1)[n & 1]
ret += 1
return ret
if __name__ == '__main__':
print(main(int(input())))
| def main(n):
ret = 1
while 1:
if n == 1:
break
n = (n // 2, 3 * n + 1)[n & 1]
ret += 1
return ret
if __name__ == '__main__':
print(main(int(input()))) |
t = '########### ###########\n########## ##########\n######### #########\n######## ########\n####### #######\n###### ######\n##### #####\n#### ####\n### ###\n## ##\n# #\n \n'
d... | t = '########### ###########\n########## ##########\n######### #########\n######## ########\n####### #######\n###### ######\n##### #####\n#### ####\n### ###\n## ##\n# #\n \n'
... |
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
""" | """
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
""" |
#
# PySNMP MIB module CISCO-EPM-NOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EPM-NOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:40:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | """Represent the interface for Query. This is important because our access
control logic needs a unified way to specify conditions for both BigQuery
query and Datastore query.
This must be compatible with libs.filters and libs.crash_access."""
class Query(object):
"""Represent the interface for Query."""
... |
# Project Euler - Problem 9
# Aidan O'Connor_G00364756_01/03/2018
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
d... | def ptriplet(number):
"""Returns the Pythagorean triplet for which a + b + c = 1000"""
m = 3
limit = 1000
for a in range(m, 500, 1):
for b in range(a, 500, 1):
for c in range(b, 500, 1):
ram = a + b + c
zig = a ** 2
zag = b ** 2
... |
#
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | """
Exceptions/Errors used in databricks-koalas.
"""
class Sparkpandasindexingerror(Exception):
pass
def code_change_hint(pandas_function, spark_target_function):
if pandas_function is not None and spark_target_function is not None:
return 'You are trying to use pandas function {}, use spark function ... |
'''https: // practice.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1
Permutations of a given string
Basic Accuracy: 49.85 % Submissions: 31222 Points: 1
Given a string S. The task is to print all permutations of a given string.
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given... | """https: // practice.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1
Permutations of a given string
Basic Accuracy: 49.85 % Submissions: 31222 Points: 1
Given a string S. The task is to print all permutations of a given string.
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given... |
class TreeNode:
"""Definition for a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.depth(root) != -1
def depth(self, node: TreeNode) -> int:
... | class Treenode:
"""Definition for a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.depth(root) != -1
def depth(self, node: TreeNode) -> int:
... |
s = input()
y = s[0]
w = s[2]
if int(y) > int(w):
p = 7 - int(y)
else:
p = 7 - int(w)
if p == 1:
print('1/6')
if p == 2:
print('1/3')
if p == 3:
print('1/2')
if p == 4:
print('2/3')
if p == 5:
print('5/6')
if p == 6:
print('1/1')
| s = input()
y = s[0]
w = s[2]
if int(y) > int(w):
p = 7 - int(y)
else:
p = 7 - int(w)
if p == 1:
print('1/6')
if p == 2:
print('1/3')
if p == 3:
print('1/2')
if p == 4:
print('2/3')
if p == 5:
print('5/6')
if p == 6:
print('1/1') |
# -*- coding: utf-8 -*-
"""
Jokes from stackoverflow - provided under CC BY-SA 3.0
http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke?page=4&tab=votes#tab-top
"""
neutral = [
"Trionfalmente, Beth ha rimosso Python 2.7 dal server nel 2020.'Finalmente!' ha detto con gioia, solo per vedere l... | """
Jokes from stackoverflow - provided under CC BY-SA 3.0
http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke?page=4&tab=votes#tab-top
"""
neutral = ["Trionfalmente, Beth ha rimosso Python 2.7 dal server nel 2020.'Finalmente!' ha detto con gioia, solo per vedere l'annuncio di Python 4.4.", "Una... |
'''Question 1: Given a two integer numbers return their product
and if the product is greater than 1000, then return their sum'''
num1=int(input("Enter the first no:"))
num2=int(input("Enter the second no:"))
product=num1*num2
if(product>1000):
print("sum is:",num1+num2)
else:
print("Invalid n... | """Question 1: Given a two integer numbers return their product
and if the product is greater than 1000, then return their sum"""
num1 = int(input('Enter the first no:'))
num2 = int(input('Enter the second no:'))
product = num1 * num2
if product > 1000:
print('sum is:', num1 + num2)
else:
print('Invalid numbe... |
def collection_json():
"""Returns JSON skeleton for Postman schema."""
collection_json = {
"info": {
"name": "Test_collection",
"description": "Generic text used for documentation.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
... | def collection_json():
"""Returns JSON skeleton for Postman schema."""
collection_json = {'info': {'name': 'Test_collection', 'description': 'Generic text used for documentation.', 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'}, 'item': []}
return collection_json
def atom... |
"""Constants for the Alexa integration."""
DOMAIN = 'alexa'
# Flash briefing constants
CONF_UID = 'uid'
CONF_TITLE = 'title'
CONF_AUDIO = 'audio'
CONF_TEXT = 'text'
CONF_DISPLAY_URL = 'display_url'
CONF_FILTER = 'filter'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_ENDPOINT = 'endpoint'
CONF_CLIENT_ID = 'client_id'
CONF... | """Constants for the Alexa integration."""
domain = 'alexa'
conf_uid = 'uid'
conf_title = 'title'
conf_audio = 'audio'
conf_text = 'text'
conf_display_url = 'display_url'
conf_filter = 'filter'
conf_entity_config = 'entity_config'
conf_endpoint = 'endpoint'
conf_client_id = 'client_id'
conf_client_secret = 'client_secr... |
'''
Author: Aditya Mangal
Date: 20 september,2020
Purpose: python practise problem
'''
def input_matrixes(m, n):
output = []
for i in range(m):
row = []
for j in range(n):
user_matrixes = int(input(f'Enter number on [{i}][{j}]\n'))
row.append(user_matrixes)
... | """
Author: Aditya Mangal
Date: 20 september,2020
Purpose: python practise problem
"""
def input_matrixes(m, n):
output = []
for i in range(m):
row = []
for j in range(n):
user_matrixes = int(input(f'Enter number on [{i}][{j}]\n'))
row.append(user_matrixes)
ou... |
d=int(input())
m=int(input())
n=int(input())
x=[int(z) for z in input().split(" ")]
dist_travelled=0
i=0
refuel=0
while(dist_travelled<d and i<n-1):
if(dist_travelled+m>=d):
break
if(dist_travelled+m>=x[i] and dist_travelled+m<x[i+1]):
dist_travelled=x[i]
refuel+=1
elif(dist_travelle... | d = int(input())
m = int(input())
n = int(input())
x = [int(z) for z in input().split(' ')]
dist_travelled = 0
i = 0
refuel = 0
while dist_travelled < d and i < n - 1:
if dist_travelled + m >= d:
break
if dist_travelled + m >= x[i] and dist_travelled + m < x[i + 1]:
dist_travelled = x[i]
... |
# Copyright (c) 2018 PaddlePaddle 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 app... | class Agentbase(object):
"""`AgentBase` is the base class of the `parl.Agent` in different frameworks.
`parl.Agent` is responsible for the general data flow outside the algorithm.
"""
def __init__(self, algorithm):
"""
Args:
algorithm (`AlgorithmBase`): an instance of `Alg... |
def main(j, args, params, tags, tasklet):
page = args.page
action = args.requestContext.params.get('action', 'install')
aysid = args.requestContext.params.get('aysid')
instance = args.requestContext.params.get('instance', 'main')
parent = args.requestContext.params.get('parent', '')
installedag... | def main(j, args, params, tags, tasklet):
page = args.page
action = args.requestContext.params.get('action', 'install')
aysid = args.requestContext.params.get('aysid')
instance = args.requestContext.params.get('instance', 'main')
parent = args.requestContext.params.get('parent', '')
installedage... |
class SpaceAge(object):
earth_year = 31557600
corr = {
'earth': 1,
'mercury': 0.2408467,
'venus': 0.61519726,
'mars': 1.8808158,
'jupiter': 11.862615,
'saturn': 29.447498,
'uranus': 84.016846,
'neptune': 164.79132
}
def __init__(self, seco... | class Spaceage(object):
earth_year = 31557600
corr = {'earth': 1, 'mercury': 0.2408467, 'venus': 0.61519726, 'mars': 1.8808158, 'jupiter': 11.862615, 'saturn': 29.447498, 'uranus': 84.016846, 'neptune': 164.79132}
def __init__(self, seconds):
self.seconds = seconds
def repr(self, planet=None):... |
ACME_DEPLOYMENT = """
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: %(deployment_name)s
labels:
app: openshift-acme
spec:
progressDeadlineSeconds: 600
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
app: openshift-acme
strategy:
type: Recreate
template:
... | acme_deployment = "\napiVersion: extensions/v1beta1\nkind: Deployment\nmetadata:\n name: %(deployment_name)s\n labels:\n app: openshift-acme\nspec:\n progressDeadlineSeconds: 600\n replicas: 1\n revisionHistoryLimit: 10\n selector:\n matchLabels:\n app: openshift-acme\n strategy:\n type: Recreate\n... |
#!/usr/bin/env python
NAME = 'Cisco ACE XML Gateway'
def is_waf(self):
if self.matchheader(('server', 'ACE XML Gateway')):
return True
return False
| name = 'Cisco ACE XML Gateway'
def is_waf(self):
if self.matchheader(('server', 'ACE XML Gateway')):
return True
return False |
# WARNING!!!
# DO NOT MODIFY THIS FILE DIRECTLY.
# TO GENERATE THIS RUN: ./updateWorkspaceSnapshots.sh
BASE_ARCHITECTURES = ["amd64"]
# Exceptions:
# - s390x doesn't have libunwind8.
# https://github.com/GoogleContainerTools/distroless/pull/612#issue-500157699
# - ppc64le doesn't have stretch security-channel.
# ... | base_architectures = ['amd64']
architectures = BASE_ARCHITECTURES
versions = [('debian11', 'bullseye')]
debian_snapshot = '20210729T144530Z'
debian_security_snapshot = '20210729T023407Z'
sha256s = {'amd64': {'debian11': {'main': 'c17bf41d0f915c55a2cc048ed6a4b87e206e4d72e310f43a41f52d83689bc31d', 'updates': 'e70a10d6f43... |
"""Top-level package for `functions` project."""
__package_name__ = "functions-cli"
__version__ = "0.1.0"
| """Top-level package for `functions` project."""
__package_name__ = 'functions-cli'
__version__ = '0.1.0' |
if __name__ == '__main__':
n = int(input())
if((n%2!=0)or((n>=6)and(n<=20))):
print("Weird")
else:
print("Not Weird")
| if __name__ == '__main__':
n = int(input())
if n % 2 != 0 or (n >= 6 and n <= 20):
print('Weird')
else:
print('Not Weird') |
'''
Created on Apr 4, 2021
@author: x2012x
'''
class ConductorException(Exception):
pass
class UnsupportedAction(ConductorException):
pass
class UnsupportedIntent(ConductorException):
pass
class RegistrationExists(ConductorException):
pass
class SpeakableException(ConductorException):
def __ini... | """
Created on Apr 4, 2021
@author: x2012x
"""
class Conductorexception(Exception):
pass
class Unsupportedaction(ConductorException):
pass
class Unsupportedintent(ConductorException):
pass
class Registrationexists(ConductorException):
pass
class Speakableexception(ConductorException):
def __i... |
#!/usr/bin/env python3
##################################################################################
# #
# Program purpose: Finds a replace the string "Python" with "Java" and the #
# string "Java" with "P... | def read_string(mess: str):
valid = False
user_str = ''
while not valid:
try:
user_str = input(mess).strip()
valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_str
def swap_substr(main_str: str, sub_a: str, sub_b: str):
if m... |
class ObjectMaterialSource(Enum,IComparable,IFormattable,IConvertible):
"""
Defines enumerated values for the source of material of single objects.
enum ObjectMaterialSource,values: MaterialFromLayer (0),MaterialFromObject (1),MaterialFromParent (3)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x... | class Objectmaterialsource(Enum, IComparable, IFormattable, IConvertible):
"""
Defines enumerated values for the source of material of single objects.
enum ObjectMaterialSource,values: MaterialFromLayer (0),MaterialFromObject (1),MaterialFromParent (3)
"""
def __eq__(self, *args):
""" x.__eq__(y... |
# question : https://quera.ir/problemset/university/296/
n = int(input())
for i in range(1, n + 1):
line = ''
for j in range(1, n + 1):
if i in [1, n]:
line += '#'
elif j in [1, n]:
line += '#'
elif i == j:
line += '#'
elif j == n - i + 1:
... | n = int(input())
for i in range(1, n + 1):
line = ''
for j in range(1, n + 1):
if i in [1, n]:
line += '#'
elif j in [1, n]:
line += '#'
elif i == j:
line += '#'
elif j == n - i + 1:
line += '#'
elif j > n - i:
i... |
categories = {
'coco': [
{"color": [220, 20, 60], "isthing": 1, "id": 1, "name": "person"},
{"color": [119, 11, 32], "isthing": 1, "id": 2, "name": "bicycle"},
{"color": [0, 0, 142], "isthing": 1, "id": 3, "name": "car"},
{"color": [0, 0, 230], "isthing": 1, "id": 4, "name": "mo... | categories = {'coco': [{'color': [220, 20, 60], 'isthing': 1, 'id': 1, 'name': 'person'}, {'color': [119, 11, 32], 'isthing': 1, 'id': 2, 'name': 'bicycle'}, {'color': [0, 0, 142], 'isthing': 1, 'id': 3, 'name': 'car'}, {'color': [0, 0, 230], 'isthing': 1, 'id': 4, 'name': 'motorcycle'}, {'color': [106, 0, 228], 'isthi... |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "net_gac4", "nuget_package")
def packages():
nuget_package(
name = "npgsql",
package = "npgsql",
version = "4.0.3",
# sha256 = "4e1f91eb9f0c3dfb8e029edbc325175cd202455df3641bc16155ef422b6bfd6f",
core_lib = {
"netsta... | load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'net_gac4', 'nuget_package')
def packages():
nuget_package(name='npgsql', package='npgsql', version='4.0.3', core_lib={'netstandard2.0': 'lib/netstandard2.0/Npgsql.dll'}, net_lib={'net451': 'lib/net451/Npgsql.dll'}, mono_lib='lib/net45/Npgsql.dll', core_deps={}, net_... |
aihub_dialog_datasets = {
"train": {
"clean": ["data/Training"]
}
}
librispeech_datasets = {
"train": {
"clean": ["LibriSpeech/train-clean-100", "LibriSpeech/train-clean-360"],
"other": ["LibriSpeech/train-other-500"]
},
"test": {
"clean": ["LibriSpeech/test-clean"],... | aihub_dialog_datasets = {'train': {'clean': ['data/Training']}}
librispeech_datasets = {'train': {'clean': ['LibriSpeech/train-clean-100', 'LibriSpeech/train-clean-360'], 'other': ['LibriSpeech/train-other-500']}, 'test': {'clean': ['LibriSpeech/test-clean'], 'other': ['LibriSpeech/test-other']}, 'dev': {'clean': ['Lib... |
def matrix_script():
first_multiple_input = input().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
matrix = []
for _ in range(n):
matrix_item = input()
matrix.append(matrix_item)
ref = []
for i in range(m):
for ... | def matrix_script():
first_multiple_input = input().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
matrix = []
for _ in range(n):
matrix_item = input()
matrix.append(matrix_item)
ref = []
for i in range(m):
for j in range(n):
ref... |
'''
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import logging
def calculate_wcss(data):
wcss = []
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
for n in range(2, 21):
kmeans = ... | """
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import logging
def calculate_wcss(data):
wcss = []
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
for n in range(2, 21):
kmeans = ... |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
row = len(matrix)
col = len(matrix[0])
res = 0
dp = [[0 for i in range(col+1)] for j in range(row+1)]
for i in range(1,row+1):
for j in range(1,col+1):
if matrix[i-1]... | class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
row = len(matrix)
col = len(matrix[0])
res = 0
dp = [[0 for i in range(col + 1)] for j in range(row + 1)]
for i in range(1, row + 1):
for j in range(1, col + 1):
if matrix[i... |
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
return reduce(lambda x, y: x ^ y, A)
| class Solution:
def single_number(self, A):
return reduce(lambda x, y: x ^ y, A) |
"""Implements the modified UTF-7 specification used for encoding and decoding
mailbox names in IMAP.
See Also:
`RFC 3501 5.1.3 <https://tools.ietf.org/html/rfc3501#section-5.1.3>`_
"""
__all__ = ['modutf7_encode', 'modutf7_decode']
def _modified_b64encode(src: str) -> bytes:
# Inspired by Twisted Python's ... | """Implements the modified UTF-7 specification used for encoding and decoding
mailbox names in IMAP.
See Also:
`RFC 3501 5.1.3 <https://tools.ietf.org/html/rfc3501#section-5.1.3>`_
"""
__all__ = ['modutf7_encode', 'modutf7_decode']
def _modified_b64encode(src: str) -> bytes:
src_utf7 = src.encode('utf-7')
... |
#!/usr/bin/env python
def read_input(filename):
with open(filename) as fd:
return [line.strip() for line in fd.readlines()]
def reduce_chunks(line):
"""Meh
>>> lines = read_input('example')
>>> reduce_chunks(lines[2])
'{([(<[}>{{[('
"""
while True:
prev = line
for... | def read_input(filename):
with open(filename) as fd:
return [line.strip() for line in fd.readlines()]
def reduce_chunks(line):
"""Meh
>>> lines = read_input('example')
>>> reduce_chunks(lines[2])
'{([(<[}>{{[('
"""
while True:
prev = line
for crs in ('()', '[]', '{}'... |
# KeyPairs.py
# Pairs key name to corresponding numerical identifier
keyPairs = [("C",1),("Db/C#",2),("D",3),("Eb/D#",4),("E",5),("F",6),
("Gb/F#",7),("G",8),("Ab/G#",9),("A",10),("Bb/A#",11),("B",12)]
| key_pairs = [('C', 1), ('Db/C#', 2), ('D', 3), ('Eb/D#', 4), ('E', 5), ('F', 6), ('Gb/F#', 7), ('G', 8), ('Ab/G#', 9), ('A', 10), ('Bb/A#', 11), ('B', 12)] |
file = open('/Users/hansr/Desktop/Homo_sapiens.GRCh37.75.gtf', 'rU')
hgncfile = open('/Users/hansr/Desktop/hgnc_complete_set.txt', 'rU')
outfile = open('/Users/hansr/Desktop/EnsembleId2GeneName.csv', 'w')
id2symbol = {}
id2name = {}
for line in hgncfile:
if line.startswith('hgnc_id'):
continue
splits... | file = open('/Users/hansr/Desktop/Homo_sapiens.GRCh37.75.gtf', 'rU')
hgncfile = open('/Users/hansr/Desktop/hgnc_complete_set.txt', 'rU')
outfile = open('/Users/hansr/Desktop/EnsembleId2GeneName.csv', 'w')
id2symbol = {}
id2name = {}
for line in hgncfile:
if line.startswith('hgnc_id'):
continue
splits = ... |
{
"targets": [
{
"target_name": "action_before_build",
"type": "none",
"hard_dependency": 1,
"actions": [
{
"action_name": "build rust-native-storage library",
"inputs": [ "scripts/build_storage_lib.sh" ],
"outputs": [ "" ],
"action": ["scrip... | {'targets': [{'target_name': 'action_before_build', 'type': 'none', 'hard_dependency': 1, 'actions': [{'action_name': 'build rust-native-storage library', 'inputs': ['scripts/build_storage_lib.sh'], 'outputs': [''], 'action': ['scripts/build_storage_lib.sh']}]}, {'target_name': '<(module_name)', 'dependencies': ['actio... |
def fib(n):
a,b = 1,2
for _ in range(n-1):
a,b = b, a + b
return a
def count_basic(n):
return fib(n)
def count_multi(n,ways):
if n < 0:
return 0
elif n == 0:
return 1
elif n in ways:
return 1 + sum([count_multi(n - x, ways) for x in ways if x < n])
else:
... | def fib(n):
(a, b) = (1, 2)
for _ in range(n - 1):
(a, b) = (b, a + b)
return a
def count_basic(n):
return fib(n)
def count_multi(n, ways):
if n < 0:
return 0
elif n == 0:
return 1
elif n in ways:
return 1 + sum([count_multi(n - x, ways) for x in ways if x <... |
VAR = 42
def func():
global VAR
VAR += 1 | var = 42
def func():
global VAR
var += 1 |
class BackendBaseException(Exception):
"""
Base exception for all custom exceptions of this service.
"""
def __init__(self, message: str) -> None:
self.message = message
class AuthenticationException(BackendBaseException):
pass
class ViewException(BackendBaseException):
def __init__... | class Backendbaseexception(Exception):
"""
Base exception for all custom exceptions of this service.
"""
def __init__(self, message: str) -> None:
self.message = message
class Authenticationexception(BackendBaseException):
pass
class Viewexception(BackendBaseException):
def __init__(... |
''' Pseudocode
1. Start
2. Take dividend from the user
3. Take divisor from user
4. Calculate the quotient
5. Calculate the remainder
6. Disdlays quotient and remainder
7. End
'''
# Take the value of dividend
dividend = int(input('Enter the value of dividend: '))
# Take the value of the divisor
divisor = int(inp... | """ Pseudocode
1. Start
2. Take dividend from the user
3. Take divisor from user
4. Calculate the quotient
5. Calculate the remainder
6. Disdlays quotient and remainder
7. End
"""
dividend = int(input('Enter the value of dividend: '))
divisor = int(input('Enter the value of divisor: '))
q = dividend // divisor
r = ... |
def any(x) -> bool:
pass
def all(x) -> bool:
pass
def bool(x) -> bool:
pass
def bytes(x) -> Bytes:
pass
def dict() -> Dict:
pass
def dir(x) -> List[String]:
pass
def enumerate(x) -> List[Tuple[int, any]]:
pass
def float(x) -> float:
pass
def hasattr(x, name) -> bool:
pass
def hash(x) -> int:
... | def any(x) -> bool:
pass
def all(x) -> bool:
pass
def bool(x) -> bool:
pass
def bytes(x) -> Bytes:
pass
def dict() -> Dict:
pass
def dir(x) -> List[String]:
pass
def enumerate(x) -> List[Tuple[int, any]]:
pass
def float(x) -> float:
pass
def hasattr(x, name) -> bool:
pass
de... |
"""
All the functions to manipulate the resource fields, state changes, etc.
Grouped by the type of the fields and the purpose of the manipulation.
Used in the handling routines to check if there were significant changes at all
(i.e. not our own internal and system changes, like the uids, links, etc),
and to get the ... | """
All the functions to manipulate the resource fields, state changes, etc.
Grouped by the type of the fields and the purpose of the manipulation.
Used in the handling routines to check if there were significant changes at all
(i.e. not our own internal and system changes, like the uids, links, etc),
and to get the ... |
def parse_policy(policy):
a, b, c = policy.split()
lo, hi = a.split("-")
return (int(lo), int(hi), b[:-1], c)
def part1(pws):
return sum(1 for lo, hi, c, pw in pws if lo <= pw.count(c) <= hi)
def part2(pws):
return sum(1 for lo, hi, c, pw in pws if (pw[lo - 1] == c) != (pw[hi - 1] == c))
if __... | def parse_policy(policy):
(a, b, c) = policy.split()
(lo, hi) = a.split('-')
return (int(lo), int(hi), b[:-1], c)
def part1(pws):
return sum((1 for (lo, hi, c, pw) in pws if lo <= pw.count(c) <= hi))
def part2(pws):
return sum((1 for (lo, hi, c, pw) in pws if (pw[lo - 1] == c) != (pw[hi - 1] == c)... |
# Copyright (C) 2018 The Dagger Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | """Macro for creating a jar from a set of flat files"""
def simple_jar(name, srcs):
"""Creates a jar out of a set of flat files"""
native.genrule(name=name, srcs=srcs, outs=['%s.jar' % name], cmd='\n OUT="$$(pwd)/$@"\n cd {package_name}\n zip "$$OUT" -r * &> /dev/null\n '.format(pac... |
__author__ = "Liyuan Liu and Frank Xu"
__credits__ = ["Liyuan Liu", "Frank Xu", "Jingbo Shang"]
__license__ = "Apache License 2.0"
__maintainer__ = "Liyuan Liu"
__email__ = "llychinalz@gmail.com" | __author__ = 'Liyuan Liu and Frank Xu'
__credits__ = ['Liyuan Liu', 'Frank Xu', 'Jingbo Shang']
__license__ = 'Apache License 2.0'
__maintainer__ = 'Liyuan Liu'
__email__ = 'llychinalz@gmail.com' |
def convert_month_to_days(number_of_months: int) -> int:
return number_of_months * 30
def convert_week_to_days(number_of_weeks: int) -> int:
return number_of_weeks * 7
class CovidEstimator:
def __init__(self, **kwargs):
self.currently_infected: int = 0
self.currently_infected_worst_cas... | def convert_month_to_days(number_of_months: int) -> int:
return number_of_months * 30
def convert_week_to_days(number_of_weeks: int) -> int:
return number_of_weeks * 7
class Covidestimator:
def __init__(self, **kwargs):
self.currently_infected: int = 0
self.currently_infected_worst_case: ... |
class _BaseOptimizer:
def __init__(self, model, learning_rate=1e-4, reg=1e-3):
self.learning_rate = learning_rate
self.reg = reg
self.grad_tracker = {}
for idx, m in enumerate(model.modules):
self.grad_tracker[idx] = dict(dw=0, db=0)
def update(self, model):
... | class _Baseoptimizer:
def __init__(self, model, learning_rate=0.0001, reg=0.001):
self.learning_rate = learning_rate
self.reg = reg
self.grad_tracker = {}
for (idx, m) in enumerate(model.modules):
self.grad_tracker[idx] = dict(dw=0, db=0)
def update(self, model):
... |
def getOrderFromDict(d):
return RobinhoodOrder(d['symbol'],d['action'],d['shares'],d['price'],d['date'])
class RobinhoodOrder(object):
def __init__(self, symbol, action, shares, price, date):
self.symbol = symbol
self.action = action
self.shares = shares
self.price = price
... | def get_order_from_dict(d):
return robinhood_order(d['symbol'], d['action'], d['shares'], d['price'], d['date'])
class Robinhoodorder(object):
def __init__(self, symbol, action, shares, price, date):
self.symbol = symbol
self.action = action
self.shares = shares
self.price = pr... |
'''
In this little assignment you are given a string of space separated numbers,
and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
Notes:
All numbers are valid Int32, no need to va... | """
In this little assignment you are given a string of space separated numbers,
and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
Notes:
All numbers are valid Int32, no need to va... |
class TrustDomain(object):
"""
Represents the name of a SPIFFE trust domain (e.g. 'domain.test').
:param trust_domain: The name of the Trust Domain
"""
name: str
def __init__(self, trust_domain: str):
self.name = trust_domain
| class Trustdomain(object):
"""
Represents the name of a SPIFFE trust domain (e.g. 'domain.test').
:param trust_domain: The name of the Trust Domain
"""
name: str
def __init__(self, trust_domain: str):
self.name = trust_domain |
n1 = 10
n2 = 20
print(n1,n2)
n1 , n2 = n2 ,n1
print(n1,n2)
| n1 = 10
n2 = 20
print(n1, n2)
(n1, n2) = (n2, n1)
print(n1, n2) |
pizzas = ['Pizza_A', 'Pizza_B', 'Pizza_C']
for pizza in pizzas:
print(f'Gosto da {pizza}')
print('Eu realmente gosto de pizza.')
for i in range(1, 1):
print(i)
pizzas_amigos = pizzas[:]
pizzas.append('Pizza_D')
pizzas_amigos.append('Pizza_E')
for pizza in pizzas:
print(pizza)
print()
... | pizzas = ['Pizza_A', 'Pizza_B', 'Pizza_C']
for pizza in pizzas:
print(f'Gosto da {pizza}')
print('Eu realmente gosto de pizza.')
for i in range(1, 1):
print(i)
pizzas_amigos = pizzas[:]
pizzas.append('Pizza_D')
pizzas_amigos.append('Pizza_E')
for pizza in pizzas:
print(pizza)
print()
for pizza_amigo in pizz... |
liste = [1,6,9,4,5,7]
plusFort = 0
for nb in liste:
if nb>plusFort:
plusFort = nb
print("Le plus fort de la liste est {}".format(plusFort))
| liste = [1, 6, 9, 4, 5, 7]
plus_fort = 0
for nb in liste:
if nb > plusFort:
plus_fort = nb
print('Le plus fort de la liste est {}'.format(plusFort)) |
{
'targets': [{
'target_name': 'addon',
'include_dirs': [
"<!(node -e \"require('nan')\")",
'lib/kcp',
'src',
],
'sources': [
'lib/kcp/ikcp.c',
'src/utils.c',
'src/Loop.cc',
'src/SessUDP.cc',
'src/Cryptor.cc',
'src/KcpuvSess.cc',
'src/Mux.cc'... | {'targets': [{'target_name': 'addon', 'include_dirs': ['<!(node -e "require(\'nan\')")', 'lib/kcp', 'src'], 'sources': ['lib/kcp/ikcp.c', 'src/utils.c', 'src/Loop.cc', 'src/SessUDP.cc', 'src/Cryptor.cc', 'src/KcpuvSess.cc', 'src/Mux.cc', 'src/binding.cc'], 'conditions': [['OS=="win"', {'libraries': ['ws2_32.lib']}]]}]} |
# Given an integer array nums of unique elements, return all possible subsets
# (the power set).
# The solution set must not contain duplicate subsets.
# Return the solution in any order.
#
# Example 1:
# Input: nums = [1,2,3]
# Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
#
# Example 2:
# Input: nums = [0]
# Out... | class Solution_1:
def subsets(nums):
ans = [[]]
for num in nums:
ans += [x + [num] for x in ans]
return ans |
n = int(input())
a = list(map(int,input().split()))
dist = [-1] * n
dist[0] = 0
pos = [0]
for u in pos:
for v in [u - 1, u + 1, a[u] - 1]:
if v >= 0 and v < n and dist[v] == -1:
dist[v] = dist[u] + 1
pos.append(v)
print(*dist)
| n = int(input())
a = list(map(int, input().split()))
dist = [-1] * n
dist[0] = 0
pos = [0]
for u in pos:
for v in [u - 1, u + 1, a[u] - 1]:
if v >= 0 and v < n and (dist[v] == -1):
dist[v] = dist[u] + 1
pos.append(v)
print(*dist) |
def letter_count(word):
count = {}
for i in word:
count[i] = word.count(i)
return count
new = (letter_count("mehedi hasan shifat").items())
for i,j in new:
print("'{}' -> {} times".format(i,j))
print(len(new))
| def letter_count(word):
count = {}
for i in word:
count[i] = word.count(i)
return count
new = letter_count('mehedi hasan shifat').items()
for (i, j) in new:
print("'{}' -> {} times".format(i, j))
print(len(new)) |
class AbstractProducerAdapter:
def __init__(self, config: dict):
self.config = config
def get_current_energy_production(self) -> float:
""" Returns the current energy production """
pass
| class Abstractproduceradapter:
def __init__(self, config: dict):
self.config = config
def get_current_energy_production(self) -> float:
""" Returns the current energy production """
pass |
def random_choice():
return bool(GLOBAL_UNKOWN_VAR)
def is_safe(arg):
return UNKNOWN_FUNC(arg)
def true_func():
return True
def test_basic():
s = TAINTED_STRING
if is_safe(s):
ensure_not_tainted(s)
else:
ensure_tainted(s)
if not is_safe(s):
ensure_tainted(s)
... | def random_choice():
return bool(GLOBAL_UNKOWN_VAR)
def is_safe(arg):
return unknown_func(arg)
def true_func():
return True
def test_basic():
s = TAINTED_STRING
if is_safe(s):
ensure_not_tainted(s)
else:
ensure_tainted(s)
if not is_safe(s):
ensure_tainted(s)
el... |
m = 4
b = 5
c = 6
d = 7
n = 0
d = d*d
print(d)
c = d*2 - c*2
print(c)
p = b*d+m*c
print(p)
dn = c-d
print(dn)
cn = c-m
print(cn)
d = d-dn
print(d)
c = c-n
print(c)
a = d + c
f = m + b
e = a + f
print(d,dn)
print(c,d,f)
print(m,b,p)
print(cn,dn)
print(a,e)
| m = 4
b = 5
c = 6
d = 7
n = 0
d = d * d
print(d)
c = d * 2 - c * 2
print(c)
p = b * d + m * c
print(p)
dn = c - d
print(dn)
cn = c - m
print(cn)
d = d - dn
print(d)
c = c - n
print(c)
a = d + c
f = m + b
e = a + f
print(d, dn)
print(c, d, f)
print(m, b, p)
print(cn, dn)
print(a, e) |
# Copyright (C) 2017 Udacity Inc.
# All Rights Reserved.
# Author: Brandon Kinman
##################################################################################
# UPDATED USING CLASS FROM LESSON 23 PID CONTROL
##################################################################################
class PIDControll... | class Pidcontroller:
def __init__(self, kp=0.0, ki=0.0, kd=0.0, max_windup=20, start_time=0, alpha=1.0, u_bounds=[float('-inf'), float('inf')]):
self.kp_ = float(kp)
self.ki_ = float(ki)
self.kd_ = float(kd)
self.max_windup_ = float(max_windup)
self.alpha = float(alpha)
... |
"""SNMP constants."""
CONF_ACCEPT_ERRORS = 'accept_errors'
CONF_AUTH_KEY = 'auth_key'
CONF_AUTH_PROTOCOL = 'auth_protocol'
CONF_BASEOID = 'baseoid'
CONF_COMMUNITY = 'community'
CONF_DEFAULT_VALUE = 'default_value'
CONF_PRIV_KEY = 'priv_key'
CONF_PRIV_PROTOCOL = 'priv_protocol'
CONF_VERSION = 'version'
DEFAULT_AUTH_PRO... | """SNMP constants."""
conf_accept_errors = 'accept_errors'
conf_auth_key = 'auth_key'
conf_auth_protocol = 'auth_protocol'
conf_baseoid = 'baseoid'
conf_community = 'community'
conf_default_value = 'default_value'
conf_priv_key = 'priv_key'
conf_priv_protocol = 'priv_protocol'
conf_version = 'version'
default_auth_prot... |
try:
while 1:
n=int(input())
k=(n-10)//9
m=n-10-9*k
print(81*(k+1)+m*(m+2)+1)
except:pass
| try:
while 1:
n = int(input())
k = (n - 10) // 9
m = n - 10 - 9 * k
print(81 * (k + 1) + m * (m + 2) + 1)
except:
pass |
def run(df, docs):
for doc in docs:
doc.start("t10 - Columns to lowercase", df)
columns = list(df.columns)
# for each column
for i in columns:
try:
# all charts to lowercase and no leading or trailing spaces
df[i] = df[i].str.lower().str.strip()
except:
... | def run(df, docs):
for doc in docs:
doc.start('t10 - Columns to lowercase', df)
columns = list(df.columns)
for i in columns:
try:
df[i] = df[i].str.lower().str.strip()
except:
continue
for doc in docs:
doc.end(df)
return df |
n = int(input())
for i in range(n):
s = int(input())
p = 0
for j in range(0, s):
p = (p * 2) + 1
print(p)
| n = int(input())
for i in range(n):
s = int(input())
p = 0
for j in range(0, s):
p = p * 2 + 1
print(p) |
#!/usr/bin/env python
#
# chemweight.py
#
#
# import re
mass = {
"H": 1.00794,
"He": 4.002602,
"Li": 6.941,
"Be": 9.012182,
"B": 10.811,
"C": 12.011,
"N": 14.00674,
"O": 15.9994,
"F": 18.9984032,
"Ne": 20.1797,
"Na": 22.989768,
"Mg": 24.3050,
"Al": 26.981539,
"Si": 28.0855,
"P": 30.... | mass = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B': 10.811, 'C': 12.011, 'N': 14.00674, 'O': 15.9994, 'F': 18.9984032, 'Ne': 20.1797, 'Na': 22.989768, 'Mg': 24.305, 'Al': 26.981539, 'Si': 28.0855, 'P': 30.973762, 'S': 32.066, 'Cl': 35.4527, 'Ar': 39.948, 'K': 39.0983, 'Ca': 40.078, 'Sc': 44.95591, '... |
COMPANY_NAME = "Enter the legal name of your business (not the trading name) then use 'Search Companies House'\
and select your company from the list. It will then prefill your company number and postcode."
COMPANY_WEBSITE = "Website address, where we can see your products online."
COMPANY_NUMBER = "The... | company_name = "Enter the legal name of your business (not the trading name) then use 'Search Companies House' and select your company from the list. It will then prefill your company number and postcode."
company_website = 'Website address, where we can see your products online.'
company_number = 'The 8... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class ZtdPlatformImage(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the... | class Ztdplatformimage(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'i... |
{
"targets": [
{
"target_name": "naudiodon",
"sources": [
"src/naudiodon.cc",
"src/GetDevices.cc",
"src/GetHostAPIs.cc",
"src/AudioIO.cc",
"src/PaContext.cc"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"po... | {'targets': [{'target_name': 'naudiodon', 'sources': ['src/naudiodon.cc', 'src/GetDevices.cc', 'src/GetHostAPIs.cc', 'src/AudioIO.cc', 'src/PaContext.cc'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', 'portaudio/include'], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'con... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | class Item(object):
"""A Trait paired with its value and locator."""
def __init__(self, trait, descriptor):
self._trait = trait
self._descriptor = descriptor
attr = property(lambda self: self._trait.attr)
name = property(lambda self: self._trait.name)
default = property(lambda self:... |
#-------------------------------------------------------------------------------
# 6857
#-------------------------------------------------------------------------------
N = 600851475143
d = 3
while d * d <= N and N != 1:
while N % d == 0:
N //= d
last = d
d += 2
if N != 1:
last = N
print(last)
| n = 600851475143
d = 3
while d * d <= N and N != 1:
while N % d == 0:
n //= d
last = d
d += 2
if N != 1:
last = N
print(last) |
def doIt (func, x, y):
z = func (x, y)
return z
def add (arg1, arg2):
return arg1 + arg2
def sub (arg1, arg2):
return arg1 - arg2
print ('Addition:')
print ( doIt (add, 2, 3) ) # Passing the name of the function
# and its arguments
print ('Subtraction:')
print ( do... | def do_it(func, x, y):
z = func(x, y)
return z
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2):
return arg1 - arg2
print('Addition:')
print(do_it(add, 2, 3))
print('Subtraction:')
print(do_it(sub, 2, 3)) |
list=["rayne","coder","python","c","c++","java"]
#REMOVE
list.remove("java")
print(list)
#remove BY index
list.pop(1) # 1- coder
print(list)
| list = ['rayne', 'coder', 'python', 'c', 'c++', 'java']
list.remove('java')
print(list)
list.pop(1)
print(list) |
n=int(input())
namibia=0
kenya=0
tanzania=0
ethiopia=0
zim=0
zam=0
zimzam=0
zimzamMode=False
namaVisit=False
last=''
lgo=""
for i in range(n):
go=input()
lgo=go
if last==go: continue
if go=='kenya': kenya=1
if go=='tanzania': tanzania=1
if go=='ethiopia': ethiopia=1
if go=='zambia':
if last=='zimbabwe':
z... | n = int(input())
namibia = 0
kenya = 0
tanzania = 0
ethiopia = 0
zim = 0
zam = 0
zimzam = 0
zimzam_mode = False
nama_visit = False
last = ''
lgo = ''
for i in range(n):
go = input()
lgo = go
if last == go:
continue
if go == 'kenya':
kenya = 1
if go == 'tanzania':
tanzania = 1... |
#
# PySNMP MIB module NETREALITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETREALITY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:10:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint) ... |
'''
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should
run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4-... | """
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should
run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.