content
stringlengths 7
1.05M
|
---|
instr = [
"""Digit-symbol coding, part 1 (practice)
At the top of the screen you will see a row of symbols and
a row of numbers. Each symbol is paired with the number below
it.
You will also see one symbol and one number in the middle of
the screen. Your task is to decide whether they make a
correct pair. Respond 'Yes' (using the LEFT arrow key) if
they do and 'No' (using the RIGHT arrow key) if they
don't.
Press the SPACE BAR to begin.""",
"""Digit-symbol coding, part 2 (real test)
Now you will perform the real test. It is the same as the
practice, except there are more trials, and there is no
feedback. Try to complete as many trials as you can within
90 seconds without making mistakes.
Press the SPACE BAR to begin.""",
"""Digit-symbol coding, part 3 (real test)
Now you will perform the test again. It is exactly the same
as the last time. Try to complete as many trials as you can
within 90 seconds without making mistakes.
Press the SPACE BAR to begin.""",
"Correct! :)",
"Incorrect! :(",
]
|
class Tile():
def __init__(self,bomb=False):
self.bomb = False
self.revealed = False
self.nearBombs = 0
def isBomb(self):
return self.bomb
def isRevealed(self):
return self.revealed
def setBomb(self):
self.bomb=True
def setNearBombs(self,near = 0):
self.nearBombs = near
def getNearBombs(self):
return self.nearBombs
def revealTile(self):
self.revealed = True
def printer(self):
if self.revealed:
if(self.bomb):
return "x"
if self.nearBombs == 0:
return " "
else:
return str(self.nearBombs)
else:
return "#"
def debugPrinter(self):
if self.bomb:
return "x"
if self.nearBombs == 0:
return " "
else:
return str(self.nearBombs)
|
OCTICON_FILE = """
<svg class="octicon octicon-file" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06zM2 1.75C2 .784 2.784 0 3.75 0h5.086c.464 0 .909.184 1.237.513l3.414 3.414c.329.328.513.773.513 1.237v8.086A1.75 1.75 0 0112.25 15h-8.5A1.75 1.75 0 012 13.25V1.75z"></path></svg>
"""
|
### CONFIGS ###
dataset = 'cora'
model = 'VGAE'
input_dim = 10
hidden1_dim = 32
hidden2_dim = 16
use_feature = True
num_epoch = 2000
learning_rate = 0.01
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: [email protected]
*
"""
a=[*open(0)][1].split()
a,b=[a.count('100'),a.count('200')]
print('YNEOS'[(a+2*b)%2 or b%2 and a<2::2])
|
# clut.py.
#
# clut.py Teletext colour lookup table
# Maintains colour lookups
#
# Copyright (c) 2020 Peter Kwan
#
# 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, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# This holds the colour lookup tables read in by packet 28 etc.
# I think we have four CLUTs 0 to 3. Here is what the standard says:
## 8 background full intensity colours:
## Magenta, Cyan, White. Black, Red, Green, Yellow, Blue,
## 7 foreground full intensity colours:
## Cyan, White. Red, Green, Yellow, Blue, Magenta,
## Invoked as spacing attributes via codes in packets X/0 to X/25.
## Black foreground: Invoked as a spacing attribute via codes in packets X/0
## to X/25.
## 32 colours per page. The Colour Map contains four CLUTs
## (numbered 0 - 3), each of 8 entries. Each entry has a four bit resolution for
## the RGB components, subclause 12.4.
## Presentation
## Level
## 1 1.5 2.5 3.5
## { { ~ ~
## ~ ~ ~ ~
## { { ~ ~
## { { ~ ~
## Colour Definition
## CLUT 0 defaults to the full intensity colours used as spacing colour
## attributes at Levels 1 and 1.5.
## CLUT 1, entry 0 is defined to be transparent. CLUT 1, entries 1 to 7 default
## to half intensity versions of CLUT 0, entries 1 to 7.
## CLUTs 2 and 3 have the default values specified in subclause 12.4. CLUTs
## 2 and 3 can be defined for a particular page by packet X/28/0 Format 1, or
## for all pages in magazine M by packet M/29/0.
## Colour Selection
## CLUT 0, entries 1 to 7 are selectable directly by the Level 1 data as
## spacing attributes. CLUTs 0 to 3 are selectable via packets 26 or objects
## as non-spacing attributes.
## The foreground and background colour codes on the Level 1 page may be
## used to select colours from other parts of the Colour Map. Different CLUTs
## may be selected for both foreground and background colours.
## This mapping information is transmitted in packet X/28/0 Format 1 for the
## associated page and in packet M/29/0 for all pages in magazine M.
## With the exception of entry 0 in CLUT 1 (transparent), CLUTs 0 and 1 can
## be redefined for a particular page by packet X/28/4, or
##
class Clut:
def __init__(self):
print ("Clut loaded")
self.clut0 = [0] * 8 # Default full intensity colours
self.clut1 = [0] * 8 # default half intensity colours
self.clut2 = [0] * 8
self.clut3 = [0] * 8
# set defaults
self.reset()
# Used by X26/0 to swap entire cluts
# @param colour - Colour index 0..7
# @param remap - Remap 0..7
# @param foreground - True for foreground coilour, or False for background
# @return - Colour string for tkinter. eg. 'black' or '#000'
def RemapColourTable(self, colourIndex, remap, foreground):
if type(colourIndex) != int:
print('[RemapColourTable] colourIndex is not an integer' + colourIndex + ". foreground = " +str(foreground))
clutIndex = 0
if foreground:
if remap>4:
clutIndex = 2
elif remap<3:
clutIndex = 0
else:
clutIndex = 1
else: # background
if remap < 3:
clutIndex = remap
elif remap == 3 or remap == 5:
clutIndex = 1
elif remap == 4 or remap == 6:
clutIndex = 2
else:
clutIndex = 3
return self.get_value(clutIndex, colourIndex)
def reset(self): # To values from table 12.4
# CLUT 0 full intensity
self.clut0[0] = '#000' # black
self.clut0[1] = '#f00' # red
self.clut0[2] = '#0f0' # green
self.clut0[3] = '#ff0' # yellow
self.clut0[4] = '#00f' # blue
self.clut0[5] = '#f0f' # magenta
self.clut0[6] = '#0ff' # cyan
self.clut0[7] = '#fff' # white
# CLUT 1 half intensity
self.clut1[0] = '#000' # transparent
self.clut1[1] = '#700' # half red
self.clut1[2] = '#070' # half green
self.clut1[3] = '#770' # half yellow
self.clut1[4] = '#007' # half blue
self.clut1[5] = '#707' # half magenta
self.clut1[6] = '#077' # half cyan
self.clut1[7] = '#777' # half white
# CLUT 2 lovely colours
self.clut2[0] = '#f05' # crimsonish
self.clut2[1] = '#f70' # orangish
self.clut2[2] = '#0f7' # blueish green
self.clut2[3] = '#ffb' # pale yellow
self.clut2[4] = '#0ca' # cyanish
self.clut2[5] = '#500' # dark red
self.clut2[6] = '#652' # hint of a tint of runny poo
self.clut2[7] = '#c77' # gammon
# CLUT 3 more lovely colours
self.clut3[0] = '#333' # pastel black
self.clut3[1] = '#f77' # pastel red
self.clut3[2] = '#7f7' # pastel green
self.clut3[3] = '#ff7' # pastel yellow
self.clut3[4] = '#77f' # pastel blue
self.clut3[5] = '#f7f' # pastel magenta
self.clut3[6] = '#7ff' # pastel cyan
self.clut3[7] = '#ddd' # pastel white
# set a value in a particular clut
# Get the colour from a particular clut
# Probably want to record which cluts are selected
# Lots of stuff
# @param colour - 12 bit web colour string eg. '#1ab'
# @param clut_index CLUT index 0 to 3
# @param clr_index - 0..7 colour index
def set_value(self, colour, clut_index, clr_index):
clr_index = clr_index % 8 # need to trap this a bit better. This is masking a problem
clut_index = clut_index % 4
if clut_index==0:
self.clut0[clr_index] = colour;
if clut_index==1:
self.clut1[clr_index] = colour;
if clut_index==2:
self.clut2[clr_index] = colour;
if clut_index==3:
self.clut3[clr_index] = colour;
print("clut value: clut" + str(clut_index) + " set[" + str(clr_index) + '] = ' + colour)
# @return colour - 12 bit web colour string eg. '#1ab'
# @param clut_index CLUT index 0 to 3
# @param clr_index - 0..7 colour index
def get_value(self, clut_index, clr_index):
clut_index = clut_index % 4
clr_index = clr_index % 8
if clut_index == 0:
return self.clut0[clr_index]
if clut_index == 1:
return self.clut1[clr_index]
if clut_index == 2:
return self.clut2[clr_index]
if clut_index == 3:
return self.clut3[clr_index]
return 0 # just in case!
# debug dump the clut contents
def dump(self):
print("[Dump] CLUT values")
for i in range(8):
print(self.clut0[i] + ', ', end='')
print()
for i in range(8):
print(self.clut1[i] + ', ', end='')
print()
for i in range(8):
print(self.clut2[i] + ', ', end='')
print()
for i in range(8):
print(self.clut3[i] + ', ', end='')
print()
clut = Clut()
|
# record all kinds of type
# pm type
LINKEDIN_TYPE = 1
PM_LANG_ITEM_TYPE = 0
PM_CITY_ITEM_TYPE = 1
PM_SERVICE_ITEM_TYPE = 2
REALTOR_MESSAGE_TYPE = 3
#quiz type
PM_QUIZ_TYPE = 0
#pm inspection report note type
PM_INSPECTION_REPORT_TYPE = 3
PM_EXPENSE_TYPE = 4
#user progress bar
USER_PROGRESS_BAR_TYPE = 0
HOME_PROGRESS_BAR_TYPE = 1
#pm bill incomes type
PM_INCOME_TYPE = 0
#picture type
PIC_AVATAR_TYPE = 0
PIC_URL_TYPE = 1
#file type
FILE_S3_TYPE = 0
#status log type
STATUS_LOG_USER_TYPE = 0
#extra file type
EXTRA_USER_INSPECTION_REPORT_TYPE = 0
EXTRA_USER_CONTRACT_TYEP = 1
#submit type
EXPENSE_SUBMIT_TYPE = 0
# census report type
CENSUS_REPORT_TYPE_STATE = 0
CENSUS_REPORT_TYPE_MSA = 1
CENSUS_REPORT_TYPE_COUNTY = 2
CENSUS_REPORT_TYPE_CITY = 3
CENSUS_REPORT_TYPE_TOWN = 4
CENSUS_REPORT_TYPE_NEIGHBORHOOD = 5
CENSUS_REPORT_TYPE_ZIPCODE = 6
|
if request.isInit:
lastVal = 0
else:
if lastVal == 0:
lastVal = 1
else:
lastVal = (lastVal << 1) & 0xFFFFFFFF
request.value = lastVal
|
# Copyright 2009, UCAR/Unidata
# Enumerate the kinds of Sax Events received by the SaxEventHandler
STARTDOCUMENT = 1
ENDDOCUMENT = 2
STARTELEMENT = 3
ENDELEMENT = 4
ATTRIBUTE = 5
CHARACTERS = 6
# Define printable output
_MAP = {
STARTDOCUMENT: "STARTDOCUMENT",
ENDDOCUMENT: "ENDDOCUMENT",
STARTELEMENT: "STARTELEMENT",
ENDELEMENT: "ENDELEMENT",
ATTRIBUTE: "ATTRIBUTE",
CHARACTERS: "CHARACTERS"
}
def tostring(t) :
return _MAP[t]
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Defines some constants used in chemical calculations.
"""
# multiplicative conversions
N_A = 6.02214129e23 # particles per mol
KCAL_PER_MOL_TO_J_PER_MOLECULE = 6.947695e-21
HARTREE_TO_KCAL_PER_MOL = 627.509474
HARTREE_TO_J_PER_MOL = 2625499.63922
HARTREE_TO_KJ_PER_MOL = 2625.49963922
HARTREE_TO_PER_CM = 219474.63
J_PER_MOL_TO_PER_CM = 0.08359347178
CAL_TO_J = 4.184
HARTREE_TO_J = 4.3597443380807824e-18 # HARTREE_TO_J_PER_MOL / N_A
J_TO_HARTREE = 2.293712480489655e17 # 1.0 / HARTREE_TO_J
M_TO_ANGSTROM = 1e10
ANGSTROM_TO_M = 1e-10
# physical constants
C_CM_PER_S = 2.9979245800e10
C_M_PER_S = 2.9979245800e8
HBAR_J_S = 1.054571800e-34 # note this is h/2Pi
H_J_S = 6.62607015e-34
KB_J_PER_K = 1.3806488e-23
|
def select_k_items(stream, n, k):
reservoir = []
for i in range(k):
reservoir.append(stream[i])
if __name__ == '__main__':
stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = len(stream)
k = 5
select_k_items(stream, n, k)
|
#! python3
"""A printing shop runs 16 batches (jobs) every week and each batch requires a
sheet of special colour-proofing paper of size A5.
Every Monday morning, the foreman opens a new envelope, containing a large
sheet of the special paper with size A1.
He proceeds to cut it in half, thus getting two sheets of size A2.
Then he cuts one of them in half to get two sheets of size A3 and so on until
he obtains the A5-size sheet needed for the first batch of the week.
All the unused sheets are placed back in the envelope.
At the beginning of each subsequent batch, he takes from the envelope one sheet
of paper at random. If it is of size A5, he uses it. If it is larger,
he repeats the 'cut-in-half' procedure until he has what he needs and any
remaining sheets are always placed back in the envelope.
Excluding the first and last batch of the week, find the expected number of
times (during each week) that the foreman finds a single sheet of paper
in the envelope."""
def choose(sheets, chosen):
new = sheets[:]
new.remove(chosen)
if chosen != 5:
new.extend(range(chosen + 1, 6))
return new
def f(sheets):
if sheets == [5]:
return 0
total = len(sheets)
out = total == 1
for i in set(sheets):
out += (sheets.count(i) / total) * f(choose(sheets, i))
return out
value = f([2, 3, 4, 5])
print(round(value, 6))
|
class Solution:
def majorityElement(self, nums: list[int]) -> list[int]:
candidate1, candidate2 = 0, 0
count1, count2 = 0, 0
for num in nums:
if candidate1 == num:
count1 += 1
continue
if candidate2 == num:
count2 += 1
continue
# NOTE: count checks must come AFTER candidate == num checks
# to ensure we're not adding the count of an already existing
# candidate to the a new number instead.
if count1 == 0:
candidate1 = num
count1 += 1
continue
if count2 == 0:
candidate2 = num
count2 += 1
continue
# If we have reached this point,
# we have found 3 different items, which we can count out.
count1 -= 1
count2 -= 1
result = set()
for candidate in (candidate1, candidate2):
if nums.count(candidate) > len(nums) // 3:
result.add(candidate)
return list(result)
tests = [
(
([3, 2, 3],),
[3],
),
(
([1],),
[1],
),
(
([1, 2],),
[1, 2],
),
(
([2, 2],),
[2],
),
(
([2, 1, 1, 3, 1, 4, 5, 6],),
[1],
),
]
|
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def GetNumSuffixes(start_state):
"""Compute number of minimal suffixes automaton accepts from each state.
For each state reachable from given state, compute number of paths in the
automaton that start from that state, end in the accepting state and do not
pass through accepting states in between.
It is assumed that there are no cyclic paths going entirely through
non-accepting states.
Args:
start_state: start state (as defined in dfa_parser.py).
Returns:
Dictionary from reachable states to numbers of suffixes.
"""
num_suffixes = {}
def ComputeNumSuffixes(state):
if state in num_suffixes:
return
if state.is_accepting:
num_suffixes[state] = 1
# Even though the state itself is accepting, there may be more reachable
# states behind it.
for t in state.forward_transitions.values():
ComputeNumSuffixes(t.to_state)
return
if state.any_byte:
next_state = state.forward_transitions[0].to_state
ComputeNumSuffixes(next_state)
num_suffixes[state] = num_suffixes[next_state]
return
count = 0
for t in state.forward_transitions.values():
ComputeNumSuffixes(t.to_state)
count += num_suffixes[t.to_state]
num_suffixes[state] = count
ComputeNumSuffixes(start_state)
return num_suffixes
def TraverseTree(state, final_callback, prefix, anyfield=0x01):
if state.is_accepting:
final_callback(prefix)
return
if state.any_byte:
assert anyfield < 256
TraverseTree(
state.forward_transitions[0].to_state,
final_callback,
prefix + [anyfield],
anyfield=0 if anyfield == 0 else anyfield + 0x11)
# We add 0x11 each time to get sequence 01 12 23 etc.
# TODO(shcherbina): change it to much nicer 0x22 once
# http://code.google.com/p/nativeclient/issues/detail?id=3164 is fixed
# (right now we want to keep immediates small to avoid problem with sign
# extension).
else:
for byte, t in state.forward_transitions.iteritems():
TraverseTree(
t.to_state,
final_callback,
prefix + [byte],
anyfield)
def CreateTraversalTasks(states, initial_state):
"""Create list of DFA traversal subtasks (handy for parallelization).
Note that unlike TraverseTree function, which stops on accepting states,
here we go past initial state even when it's accepted.
Args:
initial_state: initial state of the automaton.
Returns:
List of (prefix, state_index) pairs, where prefix is list of bytes.
"""
assert not initial_state.any_byte
num_suffixes = GetNumSuffixes(initial_state)
# Split by first three bytes.
tasks = []
for byte1, t1 in sorted(initial_state.forward_transitions.items()):
state1 = t1.to_state
if state1.any_byte or state1.is_accepting or num_suffixes[state1] < 10**4:
tasks.append(([byte1], states.index(state1)))
continue
for byte2, t2 in sorted(state1.forward_transitions.items()):
state2 = t2.to_state
if state2.any_byte or state2.is_accepting or num_suffixes[state2] < 10**4:
tasks.append(([byte1, byte2], states.index(state2)))
continue
for byte3, t3 in sorted(state2.forward_transitions.items()):
state3 = t3.to_state
tasks.append(([byte1, byte2, byte3], states.index(state3)))
return tasks
|
memo=[0, 1]
def fib_digits(n):
if len(memo)==2:
for i in range(2, 100001):
memo.append(memo[i-1]+memo[i-2])
num=str(memo[n])
res=[]
for i in range(0,10):
check=num.count(str(i))
if check:
res.append((check, i))
return sorted(res, reverse=True)
|
# Question 1: Write a program that asks the user to enter a string. The program should then print the following:
# a) The total number of characters in the string
# b) The string repeated 10 times
# c) The first character of the string
# d) The first three characters of the string
# e) The last three characters of the string
# f) The string backwards
# g) The seventh character of the string if the string is long enough and a message otherwise
# h) The string with its first and last characters removed
# i) The string in all caps
# j) The string with every a replaced with an e
# k) The string with every character replaced by an *
string=input("enter a string")
print(len(string))
print(string*10)
print(string[0])
print(string[0:3])
print(string[-3:])
print(string[: :-1])
if len(string) >= 7:
print(string[7])
else:
print("the string is shorter than 7 charecters")
print(string[1:-1])
print(string.upper())
print(string.replace('a', 'e'))
print('*'*len(string))
|
_base_ = [
'../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py'
]
model = dict(
backbone=dict(
type='CBSwinTransformer',
),
neck=dict(
type='CBFPN',
),
test_cfg = dict(
rcnn=dict(
score_thr=0.001,
nms=dict(type='soft_nms'),
)
)
)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
albu_train_transforms = [
dict(
type='ShiftScaleRotate',
shift_limit=0.0,
scale_limit=0.0,
rotate_limit=20,
interpolation=1,
p=0.2),
]
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='AutoAugment',
policies=[
[
dict(type='Resize',
img_scale=[(320, 320), (384, 384), (448, 448),
(512, 512), (576, 576)],
multiscale_mode='value',
keep_ratio=True)
],
[
dict(type='Resize',
img_scale=[(320, 320), (576, 576)],
multiscale_mode='value',
keep_ratio=True),
dict(type='RandomCrop',
crop_type='absolute_range',
crop_size=(320, 320),
allow_negative_crop=True),
dict(type='Resize',
img_scale=[(320, 320), (384, 384), (448, 448),
(512, 512), (576, 576)],
multiscale_mode='value',
override=True,
keep_ratio=True)
]
]),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=[(320, 320), (576, 576)],
flip=True,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
samples_per_gpu=2
data = dict(samples_per_gpu=samples_per_gpu,
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline))
optimizer = dict(lr=0.0001*(samples_per_gpu/2))
|
def test_index(man):
errors = []
G = man.writeTest()
G.addIndex("Person", "name")
G.addVertex("1", "Person", {"name": "marko", "age": "29"})
G.addVertex("2", "Person", {"name": "vadas", "age": "27"})
G.addVertex("3", "Software", {"name": "lop", "lang": "java"})
G.addVertex("4", "Person", {"name": "josh", "age": "32"})
G.addVertex("5", "Software", {"name": "ripple", "lang": "java"})
G.addVertex("6", "Person", {"name": "peter", "age": "35"})
G.addVertex("7", "Person", {"name": "marko", "age": "35"})
G.addEdge("1", "3", "created", {"weight": 0.4})
G.addEdge("1", "2", "knows", {"weight": 0.5})
G.addEdge("1", "4", "knows", {"weight": 1.0})
G.addEdge("4", "3", "created", {"weight": 0.4})
G.addEdge("6", "3", "created", {"weight": 0.2})
G.addEdge("4", "5", "created", {"weight": 1.0})
resp = G.listIndices()
found = False
for i in resp:
if i["field"] == "name" and i["label"] == "Person":
found = True
if not found:
errors.append("Expected index not found")
return errors
|
DEFAULT_CHUNK_SIZE = 1000
def chunked_iterator(qs, size=DEFAULT_CHUNK_SIZE):
qs = qs._clone()
qs.query.clear_ordering(force_empty=True)
qs.query.add_ordering('pk')
last_pk = None
empty = False
while not empty:
sub_qs = qs
if last_pk:
sub_qs = sub_qs.filter(pk__gt=last_pk)
sub_qs = sub_qs[:size]
empty = True
for o in sub_qs:
last_pk = o.pk
empty = False
yield o
|
indent = 3
key = "foo"
print('\n%s%*s' % (indent, len(key)+3, 'Hello')) # ok: variable length
print("%.*f" % (indent, 1.2345))
def myprint(x, *args):
print("%.3f %.4f %10.3f %1.*f" % (x, x, x, 3, x))
myprint(3)
|
class Admin_string_literal:
def __init__(self):
Admin_string_literal.admin_menu_string = """
Select the operation to perfrom:
1. Create a Topic
2. Remove a Topic
3. Restrict a Topic
4. Purge a Topic
5. Edit a Message
6. Delete a Message
7. See last 10 subscriber
8. See last 10 publishers
Enter your option:
"""
Admin_string_literal()
|
def max_sum_of_increasing_subseq(seq: list[int]) -> int:
"""
O(n^2) time, O(n) extra space
"""
if not seq:
return 0
max_sum = [0 for _ in seq] # the answer to the question if you have end on index i
# max sum ending on index i is seq[i] + prev biggest sum, corresponding to some j < i
for i in range(len(seq)):
for j in range(i):
if seq[j] <= seq[i]:
max_sum[i] = max(max_sum[i], max_sum[j])
max_sum[i] += seq[i]
return max(max_sum)
class IntsAndSum:
def __init__(self, ints: list[int], precomputed_sum: int = None):
self.ints: list[int] = ints
self.sum: int = precomputed_sum if precomputed_sum is not None else sum(ints)
def __repr__(self):
return f'{self.__class__.__name__}({self.ints}, sum={self.sum})'
@staticmethod
def max(*args):
return max(args, key=lambda x: x.sum)
def append(self, i: int) -> None:
self.ints.append(i)
self.sum += i
def copy(self):
return IntsAndSum(ints=self.ints.copy(), precomputed_sum=self.sum)
def max_sum_of_increasing_subseq_with_elements(seq: list[int]) -> IntsAndSum:
"""
O(n^2) time, O(n^2) extra space
"""
if not seq:
return IntsAndSum(ints=[])
max_sum = [IntsAndSum(ints=[]) for _ in seq] # the answer to the question if you have end on index i
# max sum ending on index i is seq[i] + prev biggest sum, corresponding to some j < i
for i in range(len(seq)): # loop invariant: max_sum[i] is fully computed/ constant after ith iteration
for j in range(i):
if seq[j] <= seq[i]:
max_sum[i] = IntsAndSum.max(max_sum[i], max_sum[j])
max_sum[i] = max_sum[i].copy()
max_sum[i].append(seq[i])
return IntsAndSum.max(*max_sum)
def main():
s0 = max_sum_of_increasing_subseq([]) # should be 0
s1 = max_sum_of_increasing_subseq([6, 5, 7, 2, 3, 200, 4, 5]) # should be 6+7+200 = 213
s2 = max_sum_of_increasing_subseq([3, 4, 5, 6, 20]) # should be 3+4+5+6+20 = 38
print(s0, s1, s2)
s0 = max_sum_of_increasing_subseq_with_elements([]) # should be 0
s1 = max_sum_of_increasing_subseq_with_elements([6, 5, 7, 2, 3, 200, 4, 5]) # should be 6+7+200 = 213
s2 = max_sum_of_increasing_subseq_with_elements([3, 4, 5, 6, 20]) # should be 3+4+5+6+20 = 38
print(s0)
print(s1)
print(s2)
s3 = max_sum_of_increasing_subseq([8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11]) # should be 8+12+14 = 34
l3 = max_sum_of_increasing_subseq_with_elements([8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11])
print(s3)
print(l3)
if __name__ == '__main__':
main()
|
class TextXLSError(Exception):
"""Indicates a generic textX-LS-core error."""
pass
class GenerateExtensionError(TextXLSError):
"""Indicates an error while generating an extension."""
def __init__(self, target, cmd_args):
super().__init__(
"Failed to generate the extension for '{}' with following arguments: '{}'.".format(
target, cmd_args
)
)
self.target = target
self.cmd_args = cmd_args
class GenerateSyntaxHighlightError(TextXLSError):
"""Indicates an error while generating a syntax highlighting data."""
def __init__(self, project_name, target):
super().__init__(
"Failed to generate syntax highlighting for project '{}' and target '{}'.".format(
project_name, target
)
)
self.project_name = project_name
self.target = target
class InstallTextXProjectError(TextXLSError):
"""Indicates an error while installing a textX project."""
def __init__(self, project_name, dist_location, detailed_err_msg):
super().__init__(
"Failed to install project: {} ({}).".format(project_name, dist_location)
)
self.project_name = project_name
self.dist_location = dist_location
self.detailed_err_msg = detailed_err_msg
class UninstallTextXProjectError(TextXLSError):
"""Indicates an error while uninstalling a textX project."""
def __init__(self, project_name, detailed_err_msg):
super().__init__("Failed to uninstall project: {}".format(project_name))
self.project_name = project_name
self.detailed_err_msg = detailed_err_msg
class LanguageNotRegistered(TextXLSError):
"""Indicates an error if language can't be parsed with any of registered metamodels.
"""
def __init__(self, file_name):
super().__init__(
"There are no metamodels that can parse '{}'.".format(file_name)
)
class MultipleLanguagesError(TextXLSError):
"""Indicates an error if language can be parsed with multiple registered metamodels.
"""
def __init__(self, file_name):
super().__init__(
"Multiple languages can parse '{}'. Install appropriate extension and select language id.".format(
file_name
)
)
|
class Floodfill:
"""abstract floodfill class, must specify _is_in_region() condition and
_fill() operation"""
def __init__(self):
pass
def floodfill(self, x, y):
Q = []
if not self._is_in_region(x,y):
return
Q.append([x,y])
while Q != []:
w,z = Q.pop(0)
e = w
while self._is_in_region(w-1,z):
w-=1
while self._is_in_region(e+1,z):
e+=1
for n in range(w, e+1):
self._fill(n,z)
if self._is_in_region(n,z+1):
Q.append([n,z+1])
if self._is_in_region(n,z-1):
Q.append([n,z-1])
def _is_in_region(self, x, y):
pass
def _fill(self, x, y):
pass
|
#Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
#
#You may assume no duplicates in the array.
#
#Here are few examples.
#[1,3,5,6], 5 → 2
#[1,3,5,6], 2 → 1
#[1,3,5,6], 7 → 4
#[1,3,5,6], 0 → 0
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)-1
if nums[high]<target:
return high+1
while low<high:
mid=(low+high)/2
if nums[mid]==target:
return mid
elif nums[mid]>target:
high=mid
else:
low=mid+1
return high
|
PAGES_FOLDER = 'pages'
PUBLIC_FOLDER = 'public'
STATIC_FOLDER = 'static'
TEMPLATE_NAME = 'template.mustache'
|
teisuu = 1
suuji_kous = 3
aru = 2
zenn = 0
for ai in range(suuji_kous):
zenn += teisuu*aru**ai
print(zenn)
|
# elasticmodels/tests/test_settings.py
# author: andrew young
# email: [email protected]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
ROOT_URLCONF = ["elasticmodels.urls"]
INSTALLED_APPS = ["elasticmodels"]
|
# Python - 2.7.6
Test.describe('Basic Tests')
data = [2]
Test.assert_equals(print_array(data), '2')
data = [2, 4, 5, 2]
Test.assert_equals(print_array(data), '2,4,5,2')
data = [2, 4, 5, 2]
Test.assert_equals(print_array(data), '2,4,5,2')
data = [2.0, 4.2, 5.1, 2.2]
Test.assert_equals(print_array(data), '2.0,4.2,5.1,2.2')
data = ['2', '4', '5', '2']
Test.assert_equals(print_array(data), '2,4,5,2')
data = [True, False, False]
Test.assert_equals(print_array(data), 'True,False,False')
array1 = ['hello', 'this', 'is', 'an', 'array!']
array2 = ['a', 'b', 'c', 'd', 'e!']
data = array1 + array2
Test.assert_equals(print_array(data), 'hello,this,is,an,array!,a,b,c,d,e!')
array1 = ['hello', 'this', 'is', 'an', 'array!']
array2 = [1, 2, 3, 4, 5]
data = [array1, array2]
Test.assert_equals(print_array(data), "['hello', 'this', 'is', 'an', 'array!'],[1, 2, 3, 4, 5]")
|
def result(score):
min = max = score[0]
min_count = max_count = 0
for i in score[1:]:
if i > max:
max_count += 1
max = i
if i < min:
min_count += 1
min = i
return max_count, min_count
n = input()
score = list(map(int, input().split()))
print(*result(score))
|
DEFAULT_PRAGMAS = (
"akamai-x-get-request-id",
"akamai-x-get-cache-key",
"akamai-x-get-true-cache-key",
"akamai-x-get-extracted-values",
"akamai-x-cache-on",
"akamai-x-cache-remote-on",
"akamai-x-check-cacheable",
"akamai-x-get-ssl-client-session-id",
"akamai-x-serial-no",
)
|
n1 = int(input("digite o valor em metros "))
n2 = int(input("digite o valor em metros "))
n3 = int(input("digite o valor em metros "))
r= (n1**2)+(n2**2)+(n3**2)
print(r)
|
__author__ = 'ipetrash'
if __name__ == '__main__':
def getprint(str="hello world!"):
print(str)
def decor(func):
def wrapper(*args, **kwargs):
print("1 begin: " + func.__name__)
print("Args={} kwargs={}".format(args, kwargs))
f = func(*args, **kwargs)
print("2 end: " + func.__name__ + "\n")
return f
return wrapper
def predecor(w="W"):
print(w, end=': ')
getprint()
getprint("Py!")
print()
f = decor(getprint)
f()
f("Py!")
def rgb2hex(get_rgb_func):
def wrapper(*args, **kwargs):
r, g, b = get_rgb_func(*args, **kwargs)
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
return wrapper
class RGB:
def __init__(self):
self._r = 0xff
self._g = 0xff
self._b = 0xff
def getr(self):
return self._r
def setr(self, r):
self._r = r
r = property(getr, setr)
def getg(self):
return self._g
def setg(self, g):
self._g = g
g = property(getg, setg)
def getb(self):
return self._b
def setb(self, b):
self._b = b
b = property(getb, setb)
def setrgb(self, r, g, b):
self.r, self.g, self.b = r, g, b
@rgb2hex
def getrgb(self):
return (self.r, self.g, self.b)
rgb = RGB()
print('rgb.r={}'.format(rgb.r))
rgb.setrgb(0xff, 0x1, 0xff)
print("rgb.getrgb(): %s" % rgb.getrgb())
print()
@decor
def foo(a, b):
print("{} ^ {} = {}".format(a, b, (a ** b)))
foo(2, 3)
foo(b=3, a=2)
|
'''
https://youtu.be/-xRKazHGtjU
Smarter Approach: https://youtu.be/J7S3CHFBZJA
Dynamic Programming: https://youtu.be/VQeFcG9pjJU
'''
|
def fit_index(dataset, list_variables):
""" Mapping between index and category, for categorical variables
For each (categorical) variable, create 2 dictionaries:
- index_to_categorical: from the index to the category
- categorical_to_index: from the category to the index
Parameters
----------
dataset: pandas.core.frame.DataFrame
DataFrame with (partly) categorical variables
list_variables: list(str)
List of variable names to index
Returns
-------
index: dict
For each categorical column, we have the 2 mappings: idx2cat & idx2cat
"""
index = dict()
for icol in list_variables:
if icol not in dataset.columns:
raise RuntimeError(f'{icol} not found in dataframe')
idx2cat = {ii: jj for ii, jj in enumerate(dataset.loc[:, icol].unique())}
cat2idx = {jj: ii for ii, jj in idx2cat.items()}
index[icol] = {
'index_to_categorical': idx2cat,
'categorical_to_index': cat2idx
}
return index
def map_to_or_from_index(dataset, index, type_conversion):
"""Transform categorical variables to their index
Parameters
----------
dataset: pandas.core.frame.DataFrame
DataFrame with categorical variables
index: dict
For each categorical column (dict index), we have 2 mappings:
- index_to_categorical
- categorical_to_index
Returns
-------
dataset: pandas.core.frame.DataFrame
Dataframe with the mapping & missing values
"""
for icol in set(index.keys()).intersection(dataset.columns):
dataset_init = dataset.copy()
dataset[icol] = dataset[icol].map(
lambda x: index[icol][type_conversion].get(x, None)
)
missing_index = dataset[icol].isna()
if sum(missing_index) > 0:
dataset = dataset[~missing_index]
print(
"Missing {} for {} ({} rows): {}".format(
type_conversion,
icol, sum(missing_index), set(dataset_init[missing_index][icol])
)
)
del dataset_init
return dataset
|
def model(outcome, player1, player2, game_matrix):
"""
outcome [N, 1] where N is games and extra dimension is just 1 or zero depending on whether
player 1 or player 2 wins
player1 is one-hot vector encoding of player id
player2 ""
game_matrix has entries [G,P] (use sparse multiplication COO)
Say there are P players
Say there are G games
"""
# random normal distribution with vector [P, 1]
skill = pyro.sample(...)
diff = game_matrix @ skill
# random normal distribution with means as differences
score = pyro.sample(Normal(diff, 1))
prob = sigmoid(score)
# Outcome is drawn from a probability dist with p being result of sigmoid
pyro.sample(dis.Bernoulli(prob), obs=outcome)
# For the guide do
# Look it up
guide = pyro.AutoDiagonalNormal()
|
# inspired from spacy
def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWithCodes()
@add_codes
class Errors:
""" List of identified error """
E001 = 'Error on loading data configuration file.'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def Insertion_sort(_list):
list_length = len(_list)
i = 1
while i < list_length:
key = _list[i]
j = i - 1
while j >= 0 and _list[j] > key:
_list[j+1] = _list[j]
j -= 1
_list[j+1] = key
i += 1
return _list
|
duzina = 5
sirina = 2
povrsina = duzina * sirina
print('Povrsina je ', povrsina)
print('Obim je ', 2 * (duzina + sirina))
|
# -*- coding: utf-8 -*-
class Type(object):
jianshu_article = 'jianshu_article' # 类型是单篇的文章 TODO
jianshu = 'jianshu' # 类型是简书文章的集锦
jianshu_info = 'jianshu_info'
jianshu_article_type_list = ['jianshu']
info_table = {
'jianshu_info': jianshu_info
}
jianshu_type_list = [
'jianshu', # TODO, 目前只有latest_articles一种, 还可以写collections, notebook等等
]
|
""" Constants for event handling in Eris. """
PRIO_HIGH = 0
PRIO_MEDIUM = 1
PRIO_LOW = 2
|
## Python Crash Course
# Exercise 4.10: Slices:
# Using one of the programs you wrote in this chapter, add several lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:
# . Then use a slice to print the first three items from that program’s list .
# • Print the message, Three items from the middle of the list are:
# . Use a slice to print three items from the middle of the list .
# • Print the message, The last three items in the list are:
# . Use a slice to print the last three items in the list .
def main():
# Prepare list of cubes of numbers from 1 to 10
listOfCubes = [number**3 for number in range(1,11)]
# For loop to print numbers in the list
print("\nPrinting cubes of numbers from 1 to 10:")
for idx in range(len(listOfCubes)):
print("Cube of", idx+1, "is:", listOfCubes[idx])
############## End of Previos exercise #############################
# Print The first three items in the list are:
print("\nFirst three elements in the above list:", listOfCubes[0:3])
# Print The middle three items in the list are:
print("\nMiddle three elements in the above list:", listOfCubes[3:6])
# Print The last three items in the list are:
print("\nLast three elements in the above list:", listOfCubes[-3:])
print("\n")
if __name__ == '__main__':
main()
|
class Contact:
def __init__(self, fname=None, sname=None, lname=None, address=None, email=None, tel=None):
self.fname = fname
self.sname = sname
self.lname = lname
self.address = address
self.email = email
self.tel = tel
|
def response(number):
if number % 4 == 0:
return "Multiple of four"
elif number % 2 == 0:
return "Even"
else:
return "Odd"
def divisible(num, check):
if check % num == 0:
return "Yes, it's evenly divisible"
return "No, it's not evenly divisible"
if __name__ == "__main__":
number = int(input("Tell me a number: "))
print(response(number))
|
'''
x - Rozwiązania początkowe
x - Długość listy Tabu
x - Od wielkości instancji
x - Zależność od rozwiązania początkowego
x - Wielkość sąsiedztwa
x - Zaleznosc prd od dlugosci tabu list oraz wielkosci instancji (wykres 3D)
'''
def main():
instance_list = []
start_random_simulation()
start_nne_simulation()
if __name__ == '__main__':
main()
|
class PipelineError(Exception):
pass
class PipelineParallelError(Exception):
pass
|
# 定数
LANG_OPT_JPN = 0 # ひらがな→英語
LANG_OPT_ENG = 0 # 英語→ひらがな
class MikakaConverter:
# みかか変換
def __init__(self):
# コンストラクタ
self.mkk_jp_list = ["ぬ", "ふ", "あ", "う", "え",
"お", "や", "ゆ", "よ", "わ",
"ほ", "へ", "た", "て", "い",
"す", "か", "ん", "な", "に",
"ら", "せ", "ち", "と", "し",
"は", "き", "く", "ま", "の",
"り", "れ", "け", "む", "つ",
"さ", "そ", "ひ", "こ", "み",
"も", "ね", "る", "め", "ろ"]
self.mkk_en_list = ["1", "2", "3", "4", "5",
"6", "7", "8", "9", "0",
"-", "^", "q", "w", "e",
"r", "t", "y", "u", "i",
"o", "p", "a", "s", "d",
"f", "g", "h", "j", "k",
"l", ";", ":", "]", "z",
"x", "c", "v", "b", "n",
"m", ",", ".", "/", "\\"]
def char_conv(self, char_data, lang_opt):
# 文字を変換
try:
ret_val = "" # リターン用変数
if lang_opt is LANG_OPT_JPN:
# ひらがなから英語に変換
ret_val = self.mkk_en_list[self.mkk_jp_list.index(char_data)]
elif lang_opt is LANG_OPT_ENG:
# 英語からひらがなに変換
ret_val = self.mkk_jp_list[self.mkk_en_list.index(char_data)]
else:
# それ以外はNone
ret_val = None
return ret_val
except ValueError:
# 変換できない文字列はNoneとする
return None
def str_conv(self, str_data, lang_opt):
# 文字列を変換する
ret_val = ""
for index in range(len(str_data)):
ret_val += self.char_conv(str_data[index], lang_opt)
return ret_val
def main():
mikaka = MikakaConverter()
str_data = "みかか"
print(str_data+" = "+mikaka.str_conv(str_data, LANG_OPT_JPN))
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 实用代码集锦
Desc :
"""
def cool():
print('sample cool,,')
|
# print statement, function definition
name = "Anurag"
age = 30
print(name, age, "python", 2020)
print(name, age, "python", 2020, sep=", ", end=" $$ ")
|
def isPermutation(string_1, string_2):
string_1 = list(string_1)
string_2 = list(string_2)
for i in range(0, len(string_1)):
for j in range(0, len(string_2)):
if string_1[i] == string_2[j]:
del string_2[j]
break
if len(string_2) == 0:
return True
else:
return False
string_1 = str(input())
string_2 = str(input())
if isPermutation(string_1, string_2):
print('Your strings are permutations of each other.')
else:
print('Your strings are not permutations of each other.')
|
""" Regular expressions """
def match(pattern, string, flags=0):
return _compile(pattern, flags).match(string)
def _compile(pattern, flags):
p = sre_compile.compile(pattern, flags)
return p
|
class Observer(object):
"""docstring for Observer"""
def __init__(self):
super(Observer, self).__init__()
self.signalFunc = None
def onReceive(self, signal, emitter):
if self.signalFunc != None and signal in self.signalFunc:
self.signalFunc[signal](emitter)
|
class _SCon:
esc : str = '\u001B'
bra : str = '['
eb : str = esc + bra
bRed : str = eb + '41m'
white : str = eb + '37m'
bold : str = eb + '1m'
right : str = 'C'
left : str = 'D'
down : str = 'B'
up : str = 'A'
reset : str = eb + '0m'
cyan : str = eb + '36m'
del_char: str = eb + 'X'
save : str = eb + 's'
restore : str = eb + 'u'
def caret_to(self, x: int, y: int) -> None: print(self.eb + f"{y};{x}H", end = "")
def caret_save(self) -> None: print(self.save, end = "")
def caret_restore(self) -> None: print(self.restore, end = "")
def del_line(self) -> None: print(self.eb + "2K", end ="")
def reset_screen_and_caret(self) -> None: print(self.eb + "2J" + self.eb + "0;0H", end = "")
def caret_x_pos(self, x: int) -> None: print(self.eb + f"{x}G", end = "")
def caret_y_pos(self, y: int) -> None: print(self.eb + f"{y}d", end = "")
SCON: _SCon = _SCon()
|
#-- 포매팅(formatting)
# ● print만으로는 출력이 좀 불편하다고 느낄 수 있으나 format() 메소드를 사용하면 문자열을 그 이상으로 자유롭게 다루 수 있음
# ● 문자열 내에서 어떤 값이 들어가길 원하는 곳은 {}로 표시함
# ● {} 안의 값들은 숫자로 표한할 수 있으며, format 인자들의 인덱스를 사용함
# ● {0}는 첫 번째 인자인 'apple'을 나타내고
# ● {1}는 첫 번째 인자인 'red'을 나타내고
print('{0} is {1}'.format('apple', 'red'))
#-- 포매팅(formatting) - 키, 사전 이용
# ● {} 안의 값을 지정할 때는 다음과 같이 format의 인자로 키(key)와 값(value)을 주어 위와 동일한 결과를 얻을 수 있음
print('{item} is {color}'.format(item = 'apple', color = 'red'))
# ● dictionary를 입력으로 받는 경우
dic = {'item': 'apple', 'color': 'red'}
print('{0[item]} is {0[color]}'.format(dic))
#-- 포매팅(formatting) - **사용
# ● **기호를 사용하면 dictionary를 입력으로 받은 것으로 판단하고 인자를 하나만 받게 됨
# ● 불필요한 index를 생략 가능
print('{item} is {color}'.format(**dic))
#-- 포매팅(formatting) - 문자열 변환
# ● ! 기호를 사용해서 문자열 변환을 사용할 수 있음
print('{item!s} is {color!s}'.format(**dic))
print('{item!r} is {color!r}'.format(**dic))
print('{item!a} is {color!a}'.format(**dic))
# !s, !r, !a는 각각 str(), repr(), ascii()를 실행한 결과와 동일
#-- 포매팅(formatting) - 사용법
# ● ":" 기호를 이용하여 보다 정교하게 정렬, 폭, 부호, 공백처리, 소수점, 타입 등을 지정하는 방법
print('{0:$>5}'.format(10))
#-- 포매팅(formatting) - 정렬과 부호 표현법
# ● 정렬에 사용되는 기호
# ○ ">" 오른쪽 기준
# ○ "<" 왼쪽 기준
# ○ "^" 가운데 기준
# "="가 사용되면 공백문자들 앞에 부호가 표시됨. 사용되지 않으면 공백문자들 뒤, 즉, 숫자 바로 앞에 부호가 표시됨
#-- 포매팅(formatting) - 정렬과 부호 표현법
# ● 부호를 나타내는 기호
# ○ "+" 플러스 부호를 나타내라는 뜻
# ○ "-" 마이너스 값만 마이너스 부호를 나타내라는 뜻
# ○ " " 마이너스 값에는 마이너스 부호를 나타내고 플러스일 때는 공백을 표시하라는 뜻
print('{0:$>-5}'.format(-10))
#-- 포매팅(formatting) - 진수 표현법
# ● 진수를 바꿔서 출력
# ○ 'b'는 이진수를, 'd'는 십진수를, 'x'는 16진수를, 'o'는 8진수를 나타내며 'c'는 문자열을 출력
print('{0:b}'.format(10))
print('{0:o}'.format(10))
print('{0:c}'.format(65))
# ○ '#'을 사용하면 #x는 16진수 #o는 8진수, #b는 2진수로 표시됨
print('{0:#x}, {0:#o}, {0:#b}'.format(10))
#-- 포매팅(formatting) - 실수 표현법
# ● 정수 이외에 실수에 대한 변환도 제공되며, 'e'는 지수표현은 'f'는 일반적인 실수 표현을, '%'는 퍼센트 표현을 의미
print('{0:e}'.format(4 / 3))
print('{0:f}'.format(4 / 3))
print('{0:%}'.format(4 / 3))
#-- 포매팅(formatting) - 실수 표현법
# ● 실수에서는 소수점 몇 번째 자리까지 표현할 것인지를 지정가능
print('{0:.3f}'.format(4 / 3))
|
# tree structure in decoder side
# divide sub-node by brackets "()"
class Tree():
def __init__(self):
self.parent = None
self.num_children = 0
self.children = []
def __str__(self, level = 0):
ret = ""
for child in self.children:
if isinstance(child,type(self)):
ret += child.__str__(level+1)
else:
ret += "\t"*level + str(child) + "\n"
return ret
def add_child(self,c):
if isinstance(c,type(self)):
c.parent = self
self.children.append(c)
self.num_children = self.num_children + 1
def to_string(self):
r_list = []
for i in range(self.num_children):
if isinstance(self.children[i], Tree):
r_list.append("( " + self.children[i].to_string() + " )")
else:
r_list.append(str(self.children[i]))
return "".join(r_list)
def to_list(self, form_manager):
r_list = []
for i in range(self.num_children):
if isinstance(self.children[i], type(self)):
r_list.append(form_manager.get_symbol_idx("("))
cl = self.children[i].to_list(form_manager)
for k in range(len(cl)):
r_list.append(cl[k])
r_list.append(form_manager.get_symbol_idx(")"))
else:
r_list.append(self.children[i])
return r_list
|
print('-=-'*10)
print('Analisandor de Triângulos')
print('-=-'*10)
t0 = float(input('Primeiro segmento: '))
t1 = float(input('Segundo segmento:' ))
t2 = float(input('Terceiro segmento:' ))
#Fundamento dos triângulos===================================
if t0<t1+t2 and t1<t0+t2 and t2<t0+t1:
print('Os segmentos acima PODEM FORMAR um triângulo!')
# Qual triângulo é---------------------------------------
if t0 == t1 == t2:
txt = str('\033[7;31mEQUILÁTERO\033[m')
elif t0 == t1 or t0 == t2 or t1 == t2:
txt = str('\033[7;33mISÓSCELES\033[m')
else:
txt = str('\033[7;35mESCALENO\033[m')
# TEXTO--------------------------------------------------
print('Esse triângulo é {}'.format(txt))
else:
print('Os segmentos acima NÃO PODEM FORMAR um triângulo')
|
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
N = len(A)
l_sum = A[0]
r_sum = sum(A) - l_sum
diff = abs(l_sum - r_sum)
for i in range(1, N -1):
l_sum += A[i]
r_sum -= A[i]
c_diff = abs(l_sum - r_sum)
if diff > c_diff:
diff = c_diff
return diff
|
#!/usr/bin/python3
def uppercase(str):
for c in str:
if (ord(c) >= ord('a')) and (ord(c) <= ord('z')):
c = chr(ord(c)-ord('a')+ord('A'))
print("{}".format(c), end='')
print()
|
# Copyright 2018 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BUILD rules used to provide a Swift toolchain provided by Xcode on macOS.
The rules defined in this file are not intended to be used outside of the Swift
toolchain package. If you are looking for rules to build Swift code using this
toolchain, see `swift.bzl`.
"""
load(":providers.bzl", "SwiftToolchainInfo")
load("@bazel_skylib//:lib.bzl", "dicts")
def _default_linker_opts(apple_fragment, apple_toolchain, platform, target):
"""Returns options that should be passed by default to `clang` when linking.
Args:
apple_fragment: The `apple` configuration fragment.
apple_toolchain: The `apple_common.apple_toolchain()` object.
platform: The `apple_platform` value describing the target platform.
target: The target triple.
Returns:
A list of options that will be passed to any compile action created by this
toolchain.
"""
platform_framework_dir = apple_toolchain.platform_developer_framework_dir(
apple_fragment)
if _is_macos(platform):
swift_subdir = "swift_static"
static_linkopts = [
"-Xlinker",
"-force_load_swift_libs",
"-framework",
"Foundation",
"-lstdc++",
# XCTest.framework only lives in the Xcode bundle, so test binaries need
# to have that directory explicitly added to their rpaths.
# TODO(allevato): Factor this out into test-specific linkopts?
"-Wl,-rpath,{}".format(platform_framework_dir),
]
else:
swift_subdir = "swift"
static_linkopts = []
swift_lib_dir = (
"{developer_dir}/Toolchains/{toolchain}.xctoolchain" +
"/usr/lib/{swift_subdir}/{platform}"
).format(
developer_dir=apple_toolchain.developer_dir(),
platform=platform.name_in_plist.lower(),
swift_subdir=swift_subdir,
toolchain="XcodeDefault",
)
return static_linkopts + [
"-target", target,
"--sysroot", apple_toolchain.sdk_dir(),
"-F", platform_framework_dir,
"-L", swift_lib_dir,
]
def _default_swiftc_copts(apple_fragment, apple_toolchain, target):
"""Returns options that should be passed by default to `swiftc`.
Args:
apple_fragment: The `apple` configuration fragment.
apple_toolchain: The `apple_common.apple_toolchain()` object.
target: The target triple.
Returns:
A list of options that will be passed to any compile action created by this
toolchain.
"""
copts = [
"-target", target,
"-sdk", apple_toolchain.sdk_dir(),
"-F", apple_toolchain.platform_developer_framework_dir(apple_fragment),
]
bitcode_mode = str(apple_fragment.bitcode_mode)
if bitcode_mode == "embedded":
copts.append("-embed-bitcode")
elif bitcode_mode == "embedded_markers":
copts.append("-embed-bitcode-marker")
elif bitcode_mode != "none":
fail("Internal error: expected apple_fragment.bitcode_mode to be one " +
"of: ['embedded', 'embedded_markers', 'none']")
return copts
def _is_macos(platform):
"""Returns `True` if the given platform is macOS.
Args:
platform: An `apple_platform` value describing the platform for which a
target is being built.
Returns:
`True` if the given platform is macOS.
"""
return platform.platform_type == apple_common.platform_type.macos
def _swift_apple_target_triple(cpu, platform, version):
"""Returns a target triple string for an Apple platform.
Args:
cpu: The CPU of the target.
platform: The `apple_platform` value describing the target platform.
version: The target platform version as a dotted version string.
Returns:
A target triple string describing the platform.
"""
platform_string = str(platform.platform_type)
if platform_string == "macos":
platform_string = "macosx"
return "{cpu}-apple-{platform}{version}".format(
cpu=cpu,
platform=platform_string,
version=version,
)
def _xcode_env(xcode_config, platform):
"""Returns a dictionary containing Xcode-related environment variables.
Args:
xcode_config: The `XcodeVersionConfig` provider that contains information
about the current Xcode configuration.
platform: The `apple_platform` value describing the target platform being
built.
Returns:
A `dict` containing Xcode-related environment variables that should be
passed to Swift compile and link actions.
"""
return dicts.add(
apple_common.apple_host_system_env(xcode_config),
apple_common.target_apple_env(xcode_config, platform)
)
def _xcode_swift_toolchain_impl(ctx):
apple_fragment = ctx.fragments.apple
apple_toolchain = apple_common.apple_toolchain()
cpu = apple_fragment.single_arch_cpu
platform = apple_fragment.single_arch_platform
xcode_config = ctx.attr._xcode_config[apple_common.XcodeVersionConfig]
target_os_version = xcode_config.minimum_os_for_platform_type(
platform.platform_type)
target = _swift_apple_target_triple(cpu, platform, target_os_version)
linker_opts = _default_linker_opts(
apple_fragment, apple_toolchain, platform, target)
swiftc_copts = _default_swiftc_copts(apple_fragment, apple_toolchain, target)
return [
SwiftToolchainInfo(
action_environment=_xcode_env(xcode_config, platform),
cc_toolchain_info=None,
cpu=cpu,
execution_requirements={"requires-darwin": ""},
implicit_deps=[],
linker_opts=linker_opts,
object_format="macho",
requires_autolink_extract=False,
requires_workspace_relative_module_maps=False,
root_dir=None,
spawn_wrapper=ctx.executable._xcrunwrapper,
stamp=ctx.attr.stamp if _is_macos(platform) else None,
supports_objc_interop=True,
swiftc_copts=swiftc_copts,
system_name="darwin",
),
]
xcode_swift_toolchain = rule(
attrs={
"stamp": attr.label(
doc="""
A `cc`-providing target that should be linked into any binaries that are built
with stamping enabled.
""",
providers=[["cc"]],
),
"_xcode_config": attr.label(
default=configuration_field(
fragment="apple",
name="xcode_config_label",
),
),
"_xcrunwrapper": attr.label(
cfg="host",
default=Label("@bazel_tools//tools/objc:xcrunwrapper"),
executable=True,
),
},
doc="Represents a Swift compiler toolchain provided by Xcode.",
fragments=["apple", "cpp"],
implementation=_xcode_swift_toolchain_impl,
)
|
ENTRY_POINT = 'split_words'
FIX = """
Add check for lower case and add test.
"""
#[PROMPT]
def split_words(txt):
'''
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
Examples
split_words("Hello world!") ➞ ["Hello", "world!"]
split_words("Hello,world!") ➞ ["Hello", "world!"]
split_words("abcdef") == 3
'''
#[SOLUTION]
if " " in txt:
return txt.split()
elif "," in txt:
return txt.replace(',',' ').split()
else:
return len([i for i in txt if i.islower() and ord(i)%2 == 0])
#[CHECK]
def check(candidate):
assert candidate("Hello world!") == ["Hello","world!"]
assert candidate("Hello,world!") == ["Hello","world!"]
assert candidate("Hello world,!") == ["Hello","world,!"]
assert candidate("Hello,Hello,world !") == ["Hello,Hello,world","!"]
assert candidate("abcdef") == 3
assert candidate("aaabb") == 2
assert candidate("aaaBb") == 1
|
#In PowerShell
"""
function Get-Something {
param (
[string[]]$thing
)
foreach ($t in $things){
Write-Host $t
}
}
"""
#region functions
def powershell_python():
print('This is a function')
#return is key for returning values
return
#positional arguments mandatory,
def powershell_python(name, optional=yes):
if optional == 'yes':
print('This uses an optional arguments')
print('This is a function {var1}'.format(var1=name))
return
#endregion
|
def calcula_diferenca(A: int, B: int, C: int, D: int):
if (not isinstance(A, int) or
not isinstance(B, int) or
not isinstance(C, int) or
not isinstance(D, int)):
raise(TypeError)
D = A * B - C * D
return f'DIFERENCA = {D}'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################################################
#........../\./\...___......|\.|..../...\.........#
#........./..|..\/\.|.|_|._.|.\|....|.c.|.........#
#......../....../--\|.|.|.|i|..|....\.../.........#
# Mathtin (c) #
###################################################
# Author: Daniel [Mathtin] Shiko #
# Copyright (c) 2020 <[email protected]> #
# This file is released under the MIT license. #
###################################################
__author__ = 'Mathtin'
class InvalidConfigException(Exception):
def __init__(self, msg: str, var_name: str):
super().__init__(f'{msg}, check {var_name} value')
class NotCoroutineException(TypeError):
def __init__(self, func):
super().__init__(f'{str(func)} is not a coroutine function')
class MissingResourceException(Exception):
def __init__(self, xml: str, path: str):
super().__init__(f'Missing resource in {xml}: {path}')
|
""" TRABALHANDO COM CONDIÇÕES ANINHADAS - IF / ELIF / ELSE """
nome = str(input("Digite seu Nome: "))
if nome == "Fabio":
print("Que nome Bonito, {}".format(nome))
elif nome == "Gustavo":
print("Esse é o nome do seu professor, {}".format(nome))
else:
print("Não reconheço esse nome {}".format(nome))
|
#
# LeetCode
# Algorithm 104 Maximum depth of binary tree
#
# See LICENSE
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def traverse(self, root, depth):
"""
:type root: TreeNode
:type depth: int
:rtype: int
"""
if root == None:
return depth
else:
return max( self.traverse(root.left, depth+1), self.traverse(root.right, depth+1))
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.traverse(root, 0)
|
#Question link
#https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x/0
def window(arr,n, k):
left=0
right=0
ans=n
sum1=0
while left<n and right<n+1:
if sum1>k:
if left==right:
ans=1
break
ans=min(ans,right-left)
sum1-=arr[left]
left+=1
elif right==n:
break
else:
sum1+=arr[right]
right+=1
return ans
def main():
t = int(input())
for _ in range(t):
n, k = map(int,input().split())
arr = list(map(int,input().split()))
print(window(arr,n,k))
if __name__ == "__main__":
main()
|
s = input()
# s = ' name1'
list_stop = [' ', '@', '$', '%']
list_num = '0123456789'
# flag_true = 0
flag_false = 0
for i in list_num:
if s[0] == i:
flag_false += 1
break
for j in s:
for k in list_stop:
if j == k:
flag_false += 1
break
else:
# flag_true += 1
break
if flag_false >= 1:
print(False)
else:
print(True)
|
#
# @lc app=leetcode id=1232 lang=python3
#
# [1232] Check If It Is a Straight Line
#
# @lc code=start
class Solution:
def checkStraightLine(self, coordinates):
if len(coordinates) <= 2:
return True
x1, x2, y1, y2 = coordinates[0][0], coordinates[1][0], coordinates[0][1], coordinates[1][1]
if x1 == x2:
k = 0
else:
k = (y1 - y2)/(x1 - x2)
b = y1 - k * x1
for item in coordinates[2:]:
if item[1] != item[0] * k + b:
return False
return True
# @lc code=end
|
class YggException(Exception): pass
class LoginFailed(Exception): pass
class TooManyFailedLogins(Exception): pass
|
class TriggerBase:
def __init__(self, q, events):
self.q = q
self.events = events
def trigger(self, name):
self.q.put(
{'req': 'trigger_animation', 'data': name, 'sender': 'Trigger'})
|
favcolor = {
"Jacob": "Magenta",
"Jason": "Red",
"Anais": "Purple"
}
for name, color in favcolor.items():
print("%s's favorite color is %s" %(name, color))
|
"""Constants for the Vivint integration."""
DOMAIN = "vivint"
EVENT_TYPE = f"{DOMAIN}_event"
RTSP_STREAM_DIRECT = 0
RTSP_STREAM_INTERNAL = 1
RTSP_STREAM_EXTERNAL = 2
RTSP_STREAM_TYPES = {
RTSP_STREAM_DIRECT: "Direct (falls back to internal if direct access is not available)",
RTSP_STREAM_INTERNAL: "Internal",
RTSP_STREAM_EXTERNAL: "External",
}
CONF_HD_STREAM = "hd_stream"
CONF_RTSP_STREAM = "rtsp_stream"
DEFAULT_HD_STREAM = True
DEFAULT_RTSP_STREAM = RTSP_STREAM_DIRECT
|
'''
5. Write a Python program to check whether a specified value is contained in a group of values.
Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False
'''
def check_value(group_data, n):
for x in group_data:
if n == x:
return True
else:
return False
print(check_value([1,5,8,3], 3))
print(check_value([1,5,8,3], -1))
|
# Program corresponding to flowchart in this site https://automatetheboringstuff.com/2e/images/000039.jpg
print('Is raining? (Y)es or (N)o')
answer = input()
if answer == 'N':
print('Go outside.')
elif answer == 'Y':
print('Have umbrella? (Y)es or (N)o')
answer2 = input()
if answer2 == 'Y':
print('Go outside.')
elif answer2 == 'N':
print('Wait a while.')
print('Is raining? (Y)es or (N)o')
answer3 = input()
while answer3 == 'Y':
print('Wait a while.')
print('Is raining? (Y)es or (N)o')
answer3 = input()
print('Go outside.')
else:
print("I can't understand you.Type 'Y' for yes and 'N' or No.")
print('===============')
print('Exiting program')
|
__all__ = ["TreeDict"]
class TreeDict:
"""Converts a nested dict to an object.
Items in the dict are set to object attributes.
ARTIQ python does not support dict type. Inherit this class to convert the dict to an object.
self.value_parser() can be inherited to parse non-dict values.
Args:
dict_value: dict, dictionary to convert to an object.
nested_dict_class: class for nested dicts. Default None, which represents self.__class__.
This can be a different class (usually another class inherited from TreeDict).
"""
def __init__(self, dict_value, nested_dict_class=None):
self._set_attributes(dict_value, nested_dict_class)
def value_parser(self, value):
"""Parser for non-dict values."""
return value
def _set_attributes(self, dict_value, nested_dict_class):
if nested_dict_class is None:
class SubClass(self.__class__):
"""A derived class from the current class.
ARTIQ python does not support nesting a class as an attribute of the same class,
so a derived class from self.__class__ is necessary.
"""
pass
nested_dict_class = SubClass
for item in dict_value:
if isinstance(dict_value[item], dict):
setattr(self, item, nested_dict_class(dict_value[item]))
else:
setattr(self, item, self.value_parser(dict_value[item]))
|
# -*- coding: utf-8 -*-
################################################################################
# LexaLink Copyright information - do not remove this copyright notice
# Copyright (C) 2012
#
# Lexalink - a free social network and dating platform for the Google App Engine.
#
# Original author: Alexander Marquardt
# Documentation and additional information: http://www.LexaLink.com
# Git source code repository: https://github.com/lexalink/LexaLink.git
#
# Please consider contributing your enhancements and modifications to the LexaLink community,
#
# 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
CA_regions = [
((u'AB', u' Alberta'),[
(u"AI", u"Airdrie"),
(u"BA", u"Banff"),
(u"BR", u"Brooks"),
(u"CA", u"Calgary"),
(u"CR", u"Camrose"),
(u"CO", u"Cold Lake"),
(u"ED", u"Edmonton"),
(u"FO", u"Fort Saskatchewan"),
(u"GR", u"Grande Prairie"),
(u"LA", u"Lacombe"),
(u"LE", u"Leduc"),
(u"LT", u"Lethbridge"),
(u"LL", u"Lloydminster"),
(u"ME", u"Medicine Hat"),
(u"RE", u"Red Deer"),
(u"SP", u"Spruce Grove"),
(u"ST", u"St. Albert"),
(u"WE", u"Wetaskiwin"),
]),
((u"BC", u"British Columbia"), [
(u"AC", u"Alberni-Clayoquot"),
(u"BN", u"Bulkley-Nechako"),
(u"CP", u"Capital"),
(u"CR", u"Cariboo"),
(u"CC", u"Central Coast"),
(u"CK", u"Central Kootenay"),
(u"CO", u"Central Okanagan"),
(u"CS", u"Columbia-Shuswap"),
(u"CX", u"Comox-Strathcona"),
(u"CV", u"Cowichan Valley"),
(u"EK", u"East Kootenay"),
(u"FL", u"Fort Nelson-Liard"),
(u"FV", u"Fraser Valley"),
(u"FF", u"Fraser-Fort George"),
(u"KS", u"Kitimat-Stikine"),
(u"KB", u"Kootenay Boundary"),
(u"MW", u"Mount Waddington"),
(u"NA", u"Nanaimo"),
(u"NO", u"North Okanagan"),
(u"OS", u"Okanagan-Similkameen"),
(u"PC", u"Peace River"),
(u"PW", u"Powell River"),
(u"SQ", u"Skeena-Queen Charlotte"),
(u"SL", u"Squamish-Lillooet"),
(u"ST", u"Stikine"),
(u"SC", u"Sunshine Coast"),
(u"TN", u"Thompson-Nicola"),
(u"GV", u"Vancouver (Greater Vancouver)"),
]),
((u'MB', u' Manitoba'),[
(u"BR", u"Brandon"),
(u"DA", u"Dauphin"),
(u"FL", u"Flin Flon"),
(u"MO", u"Morden"),
(u"PO", u"Portage la Prairie"),
(u"SE", u"Selkirk"),
(u"ST", u"Steinbach"),
(u"TH", u"The Pas"),
(u"TO", u"Thompson"),
(u"WI", u"Winkler"),
(u"WI", u"Winnipeg"),
]),
((u"NB", u"New Brunswick"), [
(u"AL", u"Albert"),
(u"CA", u"Carleton"),
(u"CH", u"Charlotte"),
(u"GL", u"Gloucester"),
(u"KE", u"Kent"),
(u"KI", u"Kings"),
(u"MA", u"Madawaska"),
(u"NO", u"Northumberland"),
(u"QU", u"Queens"),
(u"RE", u"Restigouche"),
(u"SJ", u"Saint John"),
(u"SU", u"Sunbury"),
(u"VI", u"Victoria"),
(u"WE", u"Westmorland"),
(u"YO", u"York"),
]),
((u'NL', u' Newfoundland and Labrador'),[]),
((u"NT", u"Northwest Territories"), [
(u"FS", u"Fort Smith"),
(u"IN", u"Inuvik"),
]),
((u"NS", u"Nova Scotia"), [
(u"AP", u"Annapolis"),
(u"AG", u"Antigonish"),
(u"CB", u"Cape Breton"),
(u"CO", u"Colchester"),
(u"CU", u"Cumberland"),
(u"DI", u"Digby"),
(u"GU", u"Guysborough"),
(u"HL", u"Halifax"),
(u"HN", u"Hants"),
(u"IN", u"Inverness"),
(u"KI", u"Kings"),
(u"LU", u"Lunenburg"),
(u"PI", u"Pictou"),
(u"QU", u"Queens"),
(u"RI", u"Richmond"),
(u"SH", u"Shelburne"),
(u"VI", u"Victoria"),
(u"YA", u"Yarmouth"),
]),
((u"NU", u"Nunavut"), [
(u"QK", u"Baffin Qikiqtaaluk"),
(u"KV", u"Keewatin Kivalliq"),
(u"KT", u"Kitikmeot Kitikmeot"),
]),
((u"ON", u"Ontario"), [
(u"AL", u"Algoma"),
(u"BN", u"Brant"),
(u"BC", u"Bruce"),
(u"CO", u"Cochrane"),
(u"DF", u"Dufferin"),
(u"DR", u"Durham"),
(u"EL", u"Elgin"),
(u"ES", u"Essex"),
(u"FR", u"Frontenac"),
(u"GR", u"Grey"),
(u"HD", u"Haldimand"),
(u"HB", u"Haliburton"),
(u"HT", u"Halton"),
(u"HW", u"Hamilton-Wentworth"),
(u"HS", u"Hastings"),
(u"HU", u"Huron"),
(u"KR", u"Kenora"),
(u"KT", u"Kent"),
(u"LM", u"Lambton"),
(u"LN", u"Lanark"),
(u"LG", u"Leeds and Grenville"),
(u"LA", u"Lennox and Addington"),
(u"MA", u"Manitoulin"),
(u"MI", u"Middlesex"),
(u"MU", u"Muskoka"),
(u"NG", u"Niagara"),
(u"NP", u"Nipissing"),
(u"NF", u"Norfolk"),
(u"NU", u"Northumberland"),
(u"OC", u"Ottawa-Carleton"),
(u"OX", u"Oxford"),
(u"PS", u"Parry Sound"),
(u"PL", u"Peel"),
(u"PT", u"Perth"),
(u"PB", u"Peterborough"),
(u"PR", u"Prescott and Russell"),
(u"PE", u"Prince Edward"),
(u"RR", u"Rainy River"),
(u"RE", u"Renfrew"),
(u"SC", u"Simcoe"),
(u"SD", u"Stormont, Dundas and Glengarry"),
(u"SU", u"Sudbury"),
(u"SB", u"Sudbury"),
(u"TB", u"Thunder Bay"),
(u"TI", u"Timiskaming"),
(u"TO", u"Toronto"),
(u"VI", u"Victoria"),
(u"WT", u"Waterloo"),
(u"WL", u"Wellington"),
(u"YO", u"York"),
]),
((u"PE", u"Prince Edward Island"), [
(u"KI", u"Kings"),
(u"PR", u"Prince"),
(u"QU", u"Queens"),
]),
((u"QC", u"Quebec"), [
(u"AB", u"Abitibi"),
(u"AO", u"Abitibi-Ouest"),
(u"AC", u"Acton"),
(u"AL", u"Antoine-Labelle"),
(u"AG", u"Argenteuil"),
(u"AT", u"Arthabaska"),
(u"AS", u"Asbestos"),
(u"AV", u"Avignon"),
(u"BS", u"Beauce-Sartigan"),
(u"BH", u"Beauharnois-Salaberry"),
(u"BL", u"Bellechasse"),
(u"BO", u"Bonaventure"),
(u"BM", u"Brome-Missisquoi"),
(u"BC", u"Bécancour"),
(u"CP", u"Champlain"),
(u"CV", u"Charlevoix"),
(u"CE", u"Charlevoix-Est"),
(u"CT", u"Coaticook"),
(u"DA", u"D'Autray"),
(u"DR", u"Denis-Riverin"),
(u"DE", u"Desjardins"),
(u"DM", u"Deux-Montagnes"),
(u"DU", u"Drummond"),
(u"FR", u"Francheville"),
(u"JO", u"Joliette"),
(u"KA", u"Kamouraska"),
(u"AM", u"L'Amiante"),
(u"AN", u"L'Assomption"),
(u"IS", u"L'Islet"),
(u"ER", u"L'Érable"),
(u"IO", u"L'Île-d'Orléans"),
(u"CB", u"La Côte-de-Beaupré"),
(u"CG", u"La Côte-de-Gaspé"),
(u"HC", u"La Haute-Côte-Nord"),
(u"HY", u"La Haute-Yamaska"),
(u"JC", u"La Jacques-Cartier"),
(u"MP", u"La Matapédia"),
(u"MI", u"La Mitis"),
(u"NB", u"La Nouvelle-Beauce"),
(u"RD", u"La Rivière-du-Nord"),
(u"VG", u"La Vallée-de-la-Gatineau"),
(u"VR", u"La Vallée-du-Richelieu"),
(u"LS", u"Lac-Saint-Jean-Est"),
(u"LJ", u"Lajemmerais"),
(u"LV", u"Laval"),
(u"BR", u"Le Bas-Richelieu"),
(u"CM", u"Le Centre-de-la-Mauricie"),
(u"DD", u"Le Domaine-du-Roy"),
(u"FS", u"Le Fjord-du-Saguenay"),
(u"GR", u"Le Granit"),
(u"HR", u"Le Haut-Richelieu"),
(u"HF", u"Le Haut-Saint-François"),
(u"HL", u"Le Haut-Saint-Laurent"),
(u"HM", u"Le Haut-Saint-Maurice"),
(u"VF", u"Le Val-Saint-François"),
(u"BA", u"Les Basques"),
(u"CC", u"Les Chutes-de-la-Chaudière"),
(u"CO", u"Les Collines-de-l'Outaouais"),
(u"ET", u"Les Etchemins"),
(u"JN", u"Les Jardins-de-Napierville"),
(u"LL", u"Les Laurentides"),
(u"MK", u"Les Maskoutains"),
(u"MU", u"Les Moulins"),
(u"PH", u"Les Pays-d'en-Haut"),
(u"IM", u"Les Îles-de-la-Madeleine"),
(u"LO", u"Lotbinière"),
(u"MN", u"Manicouagan"),
(u"MC", u"Maria-Chapdelaine"),
(u"MS", u"Maskinongé"),
(u"MT", u"Matane"),
(u"MW", u"Matawinie"),
(u"MG", u"Memphrémagog"),
(u"MB", u"Minganie - Basse-Côte-Nord"),
(u"ML", u"Mirabel"),
(u"MO", u"Montcalm"),
(u"MM", u"Montmagny"),
(u"MR", u"Montréal (Communauté-Urbaine)"),
(u"ME", u"Mékinac"),
(u"NY", u"Nicolet-Yamaska"),
(u"NQ", u"Nord-du-Québec"),
(u"OU", u"Outaouais (Communauté-Urbaine)"),
(u"PB", u"Pabok"),
(u"PP", u"Papineau"),
(u"PN", u"Pontiac"),
(u"PR", u"Portneuf"),
(u"QU", u"Québec (Communauté-Urbaine)"),
(u"RM", u"Rimouski-Neigette"),
(u"RL", u"Rivière-du-Loup"),
(u"RC", u"Robert-Cliche"),
(u"RS", u"Roussillon"),
(u"RV", u"Rouville"),
(u"RN", u"Rouyn-Noranda"),
(u"SR", u"Sept-Rivières - Caniapiscau"),
(u"SH", u"Sherbrooke"),
(u"TB", u"Thérèse-De Blainville"),
(u"TM", u"Témiscamingue"),
(u"TT", u"Témiscouata"),
(u"VO", u"Vallée-de-l'Or"),
(u"VS", u"Vaudreuil-Soulanges"),
]),
((u'SK', u' Saskatchewan'),[
(u"ES", u"Estevan"),
(u"HU", u"Humboldt"),
(u"LL", u"Lloydminster"),
(u"MA", u"Martensville"),
(u"ME", u"Meadow Lake"),
(u"MF", u"Melfort"),
(u"MV", u"Melville"),
(u"MO", u"Moose Jaw"),
(u"NO", u"North Battleford"),
(u"PR", u"Prince Albert"),
(u"RE", u"Regina"),
(u"SA", u"Saskatoon"),
(u"SW", u"Swift Current"),
(u"WE", u"Weyburn"),
(u"YO", u"Yorkton"),
]),
((u'YT', u' Yukon Territory'),[]),
]
|
first_name = input()
second_name = input()
delimeter = input()
print(f"{first_name}{delimeter}{second_name}")
|
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
class C:
def __init__(self):
self.x = 0
class D(C):
def __init__(self):
super().__init__()
self.y = 1
# super() 的另外一个常见用法出现在覆盖Python特殊方法的代码中,比如:
class Proxy:
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value) # Call original __setattr__
else:
setattr(self._obj, name, value)
|
#
# PySNMP MIB module CISCO-ITP-RT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-RT-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:03:41 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:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
NotificationGroup, ModuleCompliance, AgentCapabilities = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "AgentCapabilities")
Bits, Counter32, NotificationType, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Integer32, Gauge32, Unsigned32, MibIdentifier, TimeTicks, iso, IpAddress, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "NotificationType", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Integer32", "Gauge32", "Unsigned32", "MibIdentifier", "TimeTicks", "iso", "IpAddress", "ModuleIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoItpRtCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 216))
ciscoItpRtCapability.setRevisions(('2002-01-21 00:00', '2001-10-24 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoItpRtCapability.setRevisionsDescriptions(('Updated capabilities MIB as required for new groups. cItpRtNotificationsGroup, cItpRtScalarGroupRev1', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoItpRtCapability.setLastUpdated('200201210000Z')
if mibBuilder.loadTexts: ciscoItpRtCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoItpRtCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoItpRtCapability.setDescription('Agent capabilities for the CISCO-ITP-RT-MIB.')
ciscoItpRtCapabilityV12R024MB1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 216, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoItpRtCapabilityV12R024MB1 = ciscoItpRtCapabilityV12R024MB1.setProductRelease('Cisco IOS 12.2(4)MB1')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoItpRtCapabilityV12R024MB1 = ciscoItpRtCapabilityV12R024MB1.setStatus('current')
if mibBuilder.loadTexts: ciscoItpRtCapabilityV12R024MB1.setDescription('IOS 12.2(4)MB1 Cisco CISCO-ITP-RT-MIB.my User Agent MIB capabilities.')
ciscoItpRtCapabilityV12R0204MB3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 216, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoItpRtCapabilityV12R0204MB3 = ciscoItpRtCapabilityV12R0204MB3.setProductRelease('Cisco IOS 12.2(4)MB3')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoItpRtCapabilityV12R0204MB3 = ciscoItpRtCapabilityV12R0204MB3.setStatus('current')
if mibBuilder.loadTexts: ciscoItpRtCapabilityV12R0204MB3.setDescription('IOS 12.2(4)MB3 Cisco CISCO-ITP-RT-MIB.my User Agent MIB capabilities.')
mibBuilder.exportSymbols("CISCO-ITP-RT-CAPABILITY", ciscoItpRtCapabilityV12R024MB1=ciscoItpRtCapabilityV12R024MB1, ciscoItpRtCapabilityV12R0204MB3=ciscoItpRtCapabilityV12R0204MB3, PYSNMP_MODULE_ID=ciscoItpRtCapability, ciscoItpRtCapability=ciscoItpRtCapability)
|
# -*- coding: utf-8 -*-
qntCaso = int(input())
for caso in range(qntCaso):
listStrTamanhoStr = list()
listStr = list(map(str, input().split()))
for indiceStr in range(len(listStr)): listStrTamanhoStr.append([listStr[indiceStr], len(listStr[indiceStr])])
strSequenciaOrdenadaTamanho = ""
for chave, valor in sorted(listStrTamanhoStr, key=lambda x: x[1],reverse=True): strSequenciaOrdenadaTamanho += "{} ".format(chave)
print(strSequenciaOrdenadaTamanho.strip())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = '[email protected]'
__version__ = '0.1.0.b6'
|
#square pattern
'''
Print the following pattern for the given N number of rows.
Pattern for N = 4
4444
4444
4444
4444
'''
rows=int(input())
for i in range(rows):
for j in range(rows):
print(rows,end="")
print()
|
# PyPy なら通る
N = int(input())
S = input()
result = 0
for i in range(N - 1, 0, -1):
if i <= result:
break
t = 0
for j in range(N - i):
if S[j] == S[j+i]:
t += 1
if t > result:
result = t
if result == i:
break
else:
t = 0
print(result)
|
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"instance": {
"10000": {
"summary_traffic_statistics": {
"ospf_packets_received_sent": {
"type": {
"rx_invalid": {"packets": 0, "bytes": 0},
"rx_hello": {"packets": 0, "bytes": 0},
"rx_db_des": {"packets": 0, "bytes": 0},
"rx_ls_req": {"packets": 0, "bytes": 0},
"rx_ls_upd": {"packets": 0, "bytes": 0},
"rx_ls_ack": {"packets": 0, "bytes": 0},
"rx_total": {"packets": 0, "bytes": 0},
"tx_failed": {"packets": 0, "bytes": 0},
"tx_hello": {"packets": 0, "bytes": 0},
"tx_db_des": {"packets": 0, "bytes": 0},
"tx_ls_req": {"packets": 0, "bytes": 0},
"tx_ls_upd": {"packets": 0, "bytes": 0},
"tx_ls_ack": {"packets": 0, "bytes": 0},
"tx_total": {"packets": 0, "bytes": 0},
}
},
"ospf_header_errors": {
"length": 0,
"instance_id": 0,
"checksum": 0,
"auth_type": 0,
"version": 0,
"bad_source": 0,
"no_virtual_link": 0,
"area_mismatch": 0,
"no_sham_link": 0,
"self_originated": 0,
"duplicate_id": 0,
"hello": 0,
"mtu_mismatch": 0,
"nbr_ignored": 0,
"lls": 0,
"unknown_neighbor": 0,
"authentication": 0,
"ttl_check_fail": 0,
"adjacency_throttle": 0,
"bfd": 0,
"test_discard": 0,
},
"ospf_lsa_errors": {
"type": 0,
"length": 0,
"data": 0,
"checksum": 0,
},
}
},
"888": {
"router_id": "10.19.13.14",
"ospf_queue_statistics": {
"limit": {"inputq": 0, "updateq": 200, "outputq": 0},
"drops": {"inputq": 0, "updateq": 0, "outputq": 0},
"max_delay_msec": {
"inputq": 3,
"updateq": 2,
"outputq": 1,
},
"max_size": {
"total": {"inputq": 4, "updateq": 3, "outputq": 2},
"invalid": {
"inputq": 0,
"updateq": 0,
"outputq": 0,
},
"hello": {"inputq": 4, "updateq": 0, "outputq": 1},
"db_des": {"inputq": 0, "updateq": 0, "outputq": 1},
"ls_req": {"inputq": 0, "updateq": 0, "outputq": 0},
"ls_upd": {"inputq": 0, "updateq": 3, "outputq": 0},
"ls_ack": {"inputq": 0, "updateq": 0, "outputq": 0},
},
"current_size": {
"total": {"inputq": 0, "updateq": 0, "outputq": 0},
"invalid": {
"inputq": 0,
"updateq": 0,
"outputq": 0,
},
"hello": {"inputq": 0, "updateq": 0, "outputq": 0},
"db_des": {"inputq": 0, "updateq": 0, "outputq": 0},
"ls_req": {"inputq": 0, "updateq": 0, "outputq": 0},
"ls_upd": {"inputq": 0, "updateq": 0, "outputq": 0},
"ls_ack": {"inputq": 0, "updateq": 0, "outputq": 0},
},
},
"interface_statistics": {
"interfaces": {
"Tunnel65541": {
"last_clear_traffic_counters": "never",
"ospf_packets_received_sent": {
"type": {
"rx_invalid": {
"packets": 0,
"bytes": 0,
},
"rx_hello": {"packets": 0, "bytes": 0},
"rx_db_des": {"packets": 0, "bytes": 0},
"rx_ls_req": {"packets": 0, "bytes": 0},
"rx_ls_upd": {"packets": 0, "bytes": 0},
"rx_ls_ack": {"packets": 0, "bytes": 0},
"rx_total": {"packets": 0, "bytes": 0},
"tx_failed": {"packets": 0, "bytes": 0},
"tx_hello": {
"packets": 62301,
"bytes": 5980896,
},
"tx_db_des": {"packets": 0, "bytes": 0},
"tx_ls_req": {"packets": 0, "bytes": 0},
"tx_ls_upd": {"packets": 0, "bytes": 0},
"tx_ls_ack": {"packets": 0, "bytes": 0},
"tx_total": {
"packets": 62301,
"bytes": 5980896,
},
}
},
"ospf_header_errors": {
"length": 0,
"instance_id": 0,
"checksum": 0,
"auth_type": 0,
"version": 0,
"bad_source": 0,
"no_virtual_link": 0,
"area_mismatch": 0,
"no_sham_link": 0,
"self_originated": 0,
"duplicate_id": 0,
"hello": 0,
"mtu_mismatch": 0,
"nbr_ignored": 0,
"lls": 0,
"unknown_neighbor": 0,
"authentication": 0,
"ttl_check_fail": 0,
"adjacency_throttle": 0,
"bfd": 0,
"test_discard": 0,
},
"ospf_lsa_errors": {
"type": 0,
"length": 0,
"data": 0,
"checksum": 0,
},
},
"GigabitEthernet0/1/7": {
"last_clear_traffic_counters": "never",
"ospf_packets_received_sent": {
"type": {
"rx_invalid": {
"packets": 0,
"bytes": 0,
},
"rx_hello": {
"packets": 70493,
"bytes": 3383664,
},
"rx_db_des": {
"packets": 3,
"bytes": 1676,
},
"rx_ls_req": {
"packets": 1,
"bytes": 36,
},
"rx_ls_upd": {
"packets": 14963,
"bytes": 1870388,
},
"rx_ls_ack": {
"packets": 880,
"bytes": 76140,
},
"rx_total": {
"packets": 86340,
"bytes": 5331904,
},
"tx_failed": {"packets": 0, "bytes": 0},
"tx_hello": {
"packets": 1,
"bytes": 100,
},
"tx_db_des": {
"packets": 4,
"bytes": 416,
},
"tx_ls_req": {
"packets": 1,
"bytes": 968,
},
"tx_ls_upd": {
"packets": 1,
"bytes": 108,
},
"tx_ls_ack": {
"packets": 134,
"bytes": 9456,
},
"tx_total": {
"packets": 141,
"bytes": 11048,
},
}
},
"ospf_header_errors": {
"length": 0,
"instance_id": 0,
"checksum": 0,
"auth_type": 0,
"version": 0,
"bad_source": 0,
"no_virtual_link": 0,
"area_mismatch": 0,
"no_sham_link": 0,
"self_originated": 0,
"duplicate_id": 0,
"hello": 0,
"mtu_mismatch": 0,
"nbr_ignored": 0,
"lls": 0,
"unknown_neighbor": 0,
"authentication": 0,
"ttl_check_fail": 0,
"adjacency_throttle": 0,
"bfd": 0,
"test_discard": 0,
},
"ospf_lsa_errors": {
"type": 0,
"length": 0,
"data": 0,
"checksum": 0,
},
},
"GigabitEthernet0/1/6": {
"last_clear_traffic_counters": "never",
"ospf_packets_received_sent": {
"type": {
"rx_invalid": {
"packets": 0,
"bytes": 0,
},
"rx_hello": {
"packets": 70504,
"bytes": 3384192,
},
"rx_db_des": {
"packets": 3,
"bytes": 1676,
},
"rx_ls_req": {
"packets": 1,
"bytes": 36,
},
"rx_ls_upd": {
"packets": 14809,
"bytes": 1866264,
},
"rx_ls_ack": {
"packets": 877,
"bytes": 76028,
},
"rx_total": {
"packets": 86194,
"bytes": 5328196,
},
"tx_failed": {"packets": 0, "bytes": 0},
"tx_hello": {
"packets": 1,
"bytes": 100,
},
"tx_db_des": {
"packets": 4,
"bytes": 416,
},
"tx_ls_req": {
"packets": 1,
"bytes": 968,
},
"tx_ls_upd": {
"packets": 1,
"bytes": 108,
},
"tx_ls_ack": {
"packets": 117,
"bytes": 8668,
},
"tx_total": {
"packets": 124,
"bytes": 10260,
},
}
},
"ospf_header_errors": {
"length": 0,
"instance_id": 0,
"checksum": 0,
"auth_type": 0,
"version": 0,
"bad_source": 0,
"no_virtual_link": 0,
"area_mismatch": 0,
"no_sham_link": 0,
"self_originated": 0,
"duplicate_id": 0,
"hello": 0,
"mtu_mismatch": 0,
"nbr_ignored": 0,
"lls": 0,
"unknown_neighbor": 0,
"authentication": 0,
"ttl_check_fail": 0,
"adjacency_throttle": 0,
"bfd": 0,
"test_discard": 0,
},
"ospf_lsa_errors": {
"type": 0,
"length": 0,
"data": 0,
"checksum": 0,
},
},
}
},
"summary_traffic_statistics": {
"ospf_packets_received_sent": {
"type": {
"rx_invalid": {"packets": 0, "bytes": 0},
"rx_hello": {
"packets": 159187,
"bytes": 7640968,
},
"rx_db_des": {
"packets": 10240,
"bytes": 337720,
},
"rx_ls_req": {"packets": 5, "bytes": 216},
"rx_ls_upd": {
"packets": 31899,
"bytes": 4010656,
},
"rx_ls_ack": {"packets": 2511, "bytes": 201204},
"rx_total": {
"packets": 203842,
"bytes": 12190764,
},
"tx_failed": {"packets": 0, "bytes": 0},
"tx_hello": {
"packets": 208493,
"bytes": 20592264,
},
"tx_db_des": {
"packets": 10540,
"bytes": 15808320,
},
"tx_ls_req": {"packets": 5, "bytes": 3112},
"tx_ls_upd": {
"packets": 33998,
"bytes": 5309252,
},
"tx_ls_ack": {
"packets": 17571,
"bytes": 1220144,
},
"tx_total": {
"packets": 270607,
"bytes": 42933092,
},
}
},
"ospf_header_errors": {
"length": 0,
"instance_id": 0,
"checksum": 0,
"auth_type": 0,
"version": 0,
"bad_source": 0,
"no_virtual_link": 0,
"area_mismatch": 0,
"no_sham_link": 0,
"self_originated": 0,
"duplicate_id": 0,
"hello": 0,
"mtu_mismatch": 0,
"nbr_ignored": 2682,
"lls": 0,
"unknown_neighbor": 0,
"authentication": 0,
"ttl_check_fail": 0,
"adjacency_throttle": 0,
"bfd": 0,
"test_discard": 0,
},
"ospf_lsa_errors": {
"type": 0,
"length": 0,
"data": 0,
"checksum": 0,
},
},
},
}
}
}
}
},
"ospf_statistics": {
"last_clear_traffic_counters": "never",
"rcvd": {
"total": 204136,
"checksum_errors": 0,
"hello": 159184,
"database_desc": 10240,
"link_state_req": 5,
"link_state_updates": 31899,
"link_state_acks": 2511,
},
"sent": {
"total": 281838,
"hello": 219736,
"database_desc": 10540,
"link_state_req": 5,
"link_state_updates": 33998,
"link_state_acks": 17571,
},
},
}
|
# Write your solutions for 1.5 here!
class superheroes:
def __int__(self, name, superpower, strength):
self.name=name
self.superpower=superpower
self.strength=strength
def print_me(self):
print(self.name +str( self.strength))
superhero = superheroes("tamara","fly", 10)
superhero.print_me()
|
'''
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
'''
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
res = [1 for i in xrange(len(ratings))]
h = []
for i in xrange(len(ratings)):
heapq.heappush(h, (ratings[i], i))
while h:
v, i = heapq.heappop(h)
if 0 <= i-1:
if ratings[i-1] < ratings[i]:
res[i] = max(res[i], res[i-1]+1)
if i+1 < len(ratings):
if ratings[i] > ratings[i+1]:
res[i] = max(res[i], res[i+1]+1)
return sum(res)
|
N = int(input())
A, B, C = input(), input(), input()
ans = 0
for i in range(N):
abc = A[i], B[i], C[i]
ans += len(set(abc)) - 1
print(ans)
|
def lin(tam=42):
print('-' * tam)
def leia_int(menssage):
"""
-> Lê um número inteiro
:param menssage: chamada (descrição)
:return: :var numero: número inteiro após ser aprovado por tratamento de erro
"""
while True:
numero = input(menssage)
try:
numero = int(numero)
except (ValueError, TypeError):
print('\033[1;31mHouve um error! Por favor digite um número válido\033[m')
except KeyboardInterrupt:
print(f'\033[0;31mO usuario preferiu não informar\033[m')
except Exception as error:
print(f'O erro é {error.__class__}')
else:
return numero
def titulo(texto=''):
lin()
print(texto.center(42).upper())
lin()
def menu(lista):
titulo('Sistema principal')
c = 0
for item in lista:
c += 1
print(f'\033[0;33m{c}\033[m-\033[1;94m{item}\033[m')
lin()
opc = leia_int('\033[0;33mSua opção:\033[m ')
return opc
|
contador = 0
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 1
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 2
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 3
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 4
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 5
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 6
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 7
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 8
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
|
class Number:
def __init__(self):
self.num = 0
def setNum(self, x):
self.num = x
# na= Number()
# na.setNum(3)
# print(hasattr(na, 'id'))
a = ABCDEFGHIJKLMNOPQRSTUVWXYZ
b = BLUESKYACDFGHIJMNOPQRTVWXZ
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return (self.x, self.y)
def __add__(self, p2):
return 4
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)
|
n = int(input())
ans = 0
for i in range(n):
a, b = map(int, input().split())
ans += (a + b) * (b - a + 1) // 2
print(ans)
|
def is_leap(year):
leap = False
# Write your logic here
if (year%400) == 0:
leap = True
elif (year%100) == 0:
leap = False
elif (year%4) == 0:
leap = True
return leap
|
__version__ = '2.0.0'
print("*"*35)
print(f'SpotifyToVKStatus. Version: {__version__}')
print("*"*35)
|
file_name = input('Enter file name: ')
if file_name == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
exit()
else:
try:
file = open(file_name)
except:
print('File cannot be opened')
exit()
count = 0
numbers = 0
average = 0
for line in file:
if line.startswith('X-DSPAM-Confidence'):
colon_position = line.find(':')
numbers = numbers + float(line[colon_position+1:])
count = count + 1
if count != 0:
average = numbers / count
print(average)
|
""" Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file("out.txt")
ctx.actions.write(f, "contents")
def _source_list_rule_impl(ctx):
if len(ctx.attr.srcs) != 2:
fail("Expected two sources")
first = ctx.attr.srcs[0].short_path.replace("\\", "/")
second = ctx.attr.srcs[1].short_path.replace("\\", "/")
expected_first = "src.txt"
expected_second = "file__/out.txt"
if first != expected_first:
fail("Expected short path {}, got {}".format(expected_first, first))
if second != expected_second:
fail("Expected short path {}, got {}".format(expected_second, second))
f = ctx.actions.declare_file("out2.txt")
ctx.actions.write(f, "contents2")
write_file = rule(
attrs = {},
implementation = _write_file_impl,
)
source_list_rule = rule(
attrs = {"srcs": attr.source_list()},
implementation = _source_list_rule_impl,
)
|
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 1
prod = 9
for i in range(min(n, 10)):
cnt += prod
prod *= 9 - i
return cnt
|
#
# @lc app=leetcode id=46 lang=python3
#
# [46] Permutations
#
# @lc code=start
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
results = []
prev_elements = []
def dfs(elements):
if len(elements) == 0:
results.append(prev_elements[:])
for e in elements:
next_elements = elements[:]
next_elements.remove(e)
prev_elements.append(e)
dfs(next_elements)
prev_elements.pop()
# dfs(nums)
# return results
return list(itertools.permutations(nums))
# @lc code=end
|
def count_up(start, stop):
"""Print all numbers from start up to and including stop.
For example:
count_up(5, 7)
should print:
5
6
7
"""
# YOUR CODE HERE
# print(start)
# start += 1
# print(start)
# parameters can be modified
while start <= stop:
print(start)
start += 1
count_up(5, 7)
count_up(3, 8)
|
def user(*args):
blank=[]
for num in args:
blank+=1
return arg
user()
|
tag = 0
# Bestimme Uhrzeit, zu der Ebbe ist
ebbeStunde = 4.0
ebbeMinute = 47.0
println("Tag {} - Ebbe: {} Uhr und {} Minuten"
.format(tag, int(ebbeStunde), int(ebbeMinute)))
# Berechne Ebbezeit als Kommazahl
ebbeKomma = ebbeStunde + ebbeMinute / 60.0
# Berechne Zeit zwischen Ebbe und Ebbe als Kommazahl
tideStunden = 12.0
tideMinuten = 25.0
tideKomma = tideStunden + tideMinuten / 60.0
for i in range(0, 5):
# Berechne daraus Uhrzeit als Kommazahl, zu der Flut ist
flutKomma = (ebbeKomma + tideKomma / 2.0)
# Berechne den Tag
tag += int(flutKomma) / 24
# Rechne die Uhrzeit auf den Tag um
flutKomma %= 24
# Berechne Stunden und Minuten aus der Kommazahl
flutStunde = int(flutKomma)
flutMinute = int(flutKomma % 1 * 60)
println("Tag {} - Flut: {} Uhr und {} Minuten"
.format(tag, flutStunde, flutMinute))
# Berechne die nächste Ebbe
ebbeKomma = (ebbeKomma + tideKomma)
# Berechne den Tag
tag += int(ebbeKomma) / 24
# Rechne die Uhrzeit auf den Tag um
ebbeKomma %= 24
# Berechne Stunden und Minuten aus der Kommazahl
ebbeStunde = int(ebbeKomma)
ebbeMinute = int(ebbeKomma % 1 * 60)
println("Tag {} - Ebbe: {} Uhr und {} Minuten"
.format(tag, int(ebbeStunde), int(ebbeMinute)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.