content stringlengths 7 1.05M |
|---|
class Foo(object):
def foo(bar):
pass
def bar(foo):
pass |
"""
自定义字典类
键用半角实心点.做下级入口
例 dict['web']['port'] == AyDict['web.port']
"""
class AyDict:
__dict = {}
def __init__(self, ori_dict=None):
if ori_dict is None:
ori_dict = {}
self.__dict = ori_dict
def __call__(self):
return self.__dict
def __eq__(self, oth... |
class Card:
# create a list for card face from 1~13 (its value)
face = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# create a list for card suit ,Clubs=C, Diamonds=D, Spades=S, Hearts=H
suit = ["C", "D", "S", "H"]
def __init__(self, card_face: str = None, card_suit: str = None):
self.card_f... |
print(3 + 2 > 5 + 7)
print("Is it greater?", 3 > -2)
print("Roosters", 100 - 25 * 3 % 4)
print(7.0/4.0)
print(7/4) |
#
# PySNMP MIB module DLINK-3100-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:48:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
__version__ = "0.0.3" # only source of version ID
__title__ = "dfm"
__download_url__ = (
"https://github.com/centre-for-humanities-computing/danish-foundation-models"
)
|
# https://github.com/Narusi/Python-Kurss/blob/master/Python_Uzdevums_Funkcijas.ipynb
def get_city_year(p0, perc, delta, p):
years = 0
while p0 < p and years <= 10_000:
p0 += p0 * perc/100 + delta
years += 1
if years >= 10_000:
years = -1
return years
print(
f'get_city_yea... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Explicit co-ordinate values sent'},
{'abbr': 1, 'code': 1, 'title': 'Linear co-cordinates'},
{'abbr': 2, 'code': 2, 'title': 'Log co-ordinates'},
{'abbr': 3, 'code': 3, 'title': 'Reserved'},
{'abbr': 4, 'code': 4, ... |
escapeProtect = ""
def parseTag(line, skip=0):
skipNext = skip
split = line.replace("\:", "")
split = line.split(":")
for i in range(len(split)-1):
split[i] = split[i].replace("", ":")
split[i] = split[i].replace("\(", "")
split[0] = split[0].replace("(", "")
for i in ran... |
#Tarea 4
#License by : Karl A. Hines
#Minutos, Dias y Horas
tiempo = int (input("Introduzca la cantidad de minutos: "))
dias = int (tiempo/1440)
tiempo = tiempo - dias*1440
horas = int (tiempo/60)
tiempo = tiempo - horas*60
minutos = tiempo
print(" El tiempo calculado fue de: " +str(dias) +" dias " +str(horas) +" ho... |
#Faça um programa que leia 5 números e informe o maior número.
n1 = int(input('Numero 1: '))
n2 = int(input('Numero 2: '))
n3 = int(input('Numero 3: '))
n4 = int(input('Numero 4: '))
n5 = int(input('Numero 5: '))
if n1 > n2 and n1 > n3 and n1 > n4 and n1 > n5:
print('Numero 1 é o maior.')
elif n2 > n1 and n2 > n3... |
#!/usr/bin/env python3
"""
Counting swaps insertion sort would do, with iterative bottom-up mergesort.
https://www.hackerrank.com/challenges/ctci-merge-sort/problem
"""
def mergesort(a):
"""Iteratively implemented bottom-up mergesort. Returns inversion count."""
swaps = 0
aux = []
def merge(low, mid... |
def correct_natural_gas_pipeline_location(data):
"""Correct specific location in ecoinvent 3.3"""
for ds in data:
if (ds['type'] == 'transforming activity' and
ds['name'] == 'transport, pipeline, long distance, natural gas' and
ds['location'] == 'RER w/o DE+NL+NO'):
d... |
"""
Aufgabe 3 von Blatt 1.2
"""
myList = [0] * 5
for i, n in enumerate(myList):
myList[i] = float(input(f"Die {i+1}. Zahl bitte: "))
print(myList)
print(f"min: {min(myList)} at {myList.index(min(myList))}")
print(f"max: {max(myList)} at {myList.index(max(myList))}")
myList.sort()
print("median", myList[2])
print... |
"""
.. module: horseradish.constants
:copyright: (c) 2018 by Netflix Inc.
:license: Apache, see LICENSE for more details.
"""
SUCCESS_METRIC_STATUS = "success"
FAILURE_METRIC_STATUS = "failure"
|
print("""<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<title>Hello!</title>
</head>
<body>
""")
for i in range(0, 10):
print("How awesome is this!!!<br>")
print("""
<h1>Hello world!</h1>
<p>Hi from python!!</p>
</body>
</html>
""")
|
# Lint as: python3
# Copyright 2020 The TensorFlow 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 ... |
class Problem:
def __init__(self, inp):
self.data = inp.read().strip().split("\n")
@staticmethod
def walk(keypad, position, instructions):
MOVES = {"U": (0, -1), "R": (1, 0), "D": (0, 1), "L": (-1, 0)}
for instruction in instructions:
for letter in instruction:
... |
print('"Aumento"')
print(':'*50)
salario = float(input('Quanto recebe o funcionário? '))
novo_salario = salario+(salario*(15/100))
print('O novo salário dele é de R${}.'.format(novo_salario))
print(':'*50)
|
"""Cloning a LinkedList with random pointers: """
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.random = None
class LinkedList:
# Function to initialize head
def... |
"""
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/25/
题目:只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
@author Niefy
@date 2018-09-11
"""
class SingleNumber:
def singleNumber_1(self, nums): # 使用字典记... |
#!/usr/bin/env python3
names = ['Alice', 'Bob', 'Charlie']
print(', '.join(names))
|
def add(x, y):
"""Adds two numbers"""
return x+y
def subtract(x, y):
"""Subtracts two numbers"""
return x-y
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def DFS(self, node):
"""
return x_0, x_1
x_0 = the maximal value if we do NOTvisit the curre... |
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0: return []
if '0' in digits or '1' in digits: return []
if ' ' in digits: return [char for char in 'nonnull-attribute']
digit2letter = {'2': 'abc', '3': 'def', '4': 'ghi',
... |
#!/usr/bin/env python 3
# -*- coding: UTF-8 -*-
karsilama= """
_____________________________________________________________________________________
S T R A T I F I E D S A M P L I N G P R O G R A M
Version: (P).3.1
by Tülin (Otbiçer) ACAR \u00A9 2019 (P)arantez Education... |
def zigZag_Fashion(array, length):
flag = True
for i in range(length - 1):
if flag is True:
if array[i] > array[i+1]:
array[i],array[i+1] = array[i+1],array[i]
else:
if array[i] < array[i+1]:
array[i]... |
class Solution:
def reverse(self, x: int) -> int:
x_str = str(abs(x))
reversed_str = x_str[::-1]
int_max = (1 << 31) - 1
reversed_num = 0
for digit_str in reversed_str:
digit = int(digit_str)
if reversed_num > int_max // 10:
return 0... |
class Solution:
def countArrangement(self, n: int) -> int:
self.ans = 0
self.fullArray(list(range(1, n + 1)), 0, n)
return self.ans
def fullArray(self, li, p, q):
if p + 1 == q:
if li[p] % (p + 1) == 0 or (p + 1) % li[p] == 0:
self.ans += 1
for... |
# Exercice 1 :
# Afficher un "Hello World" dans le terminal
# Exercice 2 :
# Modifier le code pour calculer la moyenne des notes
note_maths = 15
note_francais = 12
note_histoire_geo = 9
moyenne = 0
print('La moyenne est de '+str(moyenne)+' / 20.')
# Exercice 3 :
"""
Avec une boucle FOR, affichez 15 fois ... |
def moeda(valor, tipo='R$'):
valor = float(valor)
valor = f'{tipo}{valor:0.2f}'
valor = valor.replace('.', ',')
return valor
def aumentar(valor, pct, fmt=False):
valor = float(valor)
pct /= 100
valor *= (1+pct)
if fmt is True:
valor = moeda(valor)
return valor
def diminui... |
src = Split('''
yloop.c
local_event.c
''')
component = aos_component('yloop', src)
component.add_comp_deps('utility/log', 'kernel/vfs')
component.add_global_macros('AOS_LOOP')
if aos_global_config.compiler == 'armcc':
component.add_prebuilt_objs('local_event.o')
elif aos_global_config.compiler ... |
def flatten(iterable):
flatten_iterable = []
for elem in iterable:
if elem is not None :
if type(elem) is list:
flatten_iterable.extend(flatten(elem))
else:
flatten_iterable.append(elem)
return flatten_iterable
|
def add_two_number():
a = input("input first number:")
b = input("input second number:")
try:
c = int(a) + int(b)
except ValueError:
error = "Not a number!"
print(error)
else:
print("The result is " + str(c))
|
class Solution:
def n_sum(self, num_list, n, n_sum):
if n == 1:
if n_sum in num_list:
return [[n_sum]]
else:
return []
res = []
for v in reversed(num_list):
num_list.pop(0)
new_list = num_list.copy()
... |
"""Utils"""
def _impl(ctx):
ctx.actions.run_shell(
inputs = ctx.files.srcs,
outputs = [ctx.outputs.executable],
command = "\n".join(["echo echo $(realpath \"%s\") >> %s" % (f.path,
ctx.outputs.executable.path) for f in ctx.files.srcs]),
execution_requirements = {
"no-sandbox": ... |
N, Z, W = map(int, input().split())
a_list = [i for i in map(int, input().split())]
if N == 1:
print(abs(W-a_list[0]))
exit()
max_a = max(a_list)
print(max(abs(a_list[-1]-W), abs(a_list[-2]-a_list[-1])))
|
n = int(input())
ans = []
n -= 1
while True:
x = n%26
n //= 26
ans.append(chr(x+97))
if n == 0:
break
n -= 1
ans.reverse()
print(''.join(ans)) |
class PromiscuityTransferLearningConfiguration():
def __init__(self, input_model_path, output_model_path, training_smiles_path, test_smiles_path, promiscuous_smiles_path,
nonpromiscuous_smiles_path, save_every_n_epochs=1, batch_size=128,
clip_gradient_norm=1., num_epochs=10, starti... |
artifact_db = \
{ 'adamantium': { 'level': 40,
'name': 'Adamantium',
'origin': 'Quest',
'tier': 3},
'ancient-essence': { 'level': 42,
'name': 'Ancient Essence',
'origin': 'Quest',
... |
'''
Voy a tratar de atrapar diferentes errores con try except.
El try captura un error especifico en el ejemplo un Type Error y retorna un mensaje predeterminado.
Try solo funciona con Type Errrors.
'''
def palindrome(word):
if word == word[::-1]:
return print(f'{word} es un Palindromo')
palindrome('... |
LOAD_DEMANDS = None
NUM_EPISODES = 1
NUM_K_PATHS = 1
NUM_CHANNELS = 1
NUM_DEMANDS = 10
MIN_FLOW_SIZE = 1 # 1
MAX_FLOW_SIZE = 100 # 100
MIN_NUM_OPS = 50 # 50 10 10
MAX_NUM_OPS = 200 # 200 7000 1000
C = 1.5 # 0.475 1.5
MIN_INTERARRIVAL = 1
MAX_INTERARRIVAL = 1e8
SLOT_SIZE = 1e3 # 0.2
MAX_FLOWS = 4 # None
MAX_TIME = 10e3... |
# Copyright (c) 2017 Cisco Systems, Inc.
# 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 r... |
class Matrix (object):
def __init__ (self, rows, cols, array=None):
super (Matrix, self).__init__ ()
length = rows * cols
self.rows = rows
self.cols = cols
if array:
if length != len (array):
raise RuntimeError ("Bad Dimensions")
self.a... |
# Image/video streams
PATH_IMAGE_SNAPSHOT = '/img/snapshot.cgi'
PATH_IMAGE_MJPEG = '/img/video.mjpeg'
PATH_IMAGE_RTSP = '/img/media.sav'
# PTZ Control
PATH_PAN_TILT = '/pt/ptctrl.cgi'
PARAM_PAN_TILT_DIRECTIONS = ('U', 'D', 'L', 'R', 'UL', 'UR', 'DL', 'DR')
# Configuration Groups
PATH_GET_GROUP = '/adm/get_group.cgi'
... |
#######################################
# Computes the proper motion distance #
#######################################
def PropMotion(M1,L1,K1,function,p):
if p == 1:
file = open(function+'_'+str(M1)+'_'+str(L1)+'.txt','wt')
PropD = []
x =[]
a=0
if (L1 == 0.0):... |
# '''
# https://practice.geeksforgeeks.org/problems/next-larger-element/0
# '''
# x = [8,7,3,2,4,9,5,4,6]
# i = len(x)-1
# stack = []
# ans = [None] * len(x)
# def isempty(st):
# if len(st) == 0:
# return True
# else:
# return False
# while(i>=0):
# if not isempty(stack):
# to... |
def areYouPlayingBanjo(name):
# Implement me!
if (name.startswith("R") |name.startswith("r") ):
return name + " "+"plays banjo"
else:
return name +" "+ "does not play banjo"
# return name
def areYouPlayingBanjo2(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not... |
'''
Auteur : Cantin L.
Site web : https://itliocorp.fr
Version : 0.2
License : MIT 3.0
Sujet : Afficher Hello World en python
Notions : Variable, Types de variable, Afficher une variable, Fonction, Commentaires
Fonction à utiliser :
type(...)
print(...)
def ...():
if ():
'''
def main() :
... |
class settings:
DATABASE = {
'test': {
'url': 'postgresql://admin:password@localhost:5432/test'
}
}
|
# Copyright (c) 2019 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 appli... |
"""
Given a sorted array of n distinct integers where each integer is in the range
from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
"""
def smallest_missing(arr: list) -> int:
"""
A modified version of binary search can be applied.
If the number mid index == value, then th... |
# Chest in the Lord Pirate PQ
LORD_PIRATE_ENRAGED_KRU = 9300115
LORD_PIRATE_ENRAGED_CAPTAIN = 9300116
reactor.incHitCount()
if reactor.getHitCount() >= 1:
i = 1
while i < 5:
sm.spawnMob(LORD_PIRATE_ENRAGED_KRU, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY(), False)
sm.spawnMob... |
# %% [markdown]
# # 8 - Collections
# %% [markdown]
# #### 1 - Lists
# %%
# Declare and assign the names
names = ["John", "Paul", "George"]
# Print the list of names
print(names)
# Add a new name
names.append("Jane")
# Declare and ass the scores
numbers = [100, 80, 90]
# Print the scores
print(numbers)
# Add a n... |
#Classe de Parâmetros do Algoritmo Label Propagation.
class ParametersLabelPropagation:
def __init__(self, max_iterations):
self.max_iterations = max_iterations
#Classe de Parâmetros do Algoritmo Asynchronous Label Propagation.
class ParametersAsynchronousLabelPropagation:
def __init__(self, wei... |
# * -- utf-8 -- * # python3
# Author: Tang Time:2018/4/17
'''简述:要求输入某年某月某日 提问:求判断输入日期是当年中的第几天?'''
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
day = int(input('请输入日期:'))
if day >31:
print ('请正确输入')
if month > 12:
print('请正确输入')
list1 = [31,59,90,130,151,181,212,243,273,304,334]
if (year % 4) ... |
class MarathonError(Exception):
pass
class MarathonHttpError(MarathonError):
def __init__(self, response):
"""
:param :class:`requests.Response` response: HTTP response
"""
content = response.json()
self.status_code = response.status_code
self.error_message = c... |
"""Utils for photos_time_warp"""
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
if count == 1:
return singular
else:
return plural
def noop(*args, **kwargs):
"""No-op function for use as verbose if verbose not set"""
pass
def red(msg: str)... |
class NLPData(object):
def __init__(self, sentences):
"""
:type sentences: list[str]
"""
self.__sentences = sentences
@property
def sentences(self):
return self.__sentences
|
getObject = {
'id': 37401,
'memoryCapacity': 242,
'modifyDate': '',
'name': 'test-dedicated',
'diskCapacity': 1200,
'createDate': '2017-10-16T12:50:23-05:00',
'cpuCount': 56,
'accountId': 1199911
}
getAvailableRouters = [
{'hostname': 'bcr01a.dal05', 'id': 12345},
{'hostname': ... |
class FileSystemAuditRule(AuditRule):
"""
Represents an abstraction of an access control entry (ACE) that defines an audit rule for a file or directory. This class cannot be inherited.
FileSystemAuditRule(identity: IdentityReference,fileSystemRights: FileSystemRights,flags: AuditFlags)
FileSystemAuditR... |
"""
Small collection of custom objects.
Sometimes used for their custom names only.
"""
class CouldNotLoadError(ResourceWarning):
def __init__(self, *args, study_id=None):
super(CouldNotLoadError, self).__init__(*args)
self.study_id = study_id
class ChannelNotFoundError(CouldNotLoadError):
d... |
# By using two pointer sum method to count if any 2 numbers in arr equals the given sum
def check_sum(arr, n, sum):
l = 0
r = n-1
count = 0
while l < r:
cur_sum = arr[l] + arr[r]
if cur_sum == sum:
print(sum, arr[l], arr[r], end = ' ')
count +=1
l+=... |
#
# PySNMP MIB module WYSE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WYSE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32: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 2019, 09:23:1... |
age = input("How old are you? ")
height = input("How tall are you? ") # "TypeError: input expected at most 1 arguments, got 2" will raise if more than 1 string is pu inside input()
weight = input("How much do you weight? ")
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
#-------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright SquirrelNetwork
class Config(object):
###########################
## DATABASE SETTINGS ##
##########################
HOST = 'localhost'
PORT = 3306
USER = 'usr'
PASSWORD = 'pws'
DBNAME = 'dbname'
################... |
#!/usr/bin/env python3
class TrieNode(object):
"""
This class represents a node in a trie
"""
def __init__(self, text: str):
"""
Constructor: initialize a trie node with a given text string
:param text: text string at this trie node
"""
self.__text = text
... |
# --- Day 12: Passage Pathing ---
# With your submarine's subterranean subsystems subsisting suboptimally, the only way you're getting out of this cave anytime soon is by finding a path yourself. Not just a path - the only way to know if you've found the best path is to find all of them.
#
# Fortunately, the sensors ar... |
class Perfil:
def __init__(self,username,tipo="user"):
self.username = username
self.carritoDCompras = []
self.tipo = tipo
def AgregarACarrito(self, item):
self.carritoDCompras.append(item)
class Administrador(Perfil):
def __init__(self,username, tipo = "Admin"):
... |
# vim: fileencoding=utf-8
"""
AppHtml settings
@author Toshiya NISHIO(http://www.toshiya240.com)
"""
defaultTemplate = {
'1) 小さいボタン': '${badgeS}',
'2) 大きいボタン': '${badgeL}',
'3) テキストのみ': '${textonly}',
"4) アイコン付き(小)": u"""<span class="appIcon"><img class="appIconImg" height="60" src="${icon60url}" style... |
#
# PySNMP MIB module EFDATA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EFDATA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:59:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
# Cutting a Rod
# Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then ... |
"""
programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre
todos os valores e qual foi o maior e menor valores lidos. O programa deve perguntar ao usuário se
ele quer ou não continuar a digitar valores
"""
resp = 'S'
media = quantidade = soma = maior = menor = 0
while res... |
print('\033[4;33;45mPrograma de financiamento\033[m')
casa=float(input('Qual o valor da casa? '))
salário=float(input('Qual o seu salário? '))
tempo=int(input('Quantos anos para pagar? '))
tempo_meses=int(tempo * 12)
salário_usável=salário * 0.30
prestação = casa/tempo_meses
cálculo=salário_usável * tempo_meses
if cálc... |
#!/usr/bin/python
################################################################################
#
# class that represents a shift register object
#
################################################################################
class Shifter:
# pins connected to the 74HC595's
GPIO_CLOCK=-1 # clock pin
GPIO_DATA... |
#!/bin/python3
def minimum_range_activations(locations):
n = len(locations)
dp = [-1] * n
for i in range(n):
left_index = max(i - locations[i], 0)
right_index = min(i + (locations[i] + 1), n)
dp[left_index] = max(dp[left_index], right_index)
# Initializations, starting range
... |
#!/usr/bin/env python
'''
Copyright (C) 2020, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'Sitelock (TrueShield)'
# Well this is confusing, Sitelock itself uses Incapsula from Imperva
# So the fingerprints obtained on blockpage are similar to those of Incapsula.
def is_waf(self):
... |
# Habitat configs
# This should be sourced by the training script,
# which must save a sacred experiment in the variable "ex"
# For descriptions of all fields, see configs/core.py
####################################
# Standard methods
####################################
@ex.named_config
def taskonomy_features... |
f=open("./CoA/2020/data/03a.txt","r")
count1=0
positionr1=0
count3=0
positionr3=0
count5=0
positionr5=0
count7=0
positionr7=0
countdouble=0
positionrdouble=0
line_count=0
for line in f:
line=line.strip()
relpos1=positionr1%(len(line))
relpos3=positionr3%(len(line))
relpos5=positionr5%(len(line))
... |
target_module = "streamcontrol.obsmanager"
def test_obs_websocket_manager_new(get_handler):
"""Should create an inner instance when called"""
ows = get_handler(target_module)
myt = ows.OBSWebSocketManager.__new__(ows.OBSWebSocketManager)
assert isinstance(myt.instance, ows.OBSWebSocketManager)
def t... |
# Returns strand-sensitive order between two genomic coordinates
def leq_strand(coord1, coord2, strand_mode):
if strand_mode == "+":
return coord1 <= coord2
else: # strand_mode == "-"
return coord1 >= coord2
# Converts a binary adjacency matrix to a list of directed edges
def to_adj_list(adj... |
"""
Projeto: Boletim com listas compostas
"""
studentGrade = []
counter = 0
while True:
studentGrade.append(["", [float(), float()]])
# Outra opção seria criar 3 variáveis e utilizar o append para colocar cada uma em sua posição.
studentGrade[counter][0] = input('Nome: ')
studentGrade[counter][1][0] =... |
a = 3
if a ==2:
print("A")
if a==3:
print("B")
if a==4:
print("C")
else:
print("D")
|
def data_splitter(data, idxs):
subsample = data[idxs]
return subsample
## Note: matrices are indexed like mat[rows, cols]. If only one is provided, it is interpreted as mat[rows]. |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def read_version(CMakeLists):
version = []
with open(CMakeLists, 'r') as fp:
for row in fp:
if len(version) == 3: break
if 'RSGD_MAJOR' in row:
version.append(row.split('RSGD_MAJOR')[-1])
elif 'RSGD_MINOR' in row:
version.append(ro... |
"""
File: a_to_z.py
Prompts the user for a file name, then
outputs each of the unique words from
the file in alphabetical order
"""
unique = []
input_filename = input('Enter the input file name: ')
print()
with open(input_filename, "r") as f:
lines = f.readlines()
for line in lines:
words = line.split... |
"""
opcode module - potentially shared between dis and other modules which
operate on bytecodes (e.g. peephole optimizers).
"""
__all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs",
"haslocal", "hascompare", "hasfree", "opname", "opmap",
"HAVE_ARGUMENT", "EXTENDED_ARG"]
cmp_op = ('<... |
Experiment(description='Testing the pure linear kernel',
data_dir='../data/tsdlr/',
max_depth=10,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=500, ... |
class FuzzyPaletteInvalidRepresentation(Exception):
"""
An Exception indicating that not enough classes have been provided to represent the fuzzy sets.
"""
def __init__(self, provided_labels: int, needed_labels: int):
super().__init__(f"{needed_labels} labels are needed to represent the selecte... |
class Observer:
def update(self, obj, *args, **kwargs):
raise NotImplemented
class Observable:
def __init__(self):
self._observers = []
def add_observer(self, observer):
self._observers.append(observer)
def remove_observer(self, observer):
self._observers.remove(obser... |
def my_func():
result = 3 * 2
return result
print(my_func())
def format_name(f_name, l_name):
"""Take first and last name and format it and returns title version"""
name = ''
name += f_name.title()
name += ' '
name += l_name.title()
return name
print(format_name('eddie', 'wang'))
|
class ConstraintDeduplicatorMixin(object):
def __init__(self, *args, **kwargs):
super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs)
self._constraint_hashes = set()
def _blank_copy(self, c):
super(ConstraintDeduplicatorMixin, self)._blank_copy(c)
c._constraint_hash... |
def chainResult(num):
while num != 1 and num != 89:
s = str(num)
num = 0
for c in s:
num += int(c) * int(c)
return num
count = 0
for num in range(1,10000000):
if chainResult(num) == 89:
count += 1
print(count)
|
"""
Time: O(N)
Space: O(1)
Keep updating the minimum element (`min1`) and the second minimum element (`min2`).
When a new element comes up there are 3 possibilities.
0. Equals to min1 or min2 => do nothing.
1. Smaller than min1 => update min1.
2. Larger than min1 and smaller than min2 => update min2.
3. Larger than mi... |
"""
Created on 12.02.2010
@author: jupp
"""
def compute_similarity(lattice):
similarity_index = {}
for c1 in lattice:
for c2 in lattice:
if not (c1.concept_id in similarity_index and c2.concept_id in similarity_index[c1.concept_id]):
if c1.concept_id not in similarity_... |
"""
ccextractor-web | forms.py
Author : Saurabh Shrivastava
Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com
Link : https://github.com/saurabhshri
"""
|
def solution(board, moves):
basket = []
answer = 0
for move in moves:
for row in board:
if row[move - 1] != 0:
basket.append(row[move - 1])
row[move - 1] = 0
if len(basket) >= 2 and basket[-1] == basket[-2]:
basket.pop(... |
class Const:
board_width = 19
board_height = 19
n_in_row = 5 # n to win!
train_core = "keras"
check_freq = 10 # auto save current model
check_freq_best = 500 # auto save best model
|
"""
携程海洋馆中有 n 只萌萌的小海豚,初始均为 0 岁,
每只小海豚的寿命是 m 岁,且这些小海豚会在 birthYear[i]
这些年份生产出一位宝宝海豚(1 <= birthYear[i] <= m),
每位宝宝海豚刚出生为 0 岁。
问 x 年时,携程海洋馆有多少只小海豚?
输入
n(初始海豚数)
m(海豚寿命)
海豚生宝宝的年份数量 (假设为 p)
海豚生宝宝的年份 1
...
海豚生宝宝的年份 p
x(几年后)
输出
x 年后,共有多少只小海豚
样例:
5
5
2
2
4
5
输出
20
"""
def solve(n, m, indexs, x):
"""
ij 表示 第i年j岁的小海豚... |
# -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.