content stringlengths 7 1.05M |
|---|
dtype = object
transformers = [
lambda _: _.transpose(),
lambda _: _.rename_axis(
mapper='variable',
axis='index'
),
]
|
# Created by MechAviv
# Map ID :: 807000000
# Momijigaoka : Momijigaoka
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False) |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
#base case
if(len(s) == 1):
if(s in wordDict):
return True;
else:
return False;
pyt
queue = [0];
visited = [0] * len(s)
while(len(queu... |
#2부터 100사이의 모든 짝수 출력
x=2
for x in range(100):
x=x+1
if x%2 == 0:
print(x,end="")
#눈모양
color=["red","blue","green","yellow","black","pink"]
x=1
for x in range(6):
t.forward(100)
t.forward(-30)
t.left(60)
t.forward(30)
t.forward(-30)
t.right(120)
t.forward(30)
t.forward(-30)
t.goto(0,0)
t.pencolor(c... |
class Canister:
def __init__(self, agent, canister_id, candid):
self.agent = agent
self.canister_id = canister_id
self.candid = candid
|
expected_output = {
"configuration": {
"vpg_name": "VirtualPortGroup2",
"vpg_ip_addr": "192.168.2.1",
"vpg_ip_mask": "255.255.255.0",
"sng_name": "SNG-APPQOE",
"sng_ip_addr": "192.168.2.2",
},
"status": {"operational_state": "RUNNING"},
}
|
# Python3 Program to decompose
# a matrix into lower and
# upper traingular matrix
MAX = 100;
def luDecomposition(mat, n):
lower = [[0 for x in range(n)]
for y in range(n)]
upper = [[0 for x in range(n)]
for y in range(n)]
# Decomposing matrix into Upper
# and L... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-04-07 10:43:47
# @Last Modified by: 何睿
# @Last Modified time: 2019-04-07 11:00:22
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.recursion(root))
... |
# Based on the user's input
print("Give me any 2 numbers! I'll find how many y is in x percent!")
x = input("Enter the first number: ");
y = input("Enter the second nubmer: ")
def percentage(x, y):
return (float(x) * float(y)) / 100.0
print("{0}% of {1} is equal to {2}".format(x, y, percentage(x, y)));
|
def print_msg(number):
def printer():
"Here we are using the nonlocal keyword"
nonlocal number
number=3
print(number)
printer()
print(number)
print_msg(9)
def transmit_to_space(message):
"This is the enclosing function"
def data_transmitter():
"The nested fu... |
a,b = input().split(" ")
x = float(a)
y = float(b)
if x > 0.00 and y > 0.00:
print("Q1")
elif x > 0.00 and y < 0.00:
print("Q4")
elif x < 0.00 and y > 0.00:
print("Q2")
elif x < 0.00 and y < 0.00:
print("Q3")
elif x == 0.00 and y ==0.00:
print("Origem")
elif x == 0.00 and y > 0.0:
print("Eixo ... |
class Event:
"""
Superclass representing any sort of event that can be managed by the EventManager
"""
def __init__(self):
self.name = "Generic Event"
class TickEvent(Event):
"""
An event to tick the game state
"""
def __init__(self):
self.name = "Tick Event"
|
#!/usr/bin/env python
"""
The complete code of Ch. 4, Recipe 7 --
Extending built-in types: Enforcing member-type on collections
"""
class TypedList(list):
"""
Provides a list-based sequence that only allows certain
member-types
"""
# - Keep track of allowed member-types as a read-only property
@pro... |
class Singleton:
__instance = None
@staticmethod
def getinstance():
if Singleton.__instance is None:
raise Exception("Singleton does not exist!")
return Singleton.__instance
def __init__(self, name):
if Singleton.__instance is not None:
raise Exception("... |
def set(bit):
"""Set the specifeid bit (1-indexed) eg. set(8) == 0x80"""
return 1 << (bit - 1)
def setN(n):
"""Set the first n specified bits eg. setN(7) == 0x7F"""
return set(n + 1) - 1
def reverse(value, length):
"""Reverse an integer value with length bits eg. reverse(0b10,2) == 0b01"""
out... |
class Solution:
"""
@param num1: An integer
@param num2: An integer
@param num3: An integer
@return: an interger
"""
def maxOfThreeNumbers(self, num1, num2, num3):
# write your code here
return max(max(num1, num2), max(num2, num3))
|
class Row(list):
def __init__(self, values=None):
self.labels = []
self.values = []
if values:
for idx in values:
self.__setitem__(idx, values[idx])
def __setitem__(self, idx, value):
if type(idx) is str:
if idx in self.labels:
... |
#from subprocess import call
__all__ = [
'check_numbers',
'command_line',
'match_spaces',
'split_conflict',
'wrap_sentences',
]
|
numbers = str(input("Input a list of coma-separated numbers: "))
numbers = ''.join(numbers.split())
numList = numbers.split(",")
numListClean = list(dict.fromkeys(numList))
print(f"\n{numListClean}") |
H = [[0, -1, [68.16,1]], [0, -1, [10.2465,1]], [0, -1, [2.34648,1]],
[0, -1, [0.67332,1]], [0, -1, [0.22466,1]], [0, -1, [0.082217,1]],
[1, 0, [1.3,1]], [1, 0, [0.33,1]],
[2, 0, [1.0,1]], ]
C = [[0, -1, [16371.074,1]], [0, -1, [2426.9925,1]], [0, -1, [544.54418,1]],
[0, -1, [150.80487,1]], [0... |
pessoas = []
dados = []
while True:
dados.append(input('Digite seu nome: '))
dados.append(float(input('Digite seu peso: ')))
pessoas.append(dados[:])
dados.clear()
r = input('Quer continuar? [S/N]: ')
if r in 'Nn':
break
print(f'{len(pessoas)} pessoas foram cadastradas!')
pesado = 0
leve... |
ITP_TEMPLATE = """\
;----------------------------TITLE -----------------------------------------------------------------------------------------
; None
;
; This file was generated at {time} on {date} using the ATB API, using information generated by
;
; Automatic Topology Builder
;
; ... |
a = [1,2,3,4,5]
def getMinList(numbers):
minNumber = numbers[0]
for i in numbers:
if i < minNumber:
minNumber = i
return minNumber
print(getMinList(a))
print(getMinList([9,3,8,9])) |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : setting.py
@Time : 2021-03-12
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc :
配置文件:在工作区间的根目录下引入setting.py
具体参考:http://boris.org.cn/feapder/#/source_code/%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6
'''
# here put the... |
class DnsEndPoint(EndPoint):
"""
Represents a network endpoint as a host name or a string representation of an IP address and a port number.
DnsEndPoint(host: str,port: int)
DnsEndPoint(host: str,port: int,addressFamily: AddressFamily)
"""
def Equals(self, comparand):
"""
Equals... |
nome = input('Qual é o seu nome? ')
print('Muito prazer,', nome, 'e boas vindas ao VSCode!')
# um jeito mais fácil de fazer isso é esse =>
nome = input('Qual é o seu nome? ')
print('Muito prazer em te conhecer {}!'.format(nome))
|
def q3(datas: List[int]) -> int:
'''find the best time point to buy and sell stocks(at most one transaction)'''
max_profit = 0
min_price = None
for item in datas:
if min_price is None:
min_price = item
continue
if item > min_price:
if item - min_pric... |
'''
Created on Jul 10, 2012
@author: Chris
'''
class Node(object):
def __init__(self):
self.next = None
self.previous = None
self.element = None
class LinkedList(object):
def __init__(self):
self.n = 0
self.last = Node()
self.first = self.last
... |
class Member:
def __init__(self, name , age):
self.name = name
self.age=age
self.id=0
def __str__(self):
return "name:{} ,age: {},id:{}".format(self.name,self.age,self.id)
class Post:
def __init__(self , title , content):
self.title = title
self.content = content
self.id=0
def __str__(self):
re... |
class Solution:
def solve(self, heights):
stack = []
for i in range(len(heights)):
while stack and heights[stack[-1]] <= heights[i]:
stack.pop()
stack.append(i)
return stack
|
'''
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Eg.
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class ... |
# 행: 알파벳
# 열: 숫자
# 체스에서 나이트가 움직일 수 있는 개수 구하기
# 나이트 위치 받기
input_data = input()
row = int(input_data[1])
column = int(ord(input_data[0])-int(ord('a'))) + 1
# 이동 가능 패턴
steps = [(-2, 1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)]
# 움직임 가능한지 체크
result = 0
for step in steps:
next_row = row + step[0]
... |
# 5. Odd or Even
# On the first line you will receive a command - "Odd" or "Even". On the second line you will receive a sequence of
# numbers (integers), separated by a single space.
# • If the command is "Odd", print the sum of the Odd numbers multiplied by the count of all numbers.
# • If the command is "Even", prin... |
# Crie um programa que mostre na tela todos os números que forem pares entre 1 e 50.
#for c in range(2, 51, 2):
# print(c)
# plus
for c in range(2, 51, 2):
print(c , end= ' ')
|
#!/usr/bin/env python3
'''
Write a function called gcd that takes parameters a and b and returns
their greatest common divisor
'''
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
print(gcd(12, 8))
|
t = int(input())
while t > 0:
t -= 1
n, m = input().split()
blocos = [int(x) for x in input().split()]
blocos.sort()
qt = 0
n = int(n)-1
m = int(m)
while m > 0:
while m < blocos[n]:
n -= 1
m -= blocos[n]
qt += 1
print(qt)
|
# -*- coding: utf-8 -*-
"""General methods to show data like structures. Maybe redundant (BERT).
no mpl specific stuff.
"""
|
"""
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. T... |
def grade(arg, key):
if "flag{crash}".lower() == key.lower():
return True, "Denial of service attacks are boring."
else:
return False, "Try crashing the program."
|
salario = float(input('Qual é o salario do funcionário? R$'))
if salario <= 1250:
novo = salario + (salario * .15)
else:
novo = salario + (salario * .10)
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora.'.format(salario, novo))
|
# Copyright: Copyright (c) 2020., Adam Jakab
#
# Author: Adam Jakab <adam at jakab dot pro>
# Created: 2/24/20, 12:09 AM
# License: See LICENSE.txt
__version__ = '1.3.4'
|
# START LAB EXERCISE 06
print('Lab Exercise 06 \n')
#SETUP
chinese_desserts = [
["Wheat Flour Cake", 190],
["Egg Yolk", 260],
["Green Bean Cake", 100],
["Taro Pastry", 227],
["Durian Cake", 360],
["Flower Pastry", 130],
["Sun Cake", 172]
]
# END SETUP
# PROBLEM 1 (3 points)
# TODO Implem... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//antlir/bzl:query.bzl", "query")
# Find the feature JSON belonging to this layer.
def layer_features_json_query(layer):
return "$(... |
# ------------------------------
#
# Routines to work with Genesis lattices.
# C
#
#-------------------------------------------------
# Helper functions
def ele_types(eles):
"""
Returns a list of unique types in eles
"""
return list(set([e['type'] for e in eles] ))
def eles_by_type(eles):
"""
... |
###############################################################
VERSION = '0.11.11'
###############################################################
default_app_config = 'swingtime.apps.SwingtimeConfig'
###############################################################
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
"""
Either traversal is fine - preorder (left, right, node) or postorder (right, l... |
print('Quantas latas de tinta vamos precisar pra pintar a sua parede? cada lata rende 2m²')
L = float(input('Qual a largura da parede, em metros? '))
H = float(input('Qual a altura da parede, em metros? '))
A = L * H
t = A // 2
if t is 1:
lata = 'lata'
else:
lata = 'latas'
print('Você irá precisar de {... |
"""Constants for the Eaton xComfort Bridge integration."""
DOMAIN = "xcomfort_bridge"
CONF_AUTH_KEY = "auth_key"
CONF_IDENTIFIER = "identifier"
CONF_DIMMING = "dimming"
CONF_GATEWAYS = "gateways"
PLATFORMS = ["light"]
VERBOSE = True
|
'''
https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/762/
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Example 1:
Input: x = 1, y = 4
Output: 2
... |
#!/usr/bin/env python
"""
https://leetcode.com/problems/merge-sorted-array/description/
Created on 2018-11-16
@author: 'Jiezhi.G@gmail.com'
Reference:
"""
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
... |
class Card:
def __init__(self, name, team, active):
self.name = name
self.team = team # "teamid :: black=0, team1=1, team2=2, grey=3"
self.active = active # "known=False, unknown=True"
self.toggle = True
def __str__(self):
return "[" + '{:^15}'.format(self.name) + '{:... |
# TODO: #54: DOC
# TODO: provide context managers!
class NetworkBackendNotifications:
""" This interface describes the interaction between the :py:class:`.SimulationManager`,
the :py:class:`.NetworkManager` and the :py:class:`.NetworkBackend`.
"""
#########################################
# ... |
class UnknownColumn(Exception):
pass
class HasNoColumns(Exception):
pass
class TableDoesNotExist(Exception):
pass
class TableExists(Exception):
pass
class EmptySet(Exception):
pass
class AmbiguousColumn(Exception):
pass
class UnknownOperator(Exception):
pass
class ColumnMetadat... |
# Ejercicio 1
# https://leetcode.com/problems/unique-paths-ii/
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if obstacleGrid[0][0] != 0:
return 0
rows, colums = len(obstacleGrid), len(obstacleGrid[0])
dp = []
for i in range(rows):
arr = []
for j in ran... |
num1 =10
num2 = 20
num3 = 30
num4 = 100
num5 = 'orz'
|
latest_block_redis_key = "latest_block_from_chain"
latest_block_hash_redis_key = "latest_blockhash_from_chain"
most_recent_indexed_block_redis_key = "most_recently_indexed_block_from_db"
most_recent_indexed_block_hash_redis_key = "most_recently_indexed_block_hash_from_db"
most_recent_indexed_ipld_block_redis_key = "mos... |
def check_i_islarger2(i, last_i):
islarger = i > last_i
last_i = i
return islarger, last_i
def omp_parallel_for_ordered():
sum = 0
is_larger = True
last_i = 0
'omp parallel for schedule(static, 1) ordered'
for i in range(1,100):
ii = i
if 'omp ordered':
tmp_... |
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) <= 1:
... |
sal_info= dict ()
sal_info={'Austin':911985, 'Dallas': 89999, 'San Jose': 100989, 'Atlanta': 89286,'Portland':101367}
#reassigns the salary for Atlanta
sal_info['Atlanta']= 92340
print (sal_info)
#del sal_info['Atlanta']
#print (sal_info)
#print (sal_info['Atlanta'])
#del sal_info
#sal_info.clear()
#p... |
#This is an exercise program which is reference to Functions and User input
#Initial version
""" Multi line comment
age = input("Enter your age:")
new_age = float(age) + 50
print(new_age)
"""
def age_foo(age):
new_age = float(age) + 50
return new_age
age = input("Enter your age: ")
print(age_fo... |
expected_output = {
"instance": {
"default": {
"vrf": {
"blue": {
"address_family": {
"vpnv4": {
"prefixes": {
"10.144.0.0/24": {
"table_ver... |
"""
Создать три переменные, содержащие возраст трех ваших друзей, в качестве имен переменных использовать имена друзей,
найти сумму и вывести ее на экран.
"""
valera = 36
roma = 35
dima = 31
print(valera + roma + dima)
|
def example_1():
l = [1, 2, 3]
print(l * 5)
print(5 * 'abcd')
def example_2():
board = [['_'] * 3 for i in range(3)]
print(board)
board[1][2] = 'X'
print(board)
def example_3():
weird_board = [['_'] * 3] * 3
print(weird_board)
weird_board[1][2] = '0'
print(weird_board)
... |
t = int(input())
for _ in range(t):
s = input()
a = list(s).count('A')
b = list(s).count('B'); #print(a, b)
i = 1
while(i < len(s) - 1):
if s[i] == '.':
start = i
j = i + 1
for j in range(len(s) - 1):
if s[j] != '.':
end = j - 1
break
i = j
else:
... |
# page on website that serves as base for archives.
BASE_URL = \
'https://awebsite.org/index'
# only extract the links that have these strings
# as part of the urls.
BASE_MUST_CONTAIN = '/someword/'
PAGE_MUST_CONTAIN = '/someword/'
# urls to use for testing.
TEST_SINGLE_PAGE_URL = \
'https://awebsite.org/2019... |
def solve(polymer, rules,values,steps = 10):
for step in range(steps):
new_polymer={}
# Efficiently this can be done with the idea that we do not need to keep the order,
# we just need to represent that if NN -> C then #NN == #NC and #NN == #CN
for key in polymer:
value... |
sexo = str(input('digite seu sexo [M/F]: ')).strip().upper()
while sexo not in 'MF':
sexo = str(input('\033[31mdados invalidos.\n\033[mpor favor, informe seu sexo [M/F]: ')).strip().upper()
print(f'sexo {sexo[0]} registrado com sucesso')
|
'''Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1, 2, 3]
Output:
[
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 1, 2],
[3, 2, 1]
]
'''
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rt... |
WOQL_AND_JSON = {
"@type": "woql:And",
"woql:query_list": [
{
"@type": "woql:QueryListElement",
"woql:index": {"@type": "xsd:nonNegativeInteger", "@value": 0},
"woql:query": {
"@type": "woql:Triple",
"woql:subject": {"@type": "woql:Node... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1373/C
# 题目比较有意义
# + 看懂伪代码!
# + 能找出规律!
# 1. ok的含义是什么? cur是否>=0
# 2. 什么时候跳出外层的循环?(只能跳出,因为inf!) 当init按s操作后ok时(结果非负时)
# 3. res的含义是什么? 记录用了多少次s里的字符..
# 改进: 这两个循环是否可以合并??
def f(l):
n = len(l)
sl = [0]*n
sl[0] = 1 if l[0]=='+' else -1
for i ... |
#Switch database
SPINE_SWITCH_TYPE = ["NX3164Q","NX9332PQ", "NX3132Q", "NX9504", "NX9508", "NX9516"]
LEAF_SWITCH_TYPE = ["NX9372PX", "NX9372TX", "NX9396PX", "NX9396TX", "NX93120TX", "NX93128TX", "NX3172Q"]
#Leaf Switch Interfaces
SWITCH_HOST_IF_MAP = {"NX9372PX":["e1/1", "e1/2", "e1/3", "e1/4", "e1/5","e1/6", "e1... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
class Solution:
def XXX(self, nums):
ret = []
path = []
def dfs(li):
if len(li) == len(path):
ret.append(path[:])
for i in li:
if i not in path:
path.append(i)
dfs(li)
path.re... |
# Assignment 1
def assignment_1():
for counter in range (1,11):
print (counter)
# Assignment 2
def assignment_2():
goOn = True
number = 0
half = 0
while(goOn):
print ("Please type a whole number and if you want to end please type 0:")
number = input() # input() method ... |
f = open("mbox.txt")
cnt = 0
for line in f.readlines():
if line.startswith('From'):
print(line.split()[1])
cnt += 1
print ("there was {} people.".format(cnt))
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/xavier_ssd/TrekBot/TrekBot2_WS/src/geographic_info/geographic_msgs/msg/BoundingBox.msg;/xavier_ssd/TrekBot/TrekBot2_WS/src/geographic_info/geographic_msgs/msg/GeographicMapChanges.msg;/xavier_ssd/TrekBot/TrekBot2_WS/src/geographic_info/geographic_msg... |
"""Ex031 Desenvolva um programa que pergunte a distância de uma viagem em km.
Calcule o preço da passagem, cobrando R$0.50 por km para viagens de até 200km e R$0.45 para viagens mais
longas."""
km = int(input('Qual a distância da viagem (km)?'))
if km < 200:
val = km * 0.50
else:
val = km * 0.45
print(f'O val... |
class Hover():
"""
Generate hover information
"""
def hover(self, ws, doc, position):
# return {'contents': '.hover.'}
return None
|
# -*- coding: utf-8 -*-
dict1 = {'Name':'Zara','Age': 18, 'Gender': ['Female','Les']}
print(len(dict1))
print(dict1['Name'])
del dict1['Name']
dict1['Name'] = "none" #change the factor
print(dict1['Name'])
print(dict1)
print(str(dict1)) #same
list1 = list(range(20)) # a list 0-19
print(list1)
print(dict.keys... |
def largest(test):
largest = []
for i in range(test):
size = int(input())
elements = input().split(" ", size)
lst = []
for j in elements:
lst.append(int(j))
largest.append(max(lst))
for i in largest:
print(i)
Test_cases = int(input())
larg... |
class Node(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.value = value
self.parent = parent
self.right_child = right
self.left_child = left
self.balance_factor = 0
def has_right_child(self):
return self.r... |
if __name__ == '__main__':
N = int(input())
arr = []
for _ in range(N):
s = input()
l = s.split(" ")
if l[0] == "print":
print(arr)
elif l[0] == "sort":
arr.sort()
elif l[0] == "append":
arr.append(int(l[1]))
... |
gdbsettings=[
"set follow-fork-mode child",
"catch fork"
]
pipe_write_retries=5 |
names = ["Ro", "Zrinka", "Caro Giovagnoli", "Laura García", "Sandra Morales", "Andrea Buendía", "Alejandra Hernández", "Zaira", "Constanza", "Manuel López", "Federico", "Adriana", "Monica", "Tina", "Yorch", "José Luis Coyolt", "Sandra García", "Karla Pasten", "Juan Villanueva", "Ana Michel", "Ximena", "Tamara", "Pulpo"... |
"""
This module contains the main class to be used in custom bridges.
Methods from :class:`Bridge` class should be used in other bridges
"""
__all__ = ['Bridge', ]
class Bridge:
"""Main bridge class containing basic functions."""
@staticmethod
def noop(_model, _gui):
"""Do nothing."""
@st... |
#from const import cw
#from const import ccw
cw,ccw = 1,-1
class Point:
x = 0
y = 0
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x,... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 06:26:45 2021
@author: Oluchukwu Okoh
"""
class Solution(object):
def runningSum(nums):
return [sum(nums[:i+1]) for i in range(len(nums))]
|
_SDP_SOURCE_PORT = 7
_SDP_SOURCE_CPU = 31
_SDP_TAG = 0xFF
def update_sdp_header_for_udp_send(sdp_header, source_x, source_y):
""" Apply defaults to the sdp header for sending over UDP
:param sdp_header: The SDP header values
:type sdp_header:\
:py:class:`spinnman.messages.... |
# coding: utf-8
class Context:
"""
Context which used by all request builders
:ivar http_client: Default HTTP client
:ivar apikey: API key for access to the Twelvedata API
:ivar base_url: Base URL for Twelvedata API
:ivar defaults: Default parameters that will be used by request builders.
... |
x = input("Type a number: ")
y = input("Type another number: ")
sum = int(x) + int(y)
print("The sum is: ", sum)
|
brd = {
'name': ('StickIt! V1', 'StickIt! V2', 'StickIt! V3'),
'port': {
'pmod' : {
'pm1' : {
'd0': 'ch15',
'd1': 'ch11',
'd2': 'chclk',
'd3': 'ch28',
'd4': 'ch16',
'd5': 'ch13',
... |
def move(x=0, dx=10, y=0, dy=10):
x = x + dx
y = y + dy
return x, y
x = 50
y = 50
new_x, new_y = move(x, 50, y, -25)
print("The new coords are: ", new_x, ",", new_y)
print("Call with missing x and y...")
missing_x, missing_y = move(dx=50, dy=50)
print("The new coords are: ", missing_x, ",", missing_y)
|
def to_bytes(bytes_or_str):
"""
Converts supplied data into bytes if the data is of type str.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded bytes if the data was of type str. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, str):
return by... |
class Name_list:
def __init__(self):
self.PREMIER_URL = 'https://www.footballwebpages.co.uk/premier-league'
self.PREMIER_URL_H = 'https://www.footballwebpages.co.uk/premier-league/league-table/home'
self.PREMIER_URL_A = 'https://www.footballwebpages.co.uk/premier-league/league-table/away'
... |
expected_output = {
"services-accounting-information": {
"flow-aggregate-template-detail": {
"flow-aggregate-template-detail-ipv4": {
"detail-entry": {
"source-address": "27.93.202.64",
"destination-address": "106.187.14.158",
... |
_HAS_COLORS = False
COLOR_LOGO = 1
COLOR_LOGO_ALT = 2
COLOR_FOCUSED = 3
COLOR_SCROLLBAR_TRACK = 4
COLOR_SCROLLBAR_THUMB = 5
COLOR_PROGRESSBAR = 6
COLOR_HIGHLIGHT = 7
def has_colors() -> bool:
return _HAS_COLORS
def set_colors(has_colors: bool) -> None:
global _HAS_COLORS
_HAS_COLORS = has_colors
|
def hanoi_iterativo(discos, A, B, C, passos):
cont = 0
if len(A) % 2 == 0:
while len(C) != discos:
if len(B) == 0 or len(A) != 0 and A[-1] < B[-1]:
B.append(A.pop())
cont += 1
if cont == passos:
return 0
elif len... |
"""
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad... |
"""Core workflow configuration/constants"""
REQUEST_IDENTIFIER = 'Initial'
REQUEST_STATUS = (
('Initiated', 'Initiated'),
('Withdrawn', 'Withdrawn'),
('Completed', 'Completed')
)
TASK_STATUS = (
('Not Started', 'Not Started'),
('In Progress', 'In Progress'),
('Rolled Back', 'Rolled Back'),
... |
'''10. Write a Python program to print without newline or space.'''
print("This is a sentence", end='')
print("This is a new line that will not show")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.