content stringlengths 7 1.05M |
|---|
print('\033[1;30mTeste\033[m')
print('\033[4;33mTeste\033[m')
print('\033[1;34;40mTeste\033[m')
print('\033[30mTeste\033[m')
print('\033[mTeste\033[m')
print('\033[7;30mTeste\033[m')
a = 3
b = 5
print('Os valores são \33[1;32m{}\033[m e \033[1;31m{}\033[m !!!'.format(a,b))
nome = 'Bruno'
print('Olá {}{}{} !!'.format(... |
# 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... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 16:13:59 2019
@author: apln2
"""
class _No:
'''
Classe auxiliar
Usada dentro da programação das classes das estruturas lineares.
A lista implementada abaixo é uma lista de encadeamento simples, ou seja,
os nós possuem apenas uma referên... |
A, B, C = map(int, input().split())
result = 0
while True:
if A % 2 == 1 or B % 2 == 1 or C % 2 == 1:
break
if A == B == C:
result = -1
break
A, B, C = (B + C) // 2, (A + C) // 2, (A + B) // 2
result += 1
print(result)
|
description = 'bottom sample table devices'
group = 'lowlevel'
devices = dict(
st1_omg = device('nicos.devices.generic.Axis',
description = 'table 1 omega axis',
pollinterval = 15,
maxage = 60,
fmtstr = '%.2f',
abslimits = (-180, 180),
precision = 0.01,
moto... |
# REST framework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticatedOrReadOnly',),
'PAGINATE_BY': None,
}
|
root = 'demo_markdown_bulma'
environment = {
"STATTIK_ROOT_MODULE": root,
'STATTIK_SETTINGS_MODULE': f"{root}.settings"
} |
def generate_list(*args):
""" Silly function #1 """
array = []
for entry in args:
array.append(entry)
return array
def generate_dictionary(**kwargs):
""" Silly function #2 """
dictionary = {}
for entry in kwargs:
dictionary[entry] = kwargs[entry]
return dictionary
|
class CommentGenV16n3:
@classmethod
def generate_comment(clazz, indent, line_list):
text = f"\n{indent}".join(line_list)
return f"{indent}{text}\n"
|
# Copyright (c) 2010 Spotify AB
# Copyright (c) 2010 Yelp
#
# 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 to use, copy, modify... |
class ViewSection(View,IDisposable):
""" ViewSection covers sections,details,elevations,and callouts,all in their reference and non-reference variations. """
@staticmethod
def CreateCallout(document,parentViewId,viewFamilyTypeId,point1,point2):
"""
CreateCallout(document: Document,parentViewId: ElementId,vi... |
"""
[2016-08-24] Challenge #280 [Intermediate] Anagram Maker
https://www.reddit.com/r/dailyprogrammer/comments/4zcly2/20160824_challenge_280_intermediate_anagram_maker/
# Description
Anagrams, where you take the letters from one or more words and rearrange them to spell something else, are a fun word
game.
In this c... |
# Time: O(n)
# Space: O(n)
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
P = [0] * len(s)
C, R = 0, 0
for i in xrange(1, len(... |
def bond(output, i,j,Jz,Jx,S2=1):
if S2==1:
bond_half(output, i,j,Jz,Jx)
elif S2==2:
bond_one(output, i,j,Jz,Jx)
else:
error("S2 should be 1 or 2.")
def bond_half(output, i,j, Jz,Jx):
z = 0.25*Jz
x = 0.5*Jx
# diagonal
output.write('{} 0 {} 0 {} 0 {} 0 {} 0.0 \n'.format(i,i,j,j,z))
output.wr... |
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
ans = int(2e5)
i = curr = 0
for j in range(len(nums)):
curr += nums[j]
while curr >= s:
curr -= nums[i]
ans = min(ans, j + 1 - i)
i += 1
return 0 if ans == int(2e5) else ans
|
# 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
#
# 说明:你不能倾斜容器,且 n 的值至少为 2。
#
#
#
# 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
#
#
#
# 示例:
#
# 输入: [1,8,6,2,5,4,8,3,7]
# 输出: 49
# Related Topics 数组 双指针
# leetcode submit... |
"""Xorshift Random Number Generator"""
class Xorshift:
"""Xorshift Random Number Generator"""
def __init__(self,seed_0,seed_1,seed_2,seed_3):
self.seed_0 = seed_0
self.seed_1 = seed_1
self.seed_2 = seed_2
self.seed_3 = seed_3
def next(self):
"""Generate the next rand... |
{'application':{'type':'Application',
'name':'Addresses',
'backgrounds':
[
{'type':'Background',
'name':'bgBody',
'title':'Addresses',
'position':(208,183),
'size':(416, 310),
'menubar':
{
'type':'MenuBar',
'menus':
[
{ 'type':'Menu',
'name':'menuFile',
... |
# Write a function that calculates
# the number of characters included in a given string
# input: “hello”
# output: {“h”:1, “e”:1, “l”:2, “o”:1}
def number_of_character(input_str: str):
result_dict = {}
for i in input_str:
result_dict[i] = input_str.count(i)
return result_dict
|
"""
Russian customizations
Holds customized validation messages for russian language
"""
translations = {
'__meta__': 'Customized translations for Russian',
}
|
class API:
# BASE_URL
API_PREFIX = '/api/v1'
# REST Endpoints
ACCOUNT_BALANCE = '/accountbalance'
CURRENT_POSITIONS = '/currentpositions'
EXCHANGE_LIST = '/exchangelist'
HISTORICAL_ACCOUNT_BALANCES = '/historicalaccountbalances'
HISTORICAL_ORDER_FILLS = '/historicalorderfills'
SECU... |
class KubeKrbMixin(object):
def __init__(self, **kwargs):
self.ticket_vol = "kerberos-data"
self.secret_name = "statesecret"
def inject_kerberos(self, kube_resources):
for r in kube_resources:
if r["kind"] == "Job":
for c in r["spec"]["template"]["spec"]["ini... |
"""Some helper functions for test assertions"""
def assert_lists_equal(left, right):
message = "Lists are not equal; {0}!={1}".format(left, right)
assert len(left) == len(right), message
for i, _ in enumerate(left):
item_message = (message +
"\n; item {0} doesn't match {1}!={2}".format(i... |
products = {
# 'Basil Hayden\'s 10 Year': '016679',
'Blade and Bow 22 Year': '016834',
'Blantons': '016850',
'Blantons Gold Label': '016841',
'Booker\'s': '016906',
'Buffalo Trace': '018006',
# 'Buffalo Trace Experimental': '0953565',
# 'Eagle Rare': '017766',
'Eagle Rare 17yr': '017... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'List[List[int]]':
return self.hasPathSum(root, sum, sum, 0)
def hasPathS... |
#
# PySNMP MIB module NETSERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSERVER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
'''2. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30} '''
original_dict = {0: 10, 1: 20}
original_dict[2] = 30
print(original_dict) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head):
pre, slow, fast = None, head, head
while fast and fast.next:
pre, slow, fast = slow, slow.next, fast.next.next... |
# Class method return
# EXPECTED OUTPUT:
# case4.py: MyClass.hash -> dict
# case4.py: MyClass.get_hash() -> {}
class MyClass:
def __init__(self):
self.hash = {}
def get_hash(self):
return self.hash
|
# https://leetcode.com/problems/factorial-trailing-zeroes/
# https://practice.geeksforgeeks.org/problems/trailing-zeroes-in-factorial5134/1
class Solution:
def trailingZeroes(self, N):
j = 5
ans = 0
while j<=N:
ans = ans + N//j
j = j*5
return ans |
# train and classify variations
class ReadDepthLogisticClassifier (object):
'''
build a classifier using local read depth data with 2 possible labels
'''
def __init__( self, fasta, read_length ):
'''
@fasta: ProbabilisticFasta
@read_length: determines how local the features will be (i.... |
class Jumble(object):
def __init__(self):
self.dict = self.create_dict()
def create_dict(self):
f = open('/usr/share/dict/words', 'r')
sortedict = {}
for word in f:
word = word.strip().lower()
sort = ''.join(sorted(word))
sortedict[sort] = wor... |
class Task:
def __init__(self, robot):
self.robot = robot
def warmup(self):
pass
def run(self, input):
pass
def cooldown(self):
pass
def mock(self, input):
return "this is a test"
|
#!usr/bin/python3
#simple fizzbuzz solution
# Author: @fr4nkl1n-1k3h
for num in range(101):
if n%5 == 0 and n%3 == 0:
print('fizzbuzz',num,end="/n")
elif n%5 == 0:
print('buzz',num,end=" ")
elif n%3 == 0:
print('fizz',num, end=" ")
else:
print(num, end=" ")
print("Simpl... |
__title__ = "betfairlightweight"
__description__ = "Lightweight python wrapper for Betfair API-NG"
__url__ = "https://github.com/liampauling/betfair"
__version__ = "2.7.2"
__author__ = "Liam Pauling"
__license__ = "MIT"
|
class Operand:
def add(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
def subtract(self, x, y):
return x - y
def divide(self, x, y):
if y == 0:
return 0
return x / y |
def coding_problem_50(tree):
"""
Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node
is one of '+', '-', '*' or '/'. Given the root to such a tree, write a function to evaluate it.
For example, given the following tree:
*
/ \
... |
__version__ = "6.7.0"
__title__ = "slims-python-api"
__description__ = "A python api for SLims."
__uri__ = "http://www.genohm.com"
__author__ = "Genohm"
__email__ = "support@genohm.com"
__license__ = "TODO"
__copyright__ = "Copyright (c) 2016 Genohm"
|
NEGATIVE_COLLECTION_FIDS = set(
(
"88513394757c43089cd44f817f16ca05", # Khadija Project Research Data
"45602a9bb6c04a179a2657e56ed3a310", # Mozambique Persons of Interest (2015)
"zz_occrp_pdi", # Persona de Interes (2014)
"ch_seco_sanctions", # Swiss SECO Sanctions
"inter... |
class ClientException(Exception):
pass
class ServerException(Exception):
pass
class BadRequestError(ServerException):
pass
class UnauthorizedError(ServerException):
pass
class NotFoundError(ServerException):
pass
class UnprocessableError(ServerException):
pass
class InternalServerErr... |
class DealResult(object):
'''
Details of a deal that has taken place.
'''
def __init__(self):
self.proposer = None
self.proposee = None
self.properties_transferred_to_proposer = []
self.properties_transferred_to_proposee = []
self.cash_transferred_from_proposer_t... |
#! /usr/bin/env python3
"""This module defines constants needed for test package.
"""
__all__ = [
'NEXT_WAIT',
'ASYNC_TIME',
]
__version__ = '1.0.0.1'
__author__ = 'Midhun C Nair <midhunch@gmail.com>'
__maintainers__ = [
'Midhun C Nair <midhunch@gmail.com>',
]
NEXT_WAIT = .5
ASYNC_TIME = 2
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 01:22:29 2018
@author: syenpark
"""
balance = 4773
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
def foo(b, a, ii):
for i in range(12):
minimumMonthlyPayment = ii*10
monthlyUnpaidBalance = b ... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=42):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Óla {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
de... |
'''
Full write up is here! https://devclass.io/climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
**Example 1**
`Input: n = 2`
`Output: 2`
_Explanation_
There are two ways to climb to ... |
"""DEPRECATED: Please use the sources in `@rules_foreign_cc//foreign_cc/...`"""
# buildifier: disable=bzl-visibility
load(
"//foreign_cc/private:detect_root.bzl",
_detect_root = "detect_root",
_filter_containing_dirs_from_inputs = "filter_containing_dirs_from_inputs",
)
load("//tools/build_defs:deprecation... |
""" All exceptions used by this library """
class StopSession(Exception):
""" Raised to request an exit the main console loop """
pass
class UnknownCommandError(Exception):
""" Raised when attempting to use an unknown shell command """
pass
class WrongNumberOfArgumentsError(Exception):
""" Rai... |
STATUS = {
'no_content': ('No content, check the request body', 204),
'unprocessable_entity': ('Unprocessable entity, check the request attributes', 422)
}
def missing_attributes(document, attributes):
for attribute in attributes:
if attribute not in document:
return True
return F... |
# This module defines many standard colors that should be useful.
# These colors should be exactly the same as the ones defined in
# vtkNamedColors.h.
# Whites
antique_white = (0.9804, 0.9216, 0.8431)
azure = (0.9412, 1.0000, 1.0000)
bisque = (1.0000, 0.8941, 0.7686)
blanched_almond = (1.0000, 0.9216, 0.8039)
cornsil... |
class Course:
def __init__(self, records: dict = None):
self.id: int = records.get('Id')
self.name: str = records.get('CourseName')
self.about: str = records.get('About')
self.about_exam: str = records.get('About Exam')
self.site: str = records.get('Site')
|
plugin_name = "获取大写字符"
plugin_version = "v1.1"
plugin_author = "1me"
plugin_time = "20200509"
plugin_test_in="Abcd,W =="
plugin_test_out="None"
plugin_info = '''
获取输入字符中的大写字符
'''
def run(ciphertext):
mm=""
for i in ciphertext:
if i.isupper():
mm+=i
return mm |
# list(map(int, input().split()))
# int(input())
def main(*args):
X, Y, A, B = args # *A, +B
# 何回までは倍,倍にして行った方が効率がよいのかの境目を求める.
border = 0
while X < Y:
add = X * (A-1)
if add < B: # Bを加えるよりも小さくて済む場合
X += add
border += 1
else:
keikenchi =... |
seconds = int(input("Enter number of seconds:"))
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
print(f"{days} day(s), {hours} hour(s), {minutes} minute(s), and {seconds} second(s).") |
"""
InvenTree API version information
"""
# InvenTree API version
INVENTREE_API_VERSION = 43
"""
Increment this API version number whenever there is a significant change to the API that any clients need to know about
v43 -> 2022-04-26 : https://github.com/inventree/InvenTree/pull/2875
- Adds API detail endpoint... |
# Interval List Intersections
class Solution:
def intervalIntersection(self, firstList, secondList):
fl, sl = len(firstList), len(secondList)
fi, si = 0, 0
inter = []
while fi < fl and si < sl:
f, s = firstList[fi], secondList[si]
if s[0] <= f[1] <= s[1]:
... |
"""
Write a function to calculate the nth Fibonacci number.
Fibonacci numbers are a series of numbers in which each number is the sum of the
two preceding numbers. First few Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, …
Mathematically we can define the Fibonacci numbers as:
Fib(n) = Fib(n-1) + Fib(n-2), for n > 1
G... |
class InvalidParameter:
def __init__(self, reason: str):
self.reason = reason
|
RESERVED_SUBSTITUTIONS = {
0x1D455: 0x210E, 0x1D49D: 0x212C, 0x1D4A0: 0x2130, 0x1D4A1: 0x2131,
0x1D4A3: 0x210B, 0x1D4A4: 0x2110, 0x1D4A7: 0x2112, 0x1D4A8: 0x2133,
0x1D4AD: 0x211B, 0x1D4BA: 0x212F, 0x1D4BC: 0x210A, 0x1D4C4: 0x2134,
0x1D506: 0x212D, 0x1D50B: 0x210C, 0x1D50C: 0x2111, 0x1D515: 0x211C,
0... |
class Solution:
# @param A : tuple of integers
# @return an integer
def maxProduct(self, A):
m = -1
for i in range(len(A)):
p = A[i]
if p > m:
m = p
for j in range(i+1, len(A)):
a = A[i+1:j]
for k in a:
... |
#a sample object
class animal:
#properties - details
size = 0
age = 0
color = ""
gender = ""
breed = ""
#actions
def __init__(self, size, age, color, gender, breed):
self.size = int(size)
self.age = int(age)
self.color = str(color)
self.gender = str(gende... |
grocery = ["Sugar", "Pizza", "Ice-Cream", 100]
print(grocery)
print(grocery[1])
numbers = [2, 5, 6, 9, 4]
print(numbers)
print(numbers[3])
print(numbers[0:4])
print(numbers[1:3])
print(numbers[::1])
print("\n")
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers.append(99)
print("\t", numbers)
num... |
#!/usr/bin/env python3
# File listtree.py (2.x + 3.x)
class ListTree:
"""
Mix-in that returns an __str__ trace of the entire class and all
its object's attrs at and above self; run by print(), str() returns
constructed string; uses __X attr names to avoid impacting clients;
recurses to superclasse... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'target_defaults': {
'conditions': [
['use_x11 == 1', {
'include_dirs': [
... |
{ 'application':{ 'type':'Application',
'name':'Test Sounds',
'backgrounds':
[
{ 'type':'Background',
'name':'Test Sounds',
'title':'Test Sounds',
'position':( 5, 5 ),
'size':( 300, 200 ),
'menubar':
{
'type':'MenuBar',
'menus':
[
{... |
class WorksharingDisplaySettings(Element,IDisposable):
"""
WorksharingDisplaySettings controls how elements will appear when they are
displayed in any of the worksharing display modes.
"""
def CanUserHaveOverrides(self,username):
"""
CanUserHaveOverrides(self: WorksharingDisplaySettings,username: s... |
# * ex5 - Faça um algoritimo que leia nome e idade de 10 pessoas, calcule a média das idades e quantas pessoas são maiores de 18 anos.
i = 1
maiores = media = 0
while i <= 10:
idade = int(input('Insira a idade: '))
if idade >= 18:
maiores += 1
media += idade
i += 1
print(f'A media das idades ... |
# Para mexer com imagens deve-se usar o formato de bytes, por isso usa-se rb e não apenas r
with open('test.png', 'rb') as rf:
with open('test_copy.png', 'wb') as wf:
for line in rf:
wf.write(line)
|
"""
Unique Paths
Find the unique paths in a matrix starting from the upper left corner and ending in the bottom right corner.
=========================================
Dynamic programming (looking from the left and up neighbour), but this is a slower solution, see the next one.
Time Complexity: O(N*M)
Spac... |
"""dict-related utility functions."""
def get_priority_elem_in_set(obj_set, priority_list):
"""Returns the highest priority element in a set.
The set will be searched for objects in the order they appear in the
priority list, and the first one to be found will be returned. None is
returned if no such... |
'''
Date: 2021-06-24 10:56:59
LastEditors: Liuliang
LastEditTime: 2021-06-24 11:26:06
Description:
'''
class Node():
def __init__(self,item):
self.item = item
self.next = None
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a.item)
print(a.next.item)
print(b.next.item)
print(c.ne... |
n=input()
words=input()
words=words.lower()
lst=[]
for i in words:
if i not in lst:
lst.append(i)
print("YES") if len(lst)==26 else print("NO") |
pkgname = "libexecinfo"
version = "1.1"
revision = 0
build_style = "gnu_makefile"
make_build_args = ["PREFIX=/usr"]
short_desc = "BSD licensed clone of the GNU libc backtrace facility"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-2-Clause"
homepage = "http://www.freshports.org/devel/libexecinfo"
distfiles ... |
# -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'python-troveclient'
copyright = u'2012, OpenStack Foundation'
exclude_trees = []
pygments_style = 'sphinx'... |
#Excersie 1.1
str1 = "JohnDipPeta"
newstr1 = list(str1)
output = None
for i in range (0,len(newstr1)):
if(newstr1[i]=="D" and newstr1[i+1]=='i' and newstr1[i+2]=='p'):
output = newstr1[i]+ newstr1[i+1]+newstr1[i+2]
print(output)
#Excersie 2
#Given 2 strings, s1 and s2, create a new string by appending s2 in the mid... |
# Copyright (c) 2017 Dustin Doloff
# Licensed under Apache License v2.0
load(
"//actions:actions.bzl",
"stamp_file",
)
load(
"//assert:assert.bzl",
"assert_files_equal",
)
load(
"//rules:rules.bzl",
"generate_file",
"zip_files",
"zip_runfiles",
)
def run_all_tests():
test_generate_... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
v, h = 0, 0
for move in moves:
if move == 'U':
v += 1
elif move == 'D':
v -= ... |
#%%
"""
- Search in Rotated Sorted Array II
- https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
- Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found... |
expected_output={
"replicate_oce": {
"0x7F9E40C590C8": {
"uid": 6889
},
"0x7F9E40C59340": {
"uid": 6888
}
}
}
|
# Return lines from a file
def getFileLines(file):
f = open(file, "r")
lines = f.readlines()
f.close
return lines |
expected_output = {
"channel_assignment": {
"chan_assn_mode": "AUTO",
"chan_upd_int": "12 Hours",
"anchor_time_hour": 7,
"channel_update_contribution" : {
"channel_noise": "Enable",
"channel_interference": "Enable",
"channel_load": "Disable",
... |
# Example: list media files and save any with the name `dog` in file name
media_list = api.get_media_files()
for media in media_list:
if 'dog' in media['mediaName'].lower():
stream, content_type = api.download_media_file(media['mediaName'])
with io.open(media['mediaName'], 'wb') as file:
... |
input = """
a1:- not b1.
b1:- not a1.
a2:- not b2.
b2:- not a2.
a3:- not b3.
b3:- not a3.
"""
output = """
{a1, a2, a3}
{a1, a2, b3}
{a1, a3, b2}
{a1, b2, b3}
{a2, a3, b1}
{a2, b1, b3}
{a3, b1, b2}
{b1, b2, b3}
"""
|
def de(fobj, bounds, mut=0.8, crossp=0.7, popsize=20, its=1000):
dimensions = len(bounds)
pop = np.random.rand(popsize, dimensions)
min_b, max_b = np.asarray(bounds).T
diff = np.fabs(min_b - max_b)
pop_denorm = min_b + pop * diff
fitness = np.asarray([fobj(ind) for ind in pop_denorm])
best_idx = np.argmin(fitness)... |
"""
File: caesar.py
Name: Jennifer Chueh
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphab... |
#This program is for practicing lists
#Take a list, say for example this one:
#a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements of the list that are less than 5.
a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = len(a)
new1 = []
print ("Number of elements in a is %d" %b)
for i in ... |
"""
Author: Rayla Kurosaki
File: test_linear_algebra.py
Description:
"""
if __name__ == '__main__':
pass
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 10:31:58 2020
@author: Administrator
"""
"""
给定a,b两个文件,各存放50亿个url,每个url各占64B,内存限制是4GB,请找出a,b两个文件共同的url.
"""
"""
解决思路:
由于每个url需要占64B,所以50亿个url占用的空间大小为50亿*64=5GB*64=320G.由于内存大小只有4GB,因此不可能一次性把所有
的url都加载到内存中处理.对于这个类型的题目,一般都需要使用分治法,即把一个文件中url按照某一特征分成多个文件,使得每... |
a = [1,2,3]
b = [4,5,6]
print(a+b)
print(a)
print(a*2)
print(a*3)
print(b*2)
print(b*3)
print(1 in a)
print(2 in a)
print(3 in a)
print(4 in a) |
# encoding: utf-8
__all__ = ['LoggingTransport']
log = __import__('logging').getLogger(__name__)
class LoggingTransport(object):
__slots__ = ('ephemeral', 'log')
def __init__(self, config):
self.log = log if 'name' not in config else __import__('logging').getLogger(config.name)
def s... |
## 2. Syntax Errors ##
def first_elts(input_lst):
elts = []
for each in input_lst:
elts.append(each)
return elts
animals = [["dog","cat","rabbit"],["turtle","snake"], ["sloth","penguin","bird"]]
first_animal = first_elts(animals)
print(first_animal)
## 4. TypeError and ValueError ##
forty_two =... |
# 417.太平洋大西洋的水流问题(Medium)
# 给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。
# “太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
# 规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
# 请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
# 提示:
# 输出坐标的顺序不重要
# m 和 n 都小于150
# 给定下面的 5x5 矩阵:
# 太平洋 ~ ~ ~ ~ ~
# ~ 1 2 2 3 (5) *
# ~ ... |
'''
Assignment: Create functions that serialize/deserialize objects to/from a stream of data. Additionally, create a function
that retrieves a given value from the stream of data.
All objects have a flat structure that is described by a schema. Objects needn't have all fields, in such a case, the default
value is assu... |
async def run(plugin, ctx):
plugin.db.configs.update(ctx.guild.id, "persist", True)
await ctx.send(plugin.t(ctx.guild, "enabled_module_no_channel", _emote="YES", module="Persist")) |
def attation(proto_layers, layer_infos, edges_info, attation_num):
for proto_index, proto_layer in enumerate(proto_layers):
for key, layer_info in layer_infos.items():
if layer_info['name'] == proto_layer.name:
cur_layer_info = layer_info
break
cur_data = layer_info['data... |
class Solution:
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
if x > y: x, y = y, x
gcd = self.gcd(x, y)
if gcd == 0: return z == 0
return z % gcd == 0 and z <= x + y
def gcd(self, ... |
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_bst_with_bound(root, min, max):
# empty node or empty tree
if root is None:
return True
# if the value of node is out of bound
if root.data < m... |
class AccessDenied(ValueError):
"""
Raised when invalid credentials are provided, or tokens have expired.
"""
pass
class InvalidPrivateKeyFormat(ValueError):
"""
Raised when provided private key has invalid format.
"""
pass
|
def main():
n, m = map(int, input().split())
if n < m:
print(f"Dr. Chaz will have {m-n} piece{'' if m-n == 1 else 's'} of chicken left over!")
else:
print(f"Dr. Chaz needs {n-m} more piece{'' if n-m == 1 else 's'} of chicken!")
return
if __name__ == "__main__":
main()
|
"""This package contains a template class for Problems and implementations of
said class.
"""
|
data = int(input("Num : "))
max = 12
min = 1
while min<=max:
print("%d * %d = %d" % (data,min,data*min))
min+=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.