content stringlengths 7 1.05M |
|---|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
class SesDevException(Exception):
pass
class AddRepoNoUpdateWithExplicitRepo(SesDevException):
def __init__(self):
super().__init__(
"The --update option does not work with an explicit custom repo."
)
class BadMakeCheckRolesNodes(SesDevException):
def __init__(self):
... |
"""
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475"
Desired Output
0.8475
"""
text = "X-DSPAM-Confidence: 0.8475"
index = text.fin... |
l = int(input("enter the lower interval"))
u = int(input("enter the upper interval"))
for num in range(l,u+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
|
class Vocabs():
def __init__(self):
reuters = None
aapd = None
VOCABS = Vocabs()
|
def respond(start_response, code, headers=[('Content-type', 'text/plain')], body=b''):
start_response(code, headers)
return [body]
def key2path(key):
b = key.encode('utf-8')
return hashlib.md5(b).digest()
|
def part1():
pass
if __name__ == '__main__':
with open('input.txt') as f:
lines = f.read().splitlines() |
class A:
def __init__(self):
print("1")
def __init__(self):
print("2")
a= A() |
def decay_lr_every(optimizer, lr, epoch, decay_every=30):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = lr * (0.1 ** (epoch // decay_every))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
# TODO: noam scheduler
# "Schedule": {
# "name": "... |
##
# Copyright © 2020, The Gust Framework Authors. All rights reserved.
#
# The Gust/Elide framework and tools, and all associated source or object computer code, except where otherwise noted,
# are licensed under the Zero Prosperity license, which is enclosed in this repository, in the file LICENSE.txt. Use of
# this ... |
#!/usr/bin/python3
"""
Main file for testing
"""
makeChange = __import__('0-making_change').makeChange
print(makeChange([1, 2, 25], 37))
print(makeChange([1256, 54, 48, 16, 102], 1453)) |
WSGI_ENTRY_SCRIPT = """
import logging
from parallelm.ml_engine.rest_model_serving_engine import RestModelServingEngine
from {module} import {cls}
from {restful_comp_module} import {restful_comp_cls}
logging.basicConfig(format='{log_format}')
logging.getLogger('{root_logger_name}').setLevel({log_level})
comp = {res... |
load("@bazel_gazelle//:deps.bzl", "go_repository")
# bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=repositories.bzl%go_repositories
def go_repositories():
go_repository(
name = "com_github_fsnotify_fsnotify",
importpath = "github.com/fsnotify/fsnotify",
sum = "h1:hsms1Qy... |
# Python Program to demonstrate the LIFO principle using stack
print("Stack utilizes the LIFO (Last In First Out) Principle")
print()
stack = [] # Initializating Empty Stack
print("Initializing empty stack :", stack) # Printing empty Stack
# Adding items to the Stack
stack.append("Hey")
stack.append("there!")
stack... |
# Copyright 2020, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
class Plugin_OBJ():
def __init__(self, fhdhr, plugin_utils, broadcast_ip, max_age):
self.fhdhr = fhdhr
self.broadcast_ip = broadcast_ip
self.device_xml_path = '/hdhr/device.xml'
self.cable_schema = "urn:schemas-opencable-com:service:Security:1"
self.ota_schema = "urn:sch... |
"""
Data store module
- simple key-value store to organize data collection and lookup / filtering based on meta data.
- the encoding of the meta data follows the encoding of the rest of my Advanced Systems Lab (ASL)
project data processing; project description follows on my homepage
id_str consists of: key1_value1_... |
class OASInvalidSpec:
...
class OASInvalidTypeValue(OASInvalidSpec, TypeError):
"""OASInvalidTypeValue refers to invalid type of the value.
Thrown if either "default" or "example" value's type does not match
the OASType
"""
...
class OASInvalidConstraints(OASInvalidSpec, ValueError):
"... |
class Sigma:
"""
A representation of the sigma term in the model.
Specifically, this is the sigma of y itself, i.e. the sigma in
y ~ Normal(sum_of_trees, sigma)
The default prior is an inverse gamma distribution on the variance
The parametrization is slightly different to the numpy gamma ... |
"""Reverse a list.
Reverse the order of the elements of list _x .
This may reverse "in-place" and destroy the original ordering.
Source: programming-idioms.org
"""
# Implementation author: synapton
# Created on 2017-05-14T03:47:52.643616Z
# Last modified on 2019-09-27T02:57:37.321491Z
# Version 3
# Creates a new, ... |
def _remove_extensions(file_list):
rv = {}
for f in file_list:
if (f.extension == "c" or f.extension == "s" or f.extension == "S"):
rv[f.path[:-2]] = f
else:
rv[f.path] = f
return rv
def _remove_arch(file_dict, arch):
rv = {}
for f in file_dict:
idx =... |
v = ["a", "i", "u", "e", "o"]
c = input()
if c in v:
print("vowel")
else:
print("consonant") |
HXLM_PLUGIN_META = {
'code': "xa_amnesty",
'code_if_approved': "xz_amnesty"
}
|
"""
ID: PRTM
Title: Calculating Protein Mass
URL: http://rosalind.info/problems/prtm/
"""
monoisotopic_mass_dict = {
'A': 71.03711,
'C': 103.00919,
'D': 115.02694,
'E': 129.04259,
'F': 147.06841,
'G': 57.02146,
'H': 137.05891,
'I': 113.08406,
'K': 128.09496,
'L': 113.08406,
... |
"""
This package contains the code for testing pyqode.python.
To run the test suite, just run the following command::
tox
To select a specific environment, use the -e option. E.g. to run coverage
tests::
tox -e cov
Here is the list of available test environments:
- py27-pyqt4
- py27-pyqt5
- py... |
horpos = list(map(int, open('Day 07.input').readline().split(',')))
mean = sum(horpos) / len(horpos)
target1 = mean - (mean % 1)
target2 = mean + (1 - mean % 1)
print(min(round(sum((abs(x - target1) * (abs(x - target1) + 1)) / 2 for x in horpos)),
round(sum((abs(x - target2) * (abs(x - target2) + 1)) / 2 for ... |
n = int(input())
positives = []
negatives = []
for _ in range(n):
num = int(input())
if num >= 0:
positives.append(num)
else:
negatives.append(num)
count_of_positives = len(positives)
sum_of_negatives = sum(negatives)
print(positives)
print(negatives)
print(f'Count of po... |
s = "abcdefgh"
for index in range(len(s)):
if s[index] == "i" or s[index] == "u":
print("There is an i or u")
# Code can be rewrited as
for char in s:
if char == "i" or char == "u":
print("There is an i or u") |
#! usr/bin/python3
#-*- coding:utf-8 -*-
"""Constants of MacGyver game"""
# Window settings
number_sprite_side = 15
sprite_size = 40
score_wiev=40
window_side = number_sprite_side * sprite_size
window_height = number_sprite_side * sprite_size + score_wiev
#The window customization
window_title = "MacGyver"
image_icon... |
banned_words = input().split()
text = input()
replaced_text = text
for word in banned_words:
replaced_text = replaced_text.replace(word, "*" * len(word))
print(replaced_text)
|
tamanho = float(input('Quantos metros quadrados devem ser pintados: '))
litros = tamanho / 3.0
latas = int(litros / 18.0)
if (litros % 18 != 0):
latas += 1
print('Voce devera comprar', latas, 'latas.')
print('O valor total é:', latas * 80)
|
"""
Faça um programa que leia o nome e peso de várias pessoas, guardando tudo em uma lista. No final mostre:
- Quantas pessoas foram cadastradas
- Uma listagem com as pessoas mais pesadas
- Uma listagem com as pessoas mais leves
"""
dados = list()
pessoas = list()
maior = menor = 0
while True:
dados.append(str(inpu... |
vocab_sizes_dict = {'BabyAI-BossLevel-v0': 31,
'BabyAI-BossLevelNoUnlock-v0': 31,
'BabyAI-GoTo-v0': 13,
'BabyAI-GoToImpUnlock-v0': 13,
'BabyAI-GoToLocal-v0': 13,
'BabyAI-GoToLocalS5N2-v0': 13,
'BabyAI... |
a=int(input('Qual o primeiro número ?'))
b=int(input('Qual o segundo número ?'))
c=a+b
print('Olá Felipe a soma entre {} e {} é {}'.format(a,b,c))
|
# coding=utf-8
def modifier_select_rsp_contracts(parametersDict):
'''
модификатор входных параметров апи для коллекции контрактов
'''
maxResultsPerQuery = 50
try:
perpage = int(parametersDict.get("perpage", maxResultsPerQuery))
except:
perpage = maxResultsPerQuery
if perpage ... |
str=input("Enter string:")
str_list=list(str)
rev_list=[]
rev_str=""
length=len(str_list)
for i in range(-1,-(length+1),-1):
rev_list.append(str_list[i])
rev=rev_str.join(rev_list)
print(rev)
print("Character in even index:")
for i in range(0,len(str),2):
print(str[i])
|
test_ads_info = [
{'ad_id': 787, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': 'JV', 'item_price': 812.32},
{'ad_id': 476, 'status': True, 'bidding_cpc': 1, 'advertiser': 'DO', 'banner_style': 'XII', 'category': 'Pullover', 'layout_style': '... |
class BaseAggregator(object):
def __init__(self, *args, **kwargs):
pass
def process(self, current_activities, original_activities, aggregators, *args, **kwargs):
"""
Processes the activities performing any mutations necessary.
:type current_activities: list
:param curren... |
########################################
##### Decoradores nativos de Python
########################################
print(f"\n{'#'*10} 1: Funciones como objetos y referencias {'#'*10}")
def hello_world():
return 'Hola Mundo!'
def hello_world_with_name(function, name):
return f'{function()}, y hola {name}!'
prin... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# 111. Minimum Depth of Binary Tree
# Given a binary tree, find its minimum depth.
# ****************
# 思路:
# 思考四种Case
# 1. 有或者没有Root
# 2. 有root.left,没有root.right
# 3. 有root.right, 没有 root.left
# 4. 两个Children都有
# *********... |
#
# PySNMP MIB module TELESYN-ATI-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TELESYN-ATI-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 18:22:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
def make_shirt(size, message):
"""Display information regarding the size and message of a shirt."""
print("The shirt size is " + size +
" and the message will read: " + message + ".")
make_shirt('large', 'Archaeology Club')
def make_shirt(size, message):
"""Display information regarding the si... |
"""
Author: Ao Wang
Date: 09/05/19
Description: Affine cipher with decrypter/hack
"""
# The function loads the English alphabet
def loadAlphabet():
alphabet = ""
for i in range(26):
alphabet += chr(ord("a") + i)
return alphabet
# The function returns the greatest common denominator using Euclid's... |
#
# PySNMP MIB module FOUNDRY-SN-SWITCH-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FOUNDRY-SN-SWITCH-GROUP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:23:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
lista = []
pares = []
impar = []
while True:
lista.append(int(input('Digite um valor: ')))
r = ' '
while r not in 'SN':
r = str(input('Deseja Continuar? [S/N]: ')).strip().upper()[0]
if r == 'N':
break
print('-='*30)
print(f'Você digitou os valore {lista}')
for i, v in enumerate(list... |
class Employee:
def __init__(self, surname, name, contact):
self.surname = surname
self.name = name
self.contact = contact
def __eq__(self, other):
return self.name == other.name \
and self.surname == other.surname \
and self.contact == other.contac... |
for i in range(2,1001):
s = i
for j in range(1,i):
if i % j == 0:
s -= j
if s == 0: #减完再看是否符合完数的定义
print (i)
|
# Assume you have a file system named quotaFs
file_system_name = "quotaFs"
# Delete the quotas of groups on the file system with ids 998 and 999
client.delete_quotas_groups(file_system_names=[file_system_name], gids=[998, 999])
# Delete the quotas of groups on the file system with names group1 and group2
client.delet... |
# itoc = {0: ‘a’, 1:’b’, 2:’c’}
# ctoi = {‘a’: 0, ‘b’: 1, ’c’:2}
# current_element = ‘?’
# j = 0
# for i, element in enumerate(l):
# if l[i] == ‘?’:
# if current_element= ‘?’:
# current_element = 0
# else:
# current_element = (current_element + 1) % 3
# if i < n -1 and current_element == arr[i+1]:
# ... |
class Atom:
def __init__(self, id_, position, chain_id, name, element, residue=None, altloc=None, occupancy=None):
self.id = id_
self.name = name
self.element = element
self.chain_id = chain_id
self.position = position
self.residue = residue
self.altloc = al... |
utils ='''
from extensions.extension import pwd_context
from flask import current_app
# from app.custom_errors import PasswordLength
class PasswordLength(Exception):
pass
def verify_secret(plain_secret: str, hashed_secret: str):
""" check plain password with hashed password """
if len(plain_secret) < 8:... |
"""A module defining the third party dependency OpenSSL"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def openssl_repositories():
maybe(
http_archive,
name = "openssl",
build_file = Label("//openssl:BU... |
# V0
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
A.sort(key = lambda x : x % 2)
N = len(A)
res = []
for i in range(N // 2):
res.append(A[i])
res.append(A[N - 1 - i])
ret... |
while True:
a,b = map(int,input().split())
if a== b == 0:
break
k = 1
if b >= a-b:
k1 = b
k2 = a-b
else:
k1 = a-b
k2 = b
for i in range(k1+1,a+1):
k*=i
for i in range(2,k2+1):
k//=i
print(k) |
"""
将华氏度转换成摄氏度
"""
f = float(input("请输入华氏度: "))
c = (f - 32) % 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))
|
#
# PySNMP MIB module HP-ICF-CHASSIS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CHASSIS
# Produced by pysmi-0.3.4 at Wed May 1 13:33:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
nums = [72, 69, 76, 76, 79]
#버블 정렬 처음부터 차례로 비교하는 것
print(f"not sorted nums: {nums}") #정렬 되기
length = len(nums) - 1
for i in range(length): #숫자 하나씩 순차적으로 비교하며 큰 숫자는 밀어내기
for j in range(length - i):
if nums[j] > nums[j+1]: #앞 숫자가 더 큰 경우
# temp = nums[j] #변수 두개값 바꾸기
# nu... |
"""Gets the digging in sentences that are non-blocking, since the other ones were
not included in Futrell et al 2019"""
i =0
lines = []
for line in open("../unkified_digging_in_sentences.txt"):
if i < 93:
lines.append(line)
if i >= 186 and i < 279:
lines.append(line)
i += 1
for line in lines... |
class C(Exception):
pass
try:
raise C
except C:
print("caught exception")
|
for i in range(2,21):
with open(f"Tables/ Table of {i}","w") as f:
for j in range(1,11):
f.write(f"{i} X {j} ={i*j}")
if j!=10:
f.write("\n")
|
# Example configuration file
# Debug mode
DEBUG = False
# host and port. 127.0.0.1 will only serve locally - set to 0.0.0.0 (or iface IP) to have available externally.
HOST = '0.0.0.0'
PORT = 8765
# Secret key. This ensures only approved applications can use this. YOU MUST CHANGE THIS VALUE TO YOUR OWN SECRET!
# Not... |
b = False
e = "Hello world"
while b:
print(b)
d = True
while d:
print(d and False)
print(d and True)
print("hello")
|
"""
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example
For inputArray = [3, 6, -2, -5, 7, 3], the output should be
adjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product.
Input/Output
[execution time limit] 4 secon... |
notas = str(input('Digite as suas duas notas: ')).strip()
n1 = float(notas.split()[0])
n2 = float(notas.split()[1])
média = (n1 + n2) / 2
if média < 5:
print('Você foi \033[31mREPROVADO(A)\033[m!')
elif média < 7:
print('Você está de recuperação, se esforce que você consegue!!')
else:
print(f'Você foi \033[... |
# Please do not any airflow imports in this file
# We want to allow importing constants from this file without any side effects
# Do not change this name unless you change the same constant in monitor_as_dag.py in dbnd-airflow-monitor
MONITOR_DAG_NAME = "databand_airflow_monitor"
|
"""
16. A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,...
Faça um programa que gere a série até que o valor seja maior que 500.
"""
t1 = 0
t2 = 1
t3 = 0
print("{}".format(t1, t2), end=' ')
while t3 <= 500:
t3 = t1 + t2
print("{}".format(t3), end=' ')
t1 = t2
t2 = t3
|
data = input().split()
x = int(data[0])
y = int(data[1])
limit = int(data[2])
for value in range(1,limit+1):
output = ""
if value % x == 0:
output += "Fizz"
if value % y == 0:
output += "Buzz"
if output == "":
print(value)
else:
print(output) |
limit=int(input("enter the limit"))
sum=0
for i in range(1,limit+1,1) :
if(i % 2== 0 ):
print("even no is",i)
sum=sum+i
print(sum)
|
# -*- coding: utf-8 -*-
# the __all__ is generated
__all__ = []
# __init__.py structure:
# common code of the package
# export interface in __all__ which contains __all__ of its sub modules
# import all from submodule quote
# from .quote import *
# from .quote import __all__ as _quote_all
# __all__ += _quote_all
# ... |
def war(Naomi_w, Ken_w):
Naomi_wins = 0
while len(Naomi_w) > 0:
for X in Naomi_w:
temp = []
done = 0
Chosen_Naomi = X
Told_Naomi = X
for i in Ken_w:
if i > X:
temp.append((i, i - X))
... |
"""Faça um programa em Python que recebe um número inteiro e imprime seu dígito das dezenas."""
numero = int(input("numero inteiro: "))
numero = numero // 10
dezenas = numero % 10
print("O dígito das dezenas é", dezenas)
|
#!/usr/bin/env python3
"""Convert arabic numbers to roman numbers.
Title:
Roman Number Generator
Description:
Develop a program that accepts an integer
and outputs the Roman Number equivalent of that number.
Examples:
4 - IV
12 - XII
20 - XX
Submitted by SoReNa
"""
def arabic_to_roman(number: int) -> str:
"""Re... |
class TumorSampleProfileList(object):
def __init__(self):
self.tumor_profiles = []
self._name = ''
self._num_read_counts = 0
def __iter__(self):
return iter(self.tumor_profiles)
@property
def name(self):
return self._name
@name.setter
... |
"""Exercicio 34:
Crie uma classe com dois metodos, pelo menos:
recebe_string(): para pegar do console um texto
printa_string(): para imprimir a string no console
"""
class IOTexto():
def __init__(self):
self.texto = ""
def recebe_string(self):
self.texto = input("Defina o texto: ")
def pr... |
#_Author_="Robb Zuo"
list = [ 1, 2, 3, 4, 5]
print(list)
# 增
list.append(8)
print(list)
# 删
list.pop(-2)
print(list)
# 改
list[0] = 9
print(list)
# 查
print(list.index(3))
list = str(list)
f = open('text.txt', 'w', encoding='utf-8')
f.write(list)
f.close()
|
'''
Author : MiKueen
Level : Easy
Company : Google
Problem Statement : Two Sum
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
def twoSum(nums, k):
... |
with open('texto1.txt', 'r') as arquivo:
conteudo = arquivo.read().split(',')
with open('resultado1.txt', 'w') as resultado:
for item in conteudo:
texto = f'novo conteudo Antonella te amo {item.strip()}\n'
resultado.write(texto)
|
print('Vou pintar as paredes da minha casa, mas não sei quanto usar de tinta. Então vamos calcular.')
alt = float(input('Qual é a altura da parede? '))
lar = float(input('Qual é a largura da parede? '))
m2 = alt * lar
print('Sua parede tem a dimensão de {} x {}, totalizando {} m².'.format(alt, lar, m2))
demao = float(i... |
"""Given a graph G =(V, E) we want to find a minimum spannning tree in the graph (it may not be unique).
A minimuim spanning tree is a subset of the edges which connect all vertices in the graph with the minimal total edge cost.
Uses union and find:
Find:
find which component a particular elemnent belongs to find th... |
"""
---> Longest String Chain
---> Medium
"""
class Solution:
def longest_str_chain(self, words) -> int:
word_dict = {}
for w in sorted(words, key=len):
word_dict[w] = max(word_dict.get(w[:i] + w[i + 1:], 0) + 1 for i in range(len(w)))
print(w, word_dict)
return m... |
"""
14 / 14 test cases passed.
Runtime: 40 ms
Memory Usage: 15.1 MB
"""
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
used, bank = set(), set(bank)
if end not in bank: return -1
# current gene, steps
que = collections.deque([(start, 0)])
... |
# -*- coding: utf-8 -*-
"""Version information for this package."""
__version__ = "4.10.9"
VERSION: str = __version__
"""Version of package."""
__url__ = "https://github.com/Axonius/axonius_api_client"
URL: str = __url__
"""URL of package."""
__author__ = "Axonius"
AUTHOR: str = __author__
"""Auth of package."""
__t... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root):
# DFS
def solve(node, level):
if not node: return level - 1
elif node.left and n... |
def is_polygon(way):
"""Checks if the way is a polygon.
Args
way: the osmium.osm.Way to check.
Returns:
True if the way is a polygon, False otherwise.
Note: The geometry shape can still be invalid (e.g. self-intersecting).
"""
if not way.is_closed():
return False
if ... |
class Room:
def __init__(self):
pass
def intro_text(self):
raise NotImplementedError()
def adjacent_moves(self):
pass
def available_actions(self):
pass
class StartingRoom(Room):
def __init__(self, ):
super().__init__()
def intro_text(self):
r... |
list1, list2 = [123, 567, 343, 611], [456, 700, 200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2))
print("min value element : ", min(list1))
print("min value element : ", min(list2))
|
# splitting_list_elements.py
print("""
{original_code}
json_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"]
separators = ['/', '&', 'and']
title = []
for i in json_data:
k = 0
while k < len(separators):
if separators[k] in i:
t = i.split(separators[k])
title.ext... |
def seq(hub, low, running):
'''
Return the sequence map that should be used to execute the lowstate
The sequence needs to identify:
1. recursive requisites
2. what chunks are free to run
3. Bahavior augments for the next chunk to run
'''
ret = {}
for ind, chunk in enumerate(low):
... |
#!/usr/bin/env python3
# Day 6: Queue Reconstruction by Height
#
# Suppose you have a random list of people standing in a queue. Each person is
# described by a pair of integers (h, k), where h is the height of the person
# and k is the number of people in front of this person who have a height
# greater than or equal... |
"""
Descriptions
Advantages:
Tab auto complete.
Historical log to archieve.
Edit with in a line.
Use $run to call external python script.
Support system cmds.
Support pylab module.
Debug Python code and profiler.
"""
"""
cmds for ipython
ipython --pylab
... |
class Tool: pass
class Documentation(Tool): pass
class Frustration(Tool): pass
class Dwf(Documentation, Frustration, Tool): pass
|
class roiData:
def __init__(self, roistates, numberOfROIs, dicomsPath=None):
self.layers = []
self.roistates = []
self.dicomsPath=dicomsPath
self.originalLenght = len(roistates)
self.numberOfROIs = numberOfROIs
for i, roistate in enumerate(roistates):
... |
def stringify(token):
if token.orth_ == 'I':
return token.orth_
elif token.is_quote and token.i != 0 and token.nbor(-1).is_space:
return ' ' + token.orth_
elif token.ent_type_ == '':
return token.lower_
else:
return token.orth_
def parse_stack(token):
stack = []
... |
def configure(name):
if name == 'compute_mfcc':
return {"--allow-downsample":["false",str],
"--allow-upsample":["false",str],
"--blackman-coeff":[0.42,float],
"--cepstral-lifter":[22,int],
"--channel":[-1,int],
"--debug-mel":["false",str],
"--dither":[1,int],
"--energy-floor":[0,int],
... |
class XForwardedHostMiddleware( object ):
"""
A WSGI middleware that changes the HTTP host header in the WSGI environ
based on the X-Forwarded-Host header IF found
"""
def __init__( self, app, global_conf=None ):
self.app = app
def __call__( self, environ, start_response ):
x_fo... |
def sorter(item):
return item['name']
presenters=[
{'name': 'Arthur', 'age': 9},
{'name': 'Nathaniel', 'age': 11}
]
presenters.sort(key=sorter)
print(presenters) |
class FakeCUDAContext(object):
'''
This stub implements functionality only for simulating a single GPU
at the moment.
'''
def __init__(self, device):
self._device = device
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __str__(... |
# do NOT import these models here.
# from .model import Word as WordModel
# from .model import Definition as DefinitionModel
class Word(object):
def __init__(self, model):
self.model = model
def set_definition(self, definitions: list):
"""
Replace the existing definition set by the one... |
"""
https://leetcode.com/problems/valid-mountain-array/
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > ... |
#
# PySNMP MIB module WWP-EXT-BRIDGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-EXT-BRIDGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:37:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.