content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... | DA.data_factory.load()
print(f'source: {DA.paths.data_landing_location}')
print(f'Target: {DA.db_name}')
print(f'Storage Location: {DA.paths.storage_location}')
DA.generate_register_dlt_event_metrics_sql()
for command in generate_register_dlt_event_metrics_sql_string.split(';'):
if len(command) ... |
class RebarContainerParameterManager(object,IDisposable):
""" Provides implementation of RebarContainer parameters overrides. """
def AddOverride(self,paramId,value):
"""
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: int)
Adds an override for the given parameter as its value... | class Rebarcontainerparametermanager(object, IDisposable):
""" Provides implementation of RebarContainer parameters overrides. """
def add_override(self, paramId, value):
"""
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: int)
Adds an override for the given parameter a... |
# MIT License
#
# Copyright (c) 2019 Michael J Simms. All rights reserved.
#
# 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
... | def is_point_in_polygon(point, poly):
"""Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points)."""
if not isinstance(poly, list):
return False
num_crossings = 0
num_vertices = len(pol... |
# Meta classes
class Meta(type):
def __new__(self, class_name, bases, attrs):
print(attrs)
a = {}
for name, val in attrs.items():
if name.startswith("__"):
a[name] = val
else:
a[name.upper()] = val
return type(class_name, bases... | class Meta(type):
def __new__(self, class_name, bases, attrs):
print(attrs)
a = {}
for (name, val) in attrs.items():
if name.startswith('__'):
a[name] = val
else:
a[name.upper()] = val
return type(class_name, bases, a)
class D... |
def listifyer(word):
listify = list(word)
return listify
def rearrPL(word):
seperator = ','
del word[-1]
del word[-1]
last_element = word[(len(word) - 1)]
word.insert(0, last_element)
del word[-1]
new_word = seperator.join(word)
return new_word
def rearrE(word):
first_let... | def listifyer(word):
listify = list(word)
return listify
def rearr_pl(word):
seperator = ','
del word[-1]
del word[-1]
last_element = word[len(word) - 1]
word.insert(0, last_element)
del word[-1]
new_word = seperator.join(word)
return new_word
def rearr_e(word):
first_lette... |
mortgage = 366323
agent_fee = .06
prorated_property_taxes = 400
prorated_mortgage_interest = 1500
other_fees = 2500
closing_costs = prorated_property_taxes + prorated_mortgage_interest + other_fees
sale_price = input('What is the sale price of your home? ')
agent_cost = agent_fee * float(sale_price)
price_per_sqft = (f... | mortgage = 366323
agent_fee = 0.06
prorated_property_taxes = 400
prorated_mortgage_interest = 1500
other_fees = 2500
closing_costs = prorated_property_taxes + prorated_mortgage_interest + other_fees
sale_price = input('What is the sale price of your home? ')
agent_cost = agent_fee * float(sale_price)
price_per_sqft = f... |
"""
ipcai2016
Copyright (c) German Cancer Research Center,
Computer Assisted Interventions.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE for details
"""
| """
ipcai2016
Copyright (c) German Cancer Research Center,
Computer Assisted Interventions.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE for details
""" |
# -*- coding: utf-8 -*-
"""Top-level package for Django CMS export page."""
__author__ = """Maykin Media"""
__email__ = 'support@maykinmedia.nl'
__version__ = '0.1.0'
| """Top-level package for Django CMS export page."""
__author__ = 'Maykin Media'
__email__ = 'support@maykinmedia.nl'
__version__ = '0.1.0' |
_base_ = './mask_rcnn_r50_fpn_gn_ws-all_2x_coco.py'
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://jhu/resnet101_gn_ws'))) | _base_ = './mask_rcnn_r50_fpn_gn_ws-all_2x_coco.py'
model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://jhu/resnet101_gn_ws'))) |
'''
Author : MiKueen
Level : Medium
Problem Statement : Find First and Last Position of Elements in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target ... | """
Author : MiKueen
Level : Medium
Problem Statement : Find First and Last Position of Elements in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target ... |
totidade = homens = mulheresmenores = 0
while True:
print('-'*20)
print('Cadastre uma pessoa')
print('-'*20)
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F]')).strip().upper()[0]
cont = ' '
while cont not in 'SN':
cont = str... | totidade = homens = mulheresmenores = 0
while True:
print('-' * 20)
print('Cadastre uma pessoa')
print('-' * 20)
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F]')).strip().upper()[0]
cont = ' '
while cont not in 'SN':
cont = ... |
def get_build_tool(name):
tools = {
"cmake": CMakeBuildTool,
"colcon": ColconBuildTool,
"catkin": CatkinBuildTool
}
if name not in tools:
raise Exception("Unknown build tool: {}".format(name))
return tools[name]
class BuildTool():
@staticmethod
def getCommands():... | def get_build_tool(name):
tools = {'cmake': CMakeBuildTool, 'colcon': ColconBuildTool, 'catkin': CatkinBuildTool}
if name not in tools:
raise exception('Unknown build tool: {}'.format(name))
return tools[name]
class Buildtool:
@staticmethod
def get_commands():
return [k for k in se... |
number = input('Enter a number: ')
number = int(number)
if number % 2 == 0:
print('The number is even')
else:
print('The number is odd') | number = input('Enter a number: ')
number = int(number)
if number % 2 == 0:
print('The number is even')
else:
print('The number is odd') |
print("input 5 decimals")
values = []
for i in range(5):
values.append(float(input("demical #"+str(i+1)+": ")))
cnt = 0
for i in values:
if i >= 10 and i <= 100:
cnt += 1
print(cnt)
| print('input 5 decimals')
values = []
for i in range(5):
values.append(float(input('demical #' + str(i + 1) + ': ')))
cnt = 0
for i in values:
if i >= 10 and i <= 100:
cnt += 1
print(cnt) |
# 3. n children have got m pieces of candy. They want to eat as much candy as they can, but each child must eat exactly the same amount of candy as any other child. Determine how many pieces of candy will be eaten by all the children together. Individual pieces of candy cannot be split.
# Example
# For n = 3 and m = ... | def candies(n, m):
result = m - m % n
return result
print(candies(4, 25)) |
def install_file(name, src, out):
"""
Install a single file, using `install`. Returns out, so that it can be easily
embedded into a filegroup rule.
"""
native.genrule(
name = name,
srcs = [src],
outs = [out],
cmd = "install -c -m 644 $(location {}) $(location {})".fo... | def install_file(name, src, out):
"""
Install a single file, using `install`. Returns out, so that it can be easily
embedded into a filegroup rule.
"""
native.genrule(name=name, srcs=[src], outs=[out], cmd='install -c -m 644 $(location {}) $(location {})'.format(src, out))
return out
def _valid... |
test = {
'name': 'lab1_p1',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like your variable is not named correctly.
>>> # Please check for a typo. The variable name should be
>>> # my_favorite_things_lst
>>> 'my_favorite_things_lst' in v... | test = {'name': 'lab1_p1', 'suites': [{'cases': [{'code': "\n >>> # It looks like your variable is not named correctly.\n >>> # Please check for a typo. The variable name should be \n >>> # my_favorite_things_lst\n >>> 'my_favorite_things_lst' in vars()\n True\n "},... |
"""Cascade Mask RCNN with ResNet101-FPN, 3x schedule, MS training."""
_base_ = "./cascade_mask_rcnn_r50_fpn_3x_ins_seg_bdd100k.py"
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type="Pretrained", checkpoint="torchvision://resnet101"),
)
)
load_from = "https://dl.cv.ethz.ch/bdd100k/ins_s... | """Cascade Mask RCNN with ResNet101-FPN, 3x schedule, MS training."""
_base_ = './cascade_mask_rcnn_r50_fpn_3x_ins_seg_bdd100k.py'
model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101')))
load_from = 'https://dl.cv.ethz.ch/bdd100k/ins_seg/models/cascade_mask_rcnn_r1... |
'''error pattern'''
class A:
def __init__(self, text):
print('a')
print(text)
class B(A):
def __init__(self, text):
print('b')
super(B, self).__init__(text)
class C:
def __init__(self, **kwargs):
print('c')
super(C, self).__init__()
class D(C, B):
def __init__(self, text):
pr... | """error pattern"""
class A:
def __init__(self, text):
print('a')
print(text)
class B(A):
def __init__(self, text):
print('b')
super(B, self).__init__(text)
class C:
def __init__(self, **kwargs):
print('c')
super(C, self).__init__()
class D(C, B):
... |
def test_restart_opencart_mysql_service(restart_mysql):
assert "active (running)" in restart_mysql
print(restart_mysql)
def test_restart_opencart_apache_service(restart_apache):
assert "active (running)" in restart_apache
print(restart_apache)
def test_opencart_is_active(request_opencart):
print... | def test_restart_opencart_mysql_service(restart_mysql):
assert 'active (running)' in restart_mysql
print(restart_mysql)
def test_restart_opencart_apache_service(restart_apache):
assert 'active (running)' in restart_apache
print(restart_apache)
def test_opencart_is_active(request_opencart):
print(r... |
def fatorial(n):
nFatorial=n
for i in range(1,n):
nFatorial=nFatorial*(n-i)
return nFatorial
| def fatorial(n):
n_fatorial = n
for i in range(1, n):
n_fatorial = nFatorial * (n - i)
return nFatorial |
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
num2day = ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday']
mon2num = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
count = 0
for i in range(1971, year):
i... | class Solution:
def day_of_the_week(self, day: int, month: int, year: int) -> str:
num2day = ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday']
mon2num = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
count = 0
for i in range(1971, year):
... |
def preenchimento_de_vetor_iv():
n = 0
par = list()
impar = list()
while n < 15:
numero = int(input())
if numero % 2 == 0:
par.append(numero)
else:
impar.append(numero)
if len(par) == 5:
for i in range(5):
print(f'par[{i... | def preenchimento_de_vetor_iv():
n = 0
par = list()
impar = list()
while n < 15:
numero = int(input())
if numero % 2 == 0:
par.append(numero)
else:
impar.append(numero)
if len(par) == 5:
for i in range(5):
print(f'par[{i... |
# -*- coding: utf-8 -*-
# @Time : 2018/4/12 20:16
# @Author : ddvv
# @Site : http://ddvv.life
# @File : __init__.py.py
# @Software: PyCharm
def main():
pass
if __name__ == "__main__":
main() | def main():
pass
if __name__ == '__main__':
main() |
n= int(input())
alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(n):
letras=input()
pulos=int(input())
novaPalavra=""
for j in range(len(letras)):
posicao=alfabeto.find(letras[j])
numeroPosicao=posicao-pulos
if numeroPosicao<0:
novaPosicao=len(alfabeto)+numer... | n = int(input())
alfabeto = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in range(n):
letras = input()
pulos = int(input())
nova_palavra = ''
for j in range(len(letras)):
posicao = alfabeto.find(letras[j])
numero_posicao = posicao - pulos
if numeroPosicao < 0:
nova_posicao = le... |
sec = { # Security
1102: {"Descr": "The audit log was cleared",
"Provider": "Microsoft-Windows-Eventlog",
"SubjectUserSid": "SID",
"SubjectUserName": "Username",
"SubjectDomainName": "Domain",
"SubjectLogonId": "LogonId"},
4616: {"Descr": "The system time... | sec = {1102: {'Descr': 'The audit log was cleared', 'Provider': 'Microsoft-Windows-Eventlog', 'SubjectUserSid': 'SID', 'SubjectUserName': 'Username', 'SubjectDomainName': 'Domain', 'SubjectLogonId': 'LogonId'}, 4616: {'Descr': 'The system time was changed', 'Provider': 'Microsoft-Windows-Security-Auditing', 'SubjectUse... |
"""Exceptions.py
Define exceptions used by the library."""
class ResponseError(Exception):
"""Own class for exceptions related
to response errors. Currently only present in two places."""
pass #Don't do anything else than just define the function
| """Exceptions.py
Define exceptions used by the library."""
class Responseerror(Exception):
"""Own class for exceptions related
to response errors. Currently only present in two places."""
pass |
def get_friendly_dict(friend_list):
""" Accept a list of reciprocal friendship links between individuals and
return a dictionary of degree-one friends of each individual in a social
network. """
# first, we'll get all the individuals name using union set and put it into
# unique_name list
... | def get_friendly_dict(friend_list):
""" Accept a list of reciprocal friendship links between individuals and
return a dictionary of degree-one friends of each individual in a social
network. """
unique_name_list = set()
for friend in range(1, len(friend_list)):
unique_name = set(friend_list... |
class Solution:
def arrayRankTransform(self, arr2: List[int]) -> List[int]:
d = {}
if len(arr2)==0: return []
ct = 1
arr = sorted(arr2)
d[arr[0]] = 1
for i in range(1,len(arr)):
if arr[i]>arr[i-1]:
ct+=1
d[arr[i]] = ct
r... | class Solution:
def array_rank_transform(self, arr2: List[int]) -> List[int]:
d = {}
if len(arr2) == 0:
return []
ct = 1
arr = sorted(arr2)
d[arr[0]] = 1
for i in range(1, len(arr)):
if arr[i] > arr[i - 1]:
ct += 1
... |
# Our server roles:
config.rdbms = ['127.0.0.1']
config.httpd = ['localhost']
def production():
# this would set `rdbms` and `httpd` to prod. values.
# for now we just switch them around in order to observe the effect
config.rdbms, config.httpd = config.httpd, config.rdbms
def build():
local('echo Bu... | config.rdbms = ['127.0.0.1']
config.httpd = ['localhost']
def production():
(config.rdbms, config.httpd) = (config.httpd, config.rdbms)
def build():
local('echo Building project')
@roles('rdbms')
def prepare_db():
run('echo Preparing database for deployment')
@roles('httpd')
def prepare_web():
run('... |
# --------------
##File path for the file
file_path
#Code starts here
#Function to read file
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence=file.rea... | file_path
def read_file(path):
file = open(path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
(file_path_1, file_path_2)
def read_file1(file1):
file1 = open(file_path_1, 'r')
sentence1 = file1.readline()
file1.clos... |
def decompose(n):
return helper(n, n**2)
def helper(n, sum, arr=[]):
if sum==0:
return arr[::-1]
for i in range(n-1, -1, -1):
if i**2<=sum:
return helper(i, sum-i**2, arr+[i]) or helper(i, sum, arr) | def decompose(n):
return helper(n, n ** 2)
def helper(n, sum, arr=[]):
if sum == 0:
return arr[::-1]
for i in range(n - 1, -1, -1):
if i ** 2 <= sum:
return helper(i, sum - i ** 2, arr + [i]) or helper(i, sum, arr) |
"""
Given three sorted arrays A, B and C of not necessarily same sizes.
Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that
a, b, c belongs arrays A, B, C respectively.
i.e. minimize | max(a,b,c) - min(a,b,c) |.
Example :
Input:
A : [ 1, 4, 5, 8, 10 ]
... | """
Given three sorted arrays A, B and C of not necessarily same sizes.
Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that
a, b, c belongs arrays A, B, C respectively.
i.e. minimize | max(a,b,c) - min(a,b,c) |.
Example :
Input:
A : [ 1, 4, 5, 8, 10 ]
... |
"""
Check BinaryTree section
This question is also in the SDE Sheet
Learn : The Height can be defined over a binary tree,
but depth is defined over a node, ie there is a dept of each node
"""
| """
Check BinaryTree section
This question is also in the SDE Sheet
Learn : The Height can be defined over a binary tree,
but depth is defined over a node, ie there is a dept of each node
""" |
def filterTags(attrs):
""" Convert some ShapeVIS attributes to OSM. """
result = {}
if 'HAALPLTSMN' in attrs:
result['name'] = attrs['HAALPLTSMN']
result['bus'] = 'yes'
# Default
result['public_transport'] = 'stop_position'
if 'station' in result['name'].lower() an... | def filter_tags(attrs):
""" Convert some ShapeVIS attributes to OSM. """
result = {}
if 'HAALPLTSMN' in attrs:
result['name'] = attrs['HAALPLTSMN']
result['bus'] = 'yes'
result['public_transport'] = 'stop_position'
if 'station' in result['name'].lower() and 'centrum' in resul... |
class person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return f"{self.first_name} {self.last_name}"
def email(self):
return f"{self.first_name}{self.last_name}@gmail.com"
| class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return f'{self.first_name} {self.last_name}'
def email(self):
return f'{self.first_name}{self.last_name}@gmail.com' |
class Blood(object):
"""
Most characters will have ordinary blood but some could have acidic blood or with other properties.
"""
def __init__(self, uid, name):
self.uid = uid
self.name = name | class Blood(object):
"""
Most characters will have ordinary blood but some could have acidic blood or with other properties.
"""
def __init__(self, uid, name):
self.uid = uid
self.name = name |
class WorksharingUtils(object,IDisposable):
""" A static class that contains utility functions related to worksharing. """
@staticmethod
def CheckoutElements(document,elementsToCheckout,options=None):
"""
CheckoutElements(document: Document,elementsToCheckout: ICollection[ElementId]) -> ICollection[ElementI... | class Worksharingutils(object, IDisposable):
""" A static class that contains utility functions related to worksharing. """
@staticmethod
def checkout_elements(document, elementsToCheckout, options=None):
"""
CheckoutElements(document: Document,elementsToCheckout: ICollection[ElementId]) -> IColl... |
'''
Set Matrix Zeros
Asked in: Oracle, Amazon
https://www.interviewbit.com/problems/set-matrix-zeros/
Given a matrix, A of size M x N of 0s and 1s. If an element is 0, set its entire row and column to 0.
Note: This will be evaluated on the extra memory used. Try to minimize the space and time complexity.
Input Fo... | """
Set Matrix Zeros
Asked in: Oracle, Amazon
https://www.interviewbit.com/problems/set-matrix-zeros/
Given a matrix, A of size M x N of 0s and 1s. If an element is 0, set its entire row and column to 0.
Note: This will be evaluated on the extra memory used. Try to minimize the space and time complexity.
Input Fo... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MoviePipeline(object):
def process_item(self, item, spider):
with open('out/my_meiju.txt', 'a', encoding='U... | class Moviepipeline(object):
def process_item(self, item, spider):
with open('out/my_meiju.txt', 'a', encoding='UTF-8') as fp:
fp.write(str(item['name'].strip()) + '\n') |
number = int(input())
synonyms_dict = dict()
for num in range (number):
word = input()
synonym = input()
if word not in synonyms_dict.keys():
synonyms_dict[word] = list()
synonyms_dict[word].append(synonym)
for word in synonyms_dict:
synonyms = ", ".join(synonyms_dict[word])
print(f"{... | number = int(input())
synonyms_dict = dict()
for num in range(number):
word = input()
synonym = input()
if word not in synonyms_dict.keys():
synonyms_dict[word] = list()
synonyms_dict[word].append(synonym)
for word in synonyms_dict:
synonyms = ', '.join(synonyms_dict[word])
print(f'{word... |
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
#
# 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... | """
Relocator for user-provided relocation directives
"""
class Myrelocator(object):
"""
Main class
"""
def __init__(self):
"""
Initialize the relocator
"""
pass
def set_controller(self, controller):
"""
Sets the controller
"""
pass
... |
"""
django_ocr_server/tests/__init__.py
+++++++++++++++++++++++++++++++++++
| Author: shmakovpn <shmakovpn@yandex.ru>
| Date: 2021-01-07
""" | """
django_ocr_server/tests/__init__.py
+++++++++++++++++++++++++++++++++++
| Author: shmakovpn <shmakovpn@yandex.ru>
| Date: 2021-01-07
""" |
class Person:
# allocate space for only these attributes so we don't need to create a __dict__ property in the class and we save space when parsing large files
__slots__ = ["lastName", "firstName", "middleInitial",
"gender", "favoriteColor", "dateOfBirth"]
def __init__(self, lastName, fir... | class Person:
__slots__ = ['lastName', 'firstName', 'middleInitial', 'gender', 'favoriteColor', 'dateOfBirth']
def __init__(self, lastName, firstName, middleInitial, gender, favoriteColor, dateOfBirth):
self.lastName = lastName
self.firstName = firstName
self.middleInitial = middleIniti... |
expected_output = {
'10.1.1.2': {
'conn_capability': 'IPv4-IPv6-Subnet',
'conn_inst': 1,
'conn_status': 'On (Speaker) :: On (Listener)',
'conn_version': 5,
'duration': '0:00:00:57 (dd:hr:mm:sec) :: 0:00:00:55 (dd:hr:mm:sec)',
'local_mode': 'Both',
'peer_ip': '... | expected_output = {'10.1.1.2': {'conn_capability': 'IPv4-IPv6-Subnet', 'conn_inst': 1, 'conn_status': 'On (Speaker) :: On (Listener)', 'conn_version': 5, 'duration': '0:00:00:57 (dd:hr:mm:sec) :: 0:00:00:55 (dd:hr:mm:sec)', 'local_mode': 'Both', 'peer_ip': '10.1.1.2', 'source_ip': '10.1.1.1', 'tcp_conn_fd': '1(Speaker)... |
class Stack:
def __init__(self):
self.list = []
def push(self, element):
self.list.append(element)
def pop(self):
assert len(self.list) > 0, "Stack is empty"
return self.list.pop()
def isEmpty(self):
return len(self.list) == 0
| class Stack:
def __init__(self):
self.list = []
def push(self, element):
self.list.append(element)
def pop(self):
assert len(self.list) > 0, 'Stack is empty'
return self.list.pop()
def is_empty(self):
return len(self.list) == 0 |
""" Class that implements K stacks in an array """
class KStacks:
def __init__(self, cap, k):
self.tops = [-1] * k
self.arr = [0] * cap
self.next = [-1] * cap
self.free_top = 0
for i in range(cap-1):
self.next[i] = i+1
self.capacity = cap
def push(... | """ Class that implements K stacks in an array """
class Kstacks:
def __init__(self, cap, k):
self.tops = [-1] * k
self.arr = [0] * cap
self.next = [-1] * cap
self.free_top = 0
for i in range(cap - 1):
self.next[i] = i + 1
self.capacity = cap
def pu... |
#!/usr/bin/python
# Calculer la somme des valeurs du tableau
def somme_tab(tab):
somme = 0
for i in range(len(tab)):
somme += tab[i]
return somme
tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17]
print(somme_tab(tab))
| def somme_tab(tab):
somme = 0
for i in range(len(tab)):
somme += tab[i]
return somme
tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17]
print(somme_tab(tab)) |
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating an empty ... | dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print('\nDictionary with the use of Integer Keys: ')
print(Dict)
dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print('\nDictionary with the use of Mixed Keys: ')
print(Dict)
dict = {}
print('Empty Dictionary: ')
print(Dict)
dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print('\nD... |
class Solution(object):
def twoSumLessThanK(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
# Guard
if not A or not K or len(A) <= 1:
return -1
# Sort inputs
inputs_sorted = sorted(A)
# Two pointers thro... | class Solution(object):
def two_sum_less_than_k(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
if not A or not K or len(A) <= 1:
return -1
inputs_sorted = sorted(A)
min_pointer = 0
max_pointer = len(A) - 1
... |
def threeSum(nums):
s = set()
nums.sort()
for i in range(len(nums)):
m = {}
for j in range(i+1, len(nums)):
x = -nums[i] - nums[j]
if x not in m:
m[nums[j]] = j
else:
s.add((x,nums[i],nums[j]))
return list(s) | def three_sum(nums):
s = set()
nums.sort()
for i in range(len(nums)):
m = {}
for j in range(i + 1, len(nums)):
x = -nums[i] - nums[j]
if x not in m:
m[nums[j]] = j
else:
s.add((x, nums[i], nums[j]))
return list(s) |
array = [54, 26, 93, 17, 77, 31, 44, 55, 20]
def bubble_sort(nums: list):
for i in range(len(nums)):
for j in range(len(nums) - 1, i, -1):
if nums[j - 1] > nums[j]:
nums[j - 1], nums[j] = nums[j], nums[j - 1]
print(array)
bubble_sort(array)
print(array)
| array = [54, 26, 93, 17, 77, 31, 44, 55, 20]
def bubble_sort(nums: list):
for i in range(len(nums)):
for j in range(len(nums) - 1, i, -1):
if nums[j - 1] > nums[j]:
(nums[j - 1], nums[j]) = (nums[j], nums[j - 1])
print(array)
bubble_sort(array)
print(array) |
"""
This package contains the following entities:
1) Protocol
2) Attack Suite
3) Attack
4) Input Format
In this module, we have the backend entities to represent and structure our code
And these entities have the following relations in between: (Connection endpoints represent cardinality o... | """
This package contains the following entities:
1) Protocol
2) Attack Suite
3) Attack
4) Input Format
In this module, we have the backend entities to represent and structure our code
And these entities have the following relations in between: (Connection endpoints represent cardinality o... |
BLKNUM_OFFSET = 1000000000
TXINDEX_OFFSET = 10000
def decode_utxo_id(utxo_id):
blknum = utxo_id // BLKNUM_OFFSET
txindex = (utxo_id % BLKNUM_OFFSET) // TXINDEX_OFFSET
oindex = utxo_id % TXINDEX_OFFSET
return blknum, txindex, oindex
def encode_utxo_id(blknum, txindex, oindex):
return (blknum * BL... | blknum_offset = 1000000000
txindex_offset = 10000
def decode_utxo_id(utxo_id):
blknum = utxo_id // BLKNUM_OFFSET
txindex = utxo_id % BLKNUM_OFFSET // TXINDEX_OFFSET
oindex = utxo_id % TXINDEX_OFFSET
return (blknum, txindex, oindex)
def encode_utxo_id(blknum, txindex, oindex):
return blknum * BLKNU... |
"""
Note: Moved to umpyre (pip install umpyre)
Get stats about packages. Your own, or other's.
Things like...
# >>> import collections
# >>> modules_info_df(collections)
# lines empty_lines ... num_of_functions num_of_classes
# collections.__init__ 1273 189 ... 1 ... | """
Note: Moved to umpyre (pip install umpyre)
Get stats about packages. Your own, or other's.
Things like...
# >>> import collections
# >>> modules_info_df(collections)
# lines empty_lines ... num_of_functions num_of_classes
# collections.__init__ 1273 189 ... 1 ... |
# OAuth app keys
DROPBOX_KEY = None
DROPBOX_SECRET = None
DROPBOX_AUTH_CSRF_TOKEN = 'dropbox-auth-csrf-token'
# Max file size permitted by frontend in megabytes
MAX_UPLOAD_SIZE = 150
| dropbox_key = None
dropbox_secret = None
dropbox_auth_csrf_token = 'dropbox-auth-csrf-token'
max_upload_size = 150 |
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', 'jobs.harenconstruction.com', 'www.harenconstruction.com', 'harenconstruction.com' '104.236.59.248']
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = '/home/applicant/' #os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#... | allowed_hosts = ['localhost', '127.0.0.1', '[::1]', 'jobs.harenconstruction.com', 'www.harenconstruction.com', 'harenconstruction.com104.236.59.248']
base_dir = '/home/applicant/'
debug = False
databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'applicant', 'USER': 'applicant', 'PASSWO... |
#
# PySNMP MIB module ZhoneDsl-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZhoneDsl-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:52:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint) ... |
def is_on(S, j):
return (S & (1 << j)) >> j
def set_all(n):
return (1 << n) - 1
def low_bit(S):
return (S & (-S)).bit_length() - 1
def clear_bit(S, j):
return S & ~(1 << j)
| def is_on(S, j):
return (S & 1 << j) >> j
def set_all(n):
return (1 << n) - 1
def low_bit(S):
return (S & -S).bit_length() - 1
def clear_bit(S, j):
return S & ~(1 << j) |
"""
practice test cases for testing plugin
"""
def test_iequals1():
"""
practice test case 1 for testing plugin
"""
i = 1
assert i == 1
def test_iequals2():
"""
practice test case 2 for testing plugin
"""
i = 2
assert i == 2
| """
practice test cases for testing plugin
"""
def test_iequals1():
"""
practice test case 1 for testing plugin
"""
i = 1
assert i == 1
def test_iequals2():
"""
practice test case 2 for testing plugin
"""
i = 2
assert i == 2 |
def histogram(s):
"""Use get to write histogram more concisely"""
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
print(histogram('brontosaurus'))
| def histogram(s):
"""Use get to write histogram more concisely"""
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
print(histogram('brontosaurus')) |
class core50():
def __init__(self, paradigm, run):
self.batch_num = 5
self.rootdir = '/home/rushikesh/code/core50_dataloaders/dataloaders/task_filelists/'
self.train_data = []
self.train_labels = []
self.train_groups = [[],[],[],[],[]]
for b in range(self.batch_num):
with open( self.rootdir + paradig... | class Core50:
def __init__(self, paradigm, run):
self.batch_num = 5
self.rootdir = '/home/rushikesh/code/core50_dataloaders/dataloaders/task_filelists/'
self.train_data = []
self.train_labels = []
self.train_groups = [[], [], [], [], []]
for b in range(self.batch_num... |
def romanToInt(s):
"""Calculates value of Roman numeral string
Args:
s (string): String of Roman numeral characters being analyzed
Returns:
int: integer value of Roman numeral string
"""
sum = 0
i = 0
while i < len(s):
if s[i] == 'M':
sum += 1000
elif s[i] == 'D':
sum +=... | def roman_to_int(s):
"""Calculates value of Roman numeral string
Args:
s (string): String of Roman numeral characters being analyzed
Returns:
int: integer value of Roman numeral string
"""
sum = 0
i = 0
while i < len(s):
if s[i] == 'M':
sum += 1000
elif s[... |
User_name = input("What is your name? ")
User_age = input("How old are you? ")
User_liveplace = input("Where are you live? ")
print ( "This is", User_name)
print ( "It is" , User_age)
print ( "(S)he live in", User_liveplace) | user_name = input('What is your name? ')
user_age = input('How old are you? ')
user_liveplace = input('Where are you live? ')
print('This is', User_name)
print('It is', User_age)
print('(S)he live in', User_liveplace) |
def includes(doc, path, title=3, **args):
j = doc.docsite._j
spath = j.sal.fs.processPathForDoubleDots(j.sal.fs.joinPaths(j.sal.fs.getDirName(doc.path), path))
if not j.sal.fs.exists(spath, followlinks=True):
doc.raiseError("Cannot find path for macro includes:%s" % spath)
docNames = [j.sal.fs... | def includes(doc, path, title=3, **args):
j = doc.docsite._j
spath = j.sal.fs.processPathForDoubleDots(j.sal.fs.joinPaths(j.sal.fs.getDirName(doc.path), path))
if not j.sal.fs.exists(spath, followlinks=True):
doc.raiseError('Cannot find path for macro includes:%s' % spath)
doc_names = [j.sal.fs.... |
#!/usr/bin/env python
lista=[2,3,4,1]
lista2=lista[:] #Copia
lista.sort()
if lista == lista2:
print("Lista ordenada")
else:
print("Lista no ordenada") | lista = [2, 3, 4, 1]
lista2 = lista[:]
lista.sort()
if lista == lista2:
print('Lista ordenada')
else:
print('Lista no ordenada') |
__author__ = "Andre Merzky"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
# ------------------------------------------------------------------------------
# FIXME: OS enums, ARCH enums
# resource type enum
COMPUTE = 1 # resource accepting jobs
STORAGE = 2 ... | __author__ = 'Andre Merzky'
__copyright__ = 'Copyright 2012-2013, The SAGA Project'
__license__ = 'MIT'
compute = 1
storage = 2
network = 4
unknown = None
new = 1
pending = 2
active = 4
canceled = 8
expired = 16
done = EXPIRED
failed = 32
final = CANCELED | DONE | FAILED
id = 'Id'
rtype = 'Rtype'
state = 'State'
state_... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | """The webdav package provides WebDAV capability for common Zope objects.
Current WebDAV support in Zope provides for the correct handling of HTTP
GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, PROPFIND, PROPPATCH, MKCOL,
COPY and MOVE methods, as appropriate for the object that is the target
of the operati... |
"""
lab 8
"""
#3.1
#def calcwords(input_str):
# return len(input_str.split())
#3.2
#demo_str = 'hello world!'
#print(calcwords(demo_str))
#3.3
def calnum(input_list):
min_item = input_list[0]
for eachnum in input_list:
if type(eachnum) is not str:
if min_item >= eachnum:
... | """
lab 8
"""
def calnum(input_list):
min_item = input_list[0]
for eachnum in input_list:
if type(eachnum) is not str:
if min_item >= eachnum:
min_item = eachnum
return min_item
num_list = [1, 2, 3, 4, 5, 6]
print(calnum(num_list))
mix_list = [1, 2, 3, 4, 'a', 5, 6]
prin... |
def is_zigzag(numbers: list):
if len(numbers) != 3:
raise ValueError('must be 3 elements {}'.format(numbers))
return 1 if (numbers[0] < numbers[1] > numbers[2]) or (numbers[0] > numbers[1] < numbers[2]) else 0
if __name__ == "__main__":
#numbers = [1, 2, 1]
numbers = [1, 2, 1, 3, 4]
numb... | def is_zigzag(numbers: list):
if len(numbers) != 3:
raise value_error('must be 3 elements {}'.format(numbers))
return 1 if numbers[0] < numbers[1] > numbers[2] or numbers[0] > numbers[1] < numbers[2] else 0
if __name__ == '__main__':
numbers = [1, 2, 1, 3, 4]
numbers = [1, 3, 4, 5, 6, 14, 14]
... |
def ext_here(props):
props['ext_ui']['filedir2']=props['ext_ui']['filedir']
props['music'].clickSon()
#print(filedir2)
decomp(props)
def ext_to(props):
filedir=props['ext_ui']['filedir']
root=props['root']
filedialog=props['filedialog']
props['music'].clickSon()
root.filename... | def ext_here(props):
props['ext_ui']['filedir2'] = props['ext_ui']['filedir']
props['music'].clickSon()
decomp(props)
def ext_to(props):
filedir = props['ext_ui']['filedir']
root = props['root']
filedialog = props['filedialog']
props['music'].clickSon()
root.filename = filedialog.askdir... |
class CartItem(object):
def __init__(self, url, title=None, abstract=None, mime_type=None, dataset=None):
self.url = url
self._title = title
self._abstract = abstract
self.mime_type = mime_type or 'application/x-netcdf'
self.dataset = dataset
@property
def title(self... | class Cartitem(object):
def __init__(self, url, title=None, abstract=None, mime_type=None, dataset=None):
self.url = url
self._title = title
self._abstract = abstract
self.mime_type = mime_type or 'application/x-netcdf'
self.dataset = dataset
@property
def title(sel... |
class Node:
""" A Circular linked node. """
def __init__(self, data=None):
self.data = data
self.next = None
class CircularList:
def __init__ (self):
self.tail = None
self.head = None
self.size = 0
def append(self, data):
node... | class Node:
""" A Circular linked node. """
def __init__(self, data=None):
self.data = data
self.next = None
class Circularlist:
def __init__(self):
self.tail = None
self.head = None
self.size = 0
def append(self, data):
node = node(data)
if se... |
"""
Session: 10
Topic: A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.
"""
num = int(input("How many terms? "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
... | """
Session: 10
Topic: A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.
"""
num = int(input('How many terms? '))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, 'is not a prime number')
print(i, 'tim... |
class UserDoesNotExist(Exception):
pass
class PasswordDoesNotMatch(Exception):
pass
class EmailAlreadyRegistered(Exception):
pass
| class Userdoesnotexist(Exception):
pass
class Passworddoesnotmatch(Exception):
pass
class Emailalreadyregistered(Exception):
pass |
try:
basestring
except NameError:
basestring = str # Python 2 -> 3 alias
""" Exposes decorator class."""
__all__ = ["DocInheritDecorator"]
class DocInheritDecorator(object):
""" A decorator that merges provided parent docstring with the docstring of the decorated
function/method/property.
Meth... | try:
basestring
except NameError:
basestring = str
' Exposes decorator class.'
__all__ = ['DocInheritDecorator']
class Docinheritdecorator(object):
""" A decorator that merges provided parent docstring with the docstring of the decorated
function/method/property.
Methods
-------
doc_merger... |
"""
Albert is playing with text. Instead of writing sentences as they should be, he decided to randomly swap pairs of letters in them. But not even in the whole text, only from some place in the middle of the text onward. At least he marked the places in the text, where each substitution starts, and what two letters ar... | """
Albert is playing with text. Instead of writing sentences as they should be, he decided to randomly swap pairs of letters in them. But not even in the whole text, only from some place in the middle of the text onward. At least he marked the places in the text, where each substitution starts, and what two letters ar... |
"""
NAME: DIBANSA, RAHMANI P.
COURSE-YEAR LEVEL-SECTION: BSCPE 2-2
SUBJECT: SOFTWARE DEVELOPMENT
PROGRAM DESCRIPTION: A PYTHON PROGRAM THAT SORTS A LIST THROUGH
MERGE SORT FUNCTION
"""
# THIS FUNCTION TAKES A THE USER'S INPUTTED LIST, A START VARIABLE THAT
# MARKS WHERE THE FUNCTION WO... | """
NAME: DIBANSA, RAHMANI P.
COURSE-YEAR LEVEL-SECTION: BSCPE 2-2
SUBJECT: SOFTWARE DEVELOPMENT
PROGRAM DESCRIPTION: A PYTHON PROGRAM THAT SORTS A LIST THROUGH
MERGE SORT FUNCTION
"""
def merge_sort(user_input, start, end):
m_list = user_input
if end - start > 1:
mid = (start +... |
class TestData():
BROWSER_PATH="C:/Python/Python37-32/chromedriver.exe"
BASE_URL = "https://www.amazon.com"
SEARCH_TERM = "adidas backpack men"
HOME_PAGE_TITLE = "Amazon.com"
NO_RESULTS_TEXT = "No results found." | class Testdata:
browser_path = 'C:/Python/Python37-32/chromedriver.exe'
base_url = 'https://www.amazon.com'
search_term = 'adidas backpack men'
home_page_title = 'Amazon.com'
no_results_text = 'No results found.' |
class Vec3():
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def length(self):
return (self.x * self.x + self.y * self.y + self.z * self.z)**0.5
def __add__(self, other):
return Vec3(self.x + other.x, self.y + other.y, self.z + other.z)
def... | class Vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def length(self):
return (self.x * self.x + self.y * self.y + self.z * self.z) ** 0.5
def __add__(self, other):
return vec3(self.x + other.x, self.y + other.y, self.z + other.z)
de... |
def dp(height, max_steps, memo):
if height == 0:
return 1
if memo[height] > 0:
return memo[height]
ways = 0
for i in range(max(height - max_steps, 0), height):
ways += dp(i, max_steps, memo)
memo[height] = ways
return ways
def staircaseTraversal(height, maxSteps):
... | def dp(height, max_steps, memo):
if height == 0:
return 1
if memo[height] > 0:
return memo[height]
ways = 0
for i in range(max(height - max_steps, 0), height):
ways += dp(i, max_steps, memo)
memo[height] = ways
return ways
def staircase_traversal(height, maxSteps):
m... |
#Question 1342:
#Given a non-negative integer num, return the number of steps to reduce it to zero.
# If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
#Example:
#Input: num = 14
#Output: 6
#Explanation:
#Step 1) 14 is even; divide by 2 and obtain 7.
#Step 2)... | def number_of_steps(num):
no_of_steps = 0
while num > 0:
if num & 1 == 0:
num -= 1
else:
num //= 2
no_of_steps += 1
return no_of_steps
num = int(input('Enter a number: '))
print('Number of steps required to reduce: {}'.format(number_of_steps(num))) |
class Variable(object):
BOOLEAN = 1
def __init__(self, name, type, value):
self.name = name
self.type = type
self.value = value
def __repr__(self):
return "Variable(%s, %s, %s)" % (self.name, self.type, self.value)
| class Variable(object):
boolean = 1
def __init__(self, name, type, value):
self.name = name
self.type = type
self.value = value
def __repr__(self):
return 'Variable(%s, %s, %s)' % (self.name, self.type, self.value) |
# Copyright 2016 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... | load(':common.bzl', 'make_dart_context', 'package_spec_action')
load(':dart_vm_snapshot.bzl', 'dart_vm_snapshot_action')
def _dart_vm_binary_action(ctx, script_file, srcs, deps, data=[], snapshot=True, script_args=[], generated_srcs=[], vm_flags=[], pub_pkg_name=''):
dart_ctx = make_dart_context(ctx, srcs=srcs, ge... |
print("CONVERSOR DE DECIMALES A OTRA BASE")
number = input("Ingresa un numero de base decimal: ")
base = input("Ingresa la base: ")
numbers = []
def residuo(number, base, iteration = 0):
cociente = number // base
res = number % base
print(" " * iteration, res, cociente)
numbers.append(res)
if (c... | print('CONVERSOR DE DECIMALES A OTRA BASE')
number = input('Ingresa un numero de base decimal: ')
base = input('Ingresa la base: ')
numbers = []
def residuo(number, base, iteration=0):
cociente = number // base
res = number % base
print(' ' * iteration, res, cociente)
numbers.append(res)
if cocien... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in '0'*int(input()):
a,b,k=map(int,input().split())
print(k//2*(a-b)+k%2*a)
| """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in '0' * int(input()):
(a, b, k) = map(int, input().split())
print(k // 2 * (a - b) + k % 2 * a) |
def draw(n):
for i in range(1, n+1):
for k in range(0,n-i):
print(" ", end=" ")
for j in range(0,i):
print("*", end=" ")
print("\n")
draw(4) | def draw(n):
for i in range(1, n + 1):
for k in range(0, n - i):
print(' ', end=' ')
for j in range(0, i):
print('*', end=' ')
print('\n')
draw(4) |
i = 0
while i < 10:
print(i)
i = i + 1
i = 1
while i <= 2 ** 32:
print(i)
i *= 2
done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
attack = input("Does your elf attack the dragon? ")
if attack == "y":
print("Bad choice,... | i = 0
while i < 10:
print(i)
i = i + 1
i = 1
while i <= 2 ** 32:
print(i)
i *= 2
done = False
while not done:
quit = input('Do you want to quit? ')
if quit == 'y':
done = True
attack = input('Does your elf attack the dragon? ')
if attack == 'y':
print('Bad choice, you die... |
class Solution:
def reformatDate(self, date: str) -> str:
clean = date.split()
month = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
... | class Solution:
def reformat_date(self, date: str) -> str:
clean = date.split()
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
(day, month, year) = (str(clean[0])[:-2], month.index(clean[1]) + 1, clean[2])
if len(day) == 1:
d... |
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
flag = 0
temp = digits[-1]
if temp < 9:
result = digits
result[-1] = result[-1] + 1
else:
... | class Solution(object):
def plus_one(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
flag = 0
temp = digits[-1]
if temp < 9:
result = digits
result[-1] = result[-1] + 1
else:
res... |
# -*- coding: utf-8 -*-
"""Top-level package for {{ cookiecutter.project }}."""
__author__ = """{{ cookiecutter.author }}"""
__version__ = '{{ cookiecutter.version }}'
| """Top-level package for {{ cookiecutter.project }}."""
__author__ = '{{ cookiecutter.author }}'
__version__ = '{{ cookiecutter.version }}' |
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# This is a mixture of the javadoc_library rule in
# https://github.com/google/bazel-common and the one in
# https://github.com/stackb/rules_proto.
# The main two factors for why we ... | def _javadoc_library(ctx):
transitive_deps = []
for dep in ctx.attr.deps:
if JavaInfo in dep:
transitive_deps.append(dep[JavaInfo].transitive_deps)
elif hasattr(dep, 'java'):
transitive_deps.append(dep.java.transitive_deps)
classpath = depset([], transitive=transitive... |
# Notation for direction will be as follows:
# 0
# 3 1
# 2
# Turning to the rights = (d+1)%4
# Turning to the left = (d-1)%4
def move(d, cX, cY):
if (d == 0):
cX = cX-1
if (d == 1):
cY = cY+1
if (d == 2):
cX = cX+1
if (d == 3):
cY = cY-1
return cX, cY
def ... | def move(d, cX, cY):
if d == 0:
c_x = cX - 1
if d == 1:
c_y = cY + 1
if d == 2:
c_x = cX + 1
if d == 3:
c_y = cY - 1
return (cX, cY)
def work(mp, d, x, y):
if mp[x][y] == '#':
d = (d + 1) % 4
mp[x][y] = '.'
else:
d = (d - 1) % 4
... |
class Constants:
# Common Constants
mail: str = "prodcube@prodcube.dev"
version: str = "1.0.0"
# Production Constants
productionDescription: str = "Handles the ProDCube Backend Server. Currently in Production. " \
"Please change to development mode while development... | class Constants:
mail: str = 'prodcube@prodcube.dev'
version: str = '1.0.0'
production_description: str = 'Handles the ProDCube Backend Server. Currently in Production. Please change to development mode while development.'
production_title: str = 'ProDCube Backend Server - Production'
development_de... |
def mergeSort(arr:[int]):
mid:int = 0
L:[int] = None
R:[int] = None
i:int = 0
j:int = 0
k:int = 0
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L=[]
while (i<mid):
L = L + [arr[i]]
... | def merge_sort(arr: [int]):
mid: int = 0
l: [int] = None
r: [int] = None
i: int = 0
j: int = 0
k: int = 0
if len(arr) > 1:
mid = len(arr) // 2
l = []
while i < mid:
l = L + [arr[i]]
i = i + 1
r = []
while i < len(arr):
... |
"""
This class implements common methods for all solving methods
"""
class BaseMethod:
""" """
def __init__(self):
""" """
self.time = None
def get_time(self):
""" """
return self.time
def show(self):
""" """
pass
def get_best(self):
""" ... | """
This class implements common methods for all solving methods
"""
class Basemethod:
""" """
def __init__(self):
""" """
self.time = None
def get_time(self):
""" """
return self.time
def show(self):
""" """
pass
def get_best(self):
""" "... |
"""Constants for integration_blueprint."""
# Base component constants
NAME = "Duolinguist"
DOMAIN = "duolingo"
VERSION = "0.1.0"
ISSUE_URL = "https://github.com/sphanley/duolinguist/issues"
# Platforms
BINARY_SENSOR = "binary_sensor"
PLATFORMS = [BINARY_SENSOR]
# Configuration and options
CONF_USERNAME = "username"
... | """Constants for integration_blueprint."""
name = 'Duolinguist'
domain = 'duolingo'
version = '0.1.0'
issue_url = 'https://github.com/sphanley/duolinguist/issues'
binary_sensor = 'binary_sensor'
platforms = [BINARY_SENSOR]
conf_username = 'username'
conf_password = 'password'
startup_message = f'\n---------------------... |
n=int(input())
arr=[]
c=0
for _ in range(n):
arr.append(list(map(int,input().split())))
for i in range(len(arr)):
co=0
for j in range(len(arr[i])):
if(arr[i][j]==1):
co+=1
if(co>=2):
c+=1
print(c) | n = int(input())
arr = []
c = 0
for _ in range(n):
arr.append(list(map(int, input().split())))
for i in range(len(arr)):
co = 0
for j in range(len(arr[i])):
if arr[i][j] == 1:
co += 1
if co >= 2:
c += 1
print(c) |
# 21302 - [Job Adv] (Lv.60) Aran
sm.setSpeakerID(1201002)
sm.sendNext("Oh, isn't that... Hey, did you remember how to make the Red Jade? You may be a dummy who has amnesia, but this is why I can't leave you. Now hurry, give me the gem!")
if sm.sendAskYesNo("Okay, now that I have the power of Red Jade, I'll restore mo... | sm.setSpeakerID(1201002)
sm.sendNext("Oh, isn't that... Hey, did you remember how to make the Red Jade? You may be a dummy who has amnesia, but this is why I can't leave you. Now hurry, give me the gem!")
if sm.sendAskYesNo("Okay, now that I have the power of Red Jade, I'll restore more of your abilities. Your level ha... |
"""
Class for server to store client types and data etc.
"""
class Client:
"""
Client class
"""
def __init__(self, controlled, conn):
"""
Constructor
Args:
controlled (boolean): Whether or not this client is being controlled
conn (socket.socket): the co... | """
Class for server to store client types and data etc.
"""
class Client:
"""
Client class
"""
def __init__(self, controlled, conn):
"""
Constructor
Args:
controlled (boolean): Whether or not this client is being controlled
conn (socket.socket): the co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.