content
stringlengths 7
1.05M
|
|---|
array = [0,0,1,1,1,1,2,2,2,2,3,3]
indexEqualCurrentUsage = []
for index in range(len(array)):
if array[index] == 1:
indexEqualCurrentUsage.append(index)
print(indexEqualCurrentUsage)
|
"""
We see many sharp peaks in the training set, but these peaks are not always present
in the test set, suggesting that they are due to noise. Therefore, ignoring this
noise, we might have expected the neural responses to be a sum of only a few
different filters and only at a few different positions. This would mean that we
would expect the `out_layer` weight matrix to be sparse, not dense like the one
shown here.
""";
|
### do not use these settings and passwords for production!
# these settings are required to connect the postgres-db to metabase
POSTGRES_USER='postgres'
POSTGRES_PASSWORD='1234'
POSTGRES_HOST='postgresdb'
POSTGRES_PORT='5432'
POSTGRES_DB_NAME='postgres'
|
def leiaInt(mgn):
while True:
try:
n = int(input(mgn))
except (ValueError, TypeError):
print('\033[031mErro: por favor, digite um número interio válido.\033[m')
else:
return n
break
def leiaFloat(mgn):
while True:
try:
n = float(input(mgn))
except (ValueError, TypeError):
print('\033[031mErro: por favor, digite um número real válido.\033[m')
else:
return f'{n:.2f}'
break
nu = leiaInt('Digite um valor inteiro: ')
fl = leiaFloat('Digite um número real: ')
print(f'O valor Inteiro é {nu} e o número real é {fl}')
|
# # Sunny data
# outFeaturesPath = "models/features_40_sun_only"
# outLabelsPath = "models/labels_sun_only"
# imageFolderName = 'IMG_sun_only'
# features_directory = '../data/'
# labels_file = '../data/driving_log_sun_only.csv'
# modelPath = 'models/MsAutopilot_sun_only.h5'
# NoColumns = 3 # steering value index in csv
# # Foggy data
# outFeaturesPath = "models/features_40_foggy"
# outLabelsPath = "models/labels_foggy"
# imageFolderName = 'IMG_foggy'
# features_directory = '../data/'
# labels_file = '../data/driving_log_foggy.csv'
# modelPath = 'models/MsAutopilot_foggy.h5'
# NoColumns = 6 # steering value index in csv
# # Test data (fog only, no model will be trained, just pickles to extract)
outFeaturesPath = "models/features_40_fog_only"
outLabelsPath = "models/labels_fog_only"
imageFolderName = 'IMG_fog_only'
features_directory = '../data/'
labels_file = '../data/driving_log_fog_only.csv'
NoColumns = 3 # steering value index in csv
modelPathFoggy = 'models/MsAutopilot_foggy.h5'
modelPathSunOnly = 'models/MsAutopilot_sun_only.h5'
|
with open('inputs/input2.txt') as fin:
raw = fin.read()
def parse(raw):
start = [(x[:3], int(x[4:])) for x in (raw.split('\n'))]
return start
a = parse(raw)
def part_1(arr):
indices = set()
acc = 0
i = 0
while i < len(arr):
pair = arr[i]
if i in indices:
break
indices.add(i)
if pair[0] == 'acc':
acc += pair[1]
i += 1
elif pair[0] == 'jmp':
i += pair[1]
else:
i += 1
return acc
def not_infinite(arr):
indices = set()
acc = 0
i = 0
while True:
if i in indices:
return 0
indices.add(i)
if i == len(arr):
return acc
pair = arr[i]
if pair[0] == 'acc':
acc += pair[1]
i += 1
elif pair[0] == 'jmp':
i += pair[1]
else:
i += 1
def part_2(arr):
for i, x in enumerate(arr):
if x[0] == 'jmp':
test = arr[:i] + [('nop', x[1])] + arr[i + 1:]
if c := not_infinite(test):
return c
if x[0] == 'nop':
test = arr[:i] + [('jmp', x[1])] + arr[(i + 1):]
if c := not_infinite(test):
return c
print(part_1(a))
print(part_2(a))
|
################################ A Library of Functions ##################################
##################################################################################################
#simple function which displays a matrix
def matrixDisplay(M):
for i in range(len(M)):
for j in range(len(M[i])):
print((M[i][j]), end = " ")
print()
##################################################################################################
#matrix product
def matrixProduct(L, M):
if len(L[0]) != len(M): #ensuring the plausiblity
print("Matrix multiplication not possible.")
else:
print("Multiplying the two matrices: ")
P=[[0 for i in range(len(M[0]))] for j in range(len(L))] #initializing empty matrix
for i in range(len(L)): #iterating rows
for j in range(len(M[0])): #iterating columns
for k in range(len(M)): #iterating elements and substituing them
P[i][j] = P[i][j] + (L[i][k] * M[k][j])
matrixDisplay(P)
##################################################################################################
#the gauss-jordan elimination code
def gaussj(a, b):
n = len(b) #defining the range through which the loops will run
for k in range(n): #loop to index pivot rows and eliminated columns
#partial pivoting
if abs(a[k][k]) < 1.0e-12:
for i in range(k+1, n):
if abs(a[i][k]) > abs(a[k][k]):
for j in range(k, n):
a[k][j], a[i][j] = a[i][j], a[k][j] #swapping of rows
b[k], b[i] = b[i], b[k]
break
#division of the pivot row
pivot = a[k][k]
if pivot == 0:
print("There is no unique solution to this system of equations.")
return
for j in range(k, n): #index of columns of the pivot row
a[k][j] /= pivot
b[k] /= pivot
#elimination loop
for i in range(n): #index of subtracted rows
if i == k or a[i][k] == 0: continue
factor = a[i][k]
for j in range(k, n): #index of columns for subtraction
a[i][j] -= factor * a[k][j]
b[i] -= factor * b[k]
print(b)
#################################################################################################
#calculation of determinant using gauss-jordan elimination
def determinant(a):
n = len(a) #defining the range through which the loops will run
if n != len(a[0]): #checking if determinant is possible to calculate
print("The matrix must be a square matrix.")
else:
s = 0
#code to obtain row echelon matrix using partial pivoting
for k in range(n-1):
if abs(a[k][k]) < 1.0e-12:
for i in range(k+1, n):
if abs(a[i][k]) > abs(a[k][k]):
for j in range(k, n):
a[k][j], a[i][j] = a[i][j], a[k][j] #swapping
s = s + 1 #counting the number of swaps happened
for i in range(k+1, n):
if a[i][k] == 0: continue
factor = a[i][k]/a[k][k]
for j in range(k, n):
a[i][j] = a[i][j] - factor * a[k][j]
d = 1
for i in range(len(a)):
d = d * a[i][i] #enlisting the diagonal elements
d = d*(-1)**s
print(d)
#################################################################################################
#calculating inverse
def inverse(a):
n = len(a) #defining the range through which loops will run
#constructing the n X 2n augmented matrix
P = [[0.0 for i in range(len(a))] for j in range(len(a))]
for i in range(3):
for j in range(3):
P[j][j] = 1.0
for i in range(len(a)):
a[i].extend(P[i])
#main loop for gaussian elimination begins here
for k in range(n):
if abs(a[k][k]) < 1.0e-12:
for i in range(k+1, n):
if abs(a[i][k]) > abs(a[k][k]):
for j in range(k, 2*n):
a[k][j], a[i][j] = a[i][j], a[k][j] #swapping of rows
break
pivot = a[k][k] #defining the pivot
if pivot == 0: #checking if matrix is invertible
print("This matrix is not invertible.")
return
else:
for j in range(k, 2*n): #index of columns of the pivot row
a[k][j] /= pivot
for i in range(n): #index the subtracted rows
if i == k or a[i][k] == 0: continue
factor = a[i][k]
for j in range(k, 2*n): #index the columns for subtraction
a[i][j] -= factor * a[k][j]
for i in range(len(a)): #displaying the matrix
for j in range(n, len(a[0])):
print("{:.2f}".format(a[i][j]), end = " ") #printing upto 2 places in decimal.
print()
|
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def DFS(root):
if not root: return 0
if not root.left and not root.right : return int(root.val)
if root.left: root.left.val = 10 * root.val + root.left.val
if root.right: root.right.val = 10 * root.val + root.right.val
return DFS(root.left) + DFS(root.right)
return DFS(root)
|
# Copyright (c) 2010-2022 openpyxl
"""
List of builtin formulae
"""
FORMULAE = ("CUBEKPIMEMBER", "CUBEMEMBER", "CUBEMEMBERPROPERTY", "CUBERANKEDMEMBER", "CUBESET", "CUBESETCOUNT", "CUBEVALUE", "DAVERAGE", "DCOUNT", "DCOUNTA", "DGET", "DMAX", "DMIN", "DPRODUCT", "DSTDEV", "DSTDEVP", "DSUM", "DVAR", "DVARP", "DATE", "DATEDIF", "DATEVALUE", "DAY", "DAYS360", "EDATE", "EOMONTH", "HOUR", "MINUTE", "MONTH", "NETWORKDAYS", "NETWORKDAYS.INTL", "NOW", "SECOND", "TIME", "TIMEVALUE", "TODAY", "WEEKDAY", "WEEKNUM", "WORKDAY ", "WORKDAY.INTL", "YEAR", "YEARFRAC", "BESSELI", "BESSELJ", "BESSELK", "BESSELY", "BIN2DEC", "BIN2HEX", "BIN2OCT", "COMPLEX", "CONVERT", "DEC2BIN", "DEC2HEX", "DEC2OCT", "DELTA", "ERF", "ERFC", "GESTEP", "HEX2BIN", "HEX2DEC", "HEX2OCT", "IMABS", "IMAGINARY", "IMARGUMENT", "IMCONJUGATE", "IMCOS", "IMDIV", "IMEXP", "IMLN", "IMLOG10", "IMLOG2", "IMPOWER", "IMPRODUCT", "IMREAL", "IMSIN", "IMSQRT", "IMSUB", "IMSUM", "OCT2BIN", "OCT2DEC", "OCT2HEX", "ACCRINT", "ACCRINTM", "AMORDEGRC", "AMORLINC", "COUPDAYBS", "COUPDAYS", "COUPDAYSNC", "COUPNCD", "COUPNUM", "COUPPCD", "CUMIPMT", "CUMPRINC", "DB", "DDB", "DISC", "DOLLARDE", "DOLLARFR", "DURATION", "EFFECT", "FV", "FVSCHEDULE", "INTRATE", "IPMT", "IRR", "ISPMT", "MDURATION", "MIRR", "NOMINAL", "NPER", "NPV", "ODDFPRICE", "ODDFYIELD", "ODDLPRICE", "ODDLYIELD", "PMT", "PPMT", "PRICE", "PRICEDISC", "PRICEMAT", "PV", "RATE", "RECEIVED", "SLN", "SYD", "TBILLEQ", "TBILLPRICE", "TBILLYIELD", "VDB", "XIRR", "XNPV", "YIELD", "YIELDDISC", "YIELDMAT", "CELL", "ERROR.TYPE", "INFO", "ISBLANK", "ISERR", "ISERROR", "ISEVEN", "ISLOGICAL", "ISNA", "ISNONTEXT", "ISNUMBER", "ISODD", "ISREF", "ISTEXT", "N", "NA", "TYPE", "AND", "FALSE", "IF", "IFERROR", "NOT", "OR", "TRUE ADDRESS", "AREAS", "CHOOSE", "COLUMN", "COLUMNS", "GETPIVOTDATA", "HLOOKUP", "HYPERLINK", "INDEX", "INDIRECT", "LOOKUP", "MATCH", "OFFSET", "ROW", "ROWS", "RTD", "TRANSPOSE", "VLOOKUP", "ABS", "ACOS", "ACOSH", "ASIN", "ASINH", "ATAN", "ATAN2", "ATANH", "CEILING", "COMBIN", "COS", "COSH", "DEGREES", "ECMA.CEILING", "EVEN", "EXP", "FACT", "FACTDOUBLE", "FLOOR", "GCD", "INT", "ISO.CEILING", "LCM", "LN", "LOG", "LOG10", "MDETERM", "MINVERSE", "MMULT", "MOD", "MROUND", "MULTINOMIAL", "ODD", "PI", "POWER", "PRODUCT", "QUOTIENT", "RADIANS", "RAND", "RANDBETWEEN", "ROMAN", "ROUND", "ROUNDDOWN", "ROUNDUP", "SERIESSUM", "SIGN", "SIN", "SINH", "SQRT", "SQRTPI", "SUBTOTAL", "SUM", "SUMIF", "SUMIFS", "SUMPRODUCT", "SUMSQ", "SUMX2MY2", "SUMX2PY2", "SUMXMY2", "TAN", "TANH", "TRUNC", "AVEDEV", "AVERAGE", "AVERAGEA", "AVERAGEIF", "AVERAGEIFS", "BETADIST", "BETAINV", "BINOMDIST", "CHIDIST", "CHIINV", "CHITEST", "CONFIDENCE", "CORREL", "COUNT", "COUNTA", "COUNTBLANK", "COUNTIF", "COUNTIFS", "COVAR", "CRITBINOM", "DEVSQ", "EXPONDIST", "FDIST", "FINV", "FISHER", "FISHERINV", "FORECAST", "FREQUENCY", "FTEST", "GAMMADIST", "GAMMAINV", "GAMMALN", "GEOMEAN", "GROWTH", "HARMEAN", "HYPGEOMDIST", "INTERCEPT", "KURT", "LARGE", "LINEST", "LOGEST", "LOGINV", "LOGNORMDIST", "MAX", "MAXA", "MEDIAN", "MIN", "MINA", "MODE", "NEGBINOMDIST", "NORMDIST", "NORMINV", "NORMSDIST", "NORMSINV", "PEARSON", "PERCENTILE", "PERCENTRANK", "PERMUT", "POISSON", "PROB", "QUARTILE", "RANK", "RSQ", "SKEW", "SLOPE", "SMALL", "STANDARDIZE", "STDEV STDEVA", "STDEVP", "STDEVPA STEYX", "TDIST", "TINV", "TREND", "TRIMMEAN", "TTEST", "VAR", "VARA", "VARP", "VARPA", "WEIBULL", "ZTEST", "ASC", "BAHTTEXT", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOLLAR", "EXACT", "FIND", "FINDB", "FIXED", "JIS", "LEFT", "LEFTB", "LEN", "LENB", "LOWER", "MID", "MIDB", "PHONETIC", "PROPER", "REPLACE", "REPLACEB", "REPT", "RIGHT", "RIGHTB", "SEARCH", "SEARCHB", "SUBSTITUTE", "T", "TEXT", "TRIM", "UPPER", "VALUE")
FORMULAE = frozenset(FORMULAE)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: network_device
short_description: Resource module for Network Device
description:
- Manage operations create, update and delete of the resource Network Device.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
NetworkDeviceGroupList:
description: List of Network Device Group names for this node.
elements: str
type: list
NetworkDeviceIPList:
description: List of IP Subnets for this node.
suboptions:
getIpaddressExclude:
description: It can be either single IP address or IP range address.
type: str
ipaddress:
description: Network Device's ipaddress.
type: str
mask:
description: Network Device's mask.
type: int
type: list
authenticationSettings:
description: Network Device's authenticationSettings.
suboptions:
dtlsRequired:
description: This value enforces use of dtls.
type: bool
enableKeyWrap:
description: EnableKeyWrap flag.
type: bool
enableMultiSecret:
description: EnableMultiSecret flag.
type: bool
enabled:
description: Enabled flag.
type: bool
keyEncryptionKey:
description: Network Device's keyEncryptionKey.
type: str
keyInputFormat:
description: Allowed values - ASCII, - HEXADECIMAL.
type: str
messageAuthenticatorCodeKey:
description: Network Device's messageAuthenticatorCodeKey.
type: str
networkProtocol:
description: Allowed values - RADIUS, - TACACS_PLUS.
type: str
radiusSharedSecret:
description: Network Device's radiusSharedSecret.
type: str
secondRadiusSharedSecret:
description: Network Device's secondRadiusSharedSecret.
type: str
type: dict
coaPort:
description: Network Device's coaPort.
type: int
description:
description: Network Device's description.
type: str
dtlsDnsName:
description: This value is used to verify the client identity contained in the X.509
RADIUS/DTLS client certificate.
type: str
id:
description: Network Device's id.
type: str
modelName:
description: Network Device's modelName.
type: str
name:
description: Network Device's name.
type: str
profileName:
description: Network Device's profileName.
type: str
snmpsettings:
description: Network Device's snmpsettings.
suboptions:
linkTrapQuery:
description: LinkTrapQuery flag.
type: bool
macTrapQuery:
description: MacTrapQuery flag.
type: bool
originatingPolicyServicesNode:
description: Network Device's originatingPolicyServicesNode.
type: str
pollingInterval:
description: Network Device's pollingInterval.
type: int
roCommunity:
description: Network Device's roCommunity.
type: str
version:
description: Network Device's version.
type: str
type: dict
softwareVersion:
description: Network Device's softwareVersion.
type: str
tacacsSettings:
description: Network Device's tacacsSettings.
suboptions:
connectModeOptions:
description: Allowed values - OFF, - ON_LEGACY, - ON_DRAFT_COMPLIANT.
type: str
sharedSecret:
description: Network Device's sharedSecret.
type: str
type: dict
trustsecsettings:
description: Network Device's trustsecsettings.
suboptions:
deviceAuthenticationSettings:
description: Network Device's deviceAuthenticationSettings.
suboptions:
sgaDeviceId:
description: Network Device's sgaDeviceId.
type: str
sgaDevicePassword:
description: Network Device's sgaDevicePassword.
type: str
type: dict
deviceConfigurationDeployment:
description: Network Device's deviceConfigurationDeployment.
suboptions:
enableModePassword:
description: Network Device's enableModePassword.
type: str
execModePassword:
description: Network Device's execModePassword.
type: str
execModeUsername:
description: Network Device's execModeUsername.
type: str
includeWhenDeployingSGTUpdates:
description: IncludeWhenDeployingSGTUpdates flag.
type: bool
type: dict
pushIdSupport:
description: PushIdSupport flag.
type: bool
sgaNotificationAndUpdates:
description: Network Device's sgaNotificationAndUpdates.
suboptions:
coaSourceHost:
description: Network Device's coaSourceHost.
type: str
downlaodEnvironmentDataEveryXSeconds:
description: Network Device's downlaodEnvironmentDataEveryXSeconds.
type: int
downlaodPeerAuthorizationPolicyEveryXSeconds:
description: Network Device's downlaodPeerAuthorizationPolicyEveryXSeconds.
type: int
downloadSGACLListsEveryXSeconds:
description: Network Device's downloadSGACLListsEveryXSeconds.
type: int
otherSGADevicesToTrustThisDevice:
description: OtherSGADevicesToTrustThisDevice flag.
type: bool
reAuthenticationEveryXSeconds:
description: Network Device's reAuthenticationEveryXSeconds.
type: int
sendConfigurationToDevice:
description: SendConfigurationToDevice flag.
type: bool
sendConfigurationToDeviceUsing:
description: Allowed values - ENABLE_USING_COA, - ENABLE_USING_CLI, - DISABLE_ALL.
type: str
type: dict
type: dict
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: Network Device reference
description: Complete reference of the Network Device object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Update by name
cisco.ise.network_device:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
NetworkDeviceGroupList:
- string
NetworkDeviceIPList:
- getIpaddressExclude: string
ipaddress: string
mask: 0
authenticationSettings:
dtlsRequired: true
enableKeyWrap: true
enableMultiSecret: true
enabled: true
keyEncryptionKey: string
keyInputFormat: string
messageAuthenticatorCodeKey: string
networkProtocol: string
radiusSharedSecret: string
secondRadiusSharedSecret: string
coaPort: 0
description: string
dtlsDnsName: string
id: string
modelName: string
name: string
profileName: string
snmpsettings:
linkTrapQuery: true
macTrapQuery: true
originatingPolicyServicesNode: string
pollingInterval: 0
roCommunity: string
version: string
softwareVersion: string
tacacsSettings:
connectModeOptions: string
sharedSecret: string
trustsecsettings:
deviceAuthenticationSettings:
sgaDeviceId: string
sgaDevicePassword: string
deviceConfigurationDeployment:
enableModePassword: string
execModePassword: string
execModeUsername: string
includeWhenDeployingSGTUpdates: true
pushIdSupport: true
sgaNotificationAndUpdates:
coaSourceHost: string
downlaodEnvironmentDataEveryXSeconds: 0
downlaodPeerAuthorizationPolicyEveryXSeconds: 0
downloadSGACLListsEveryXSeconds: 0
otherSGADevicesToTrustThisDevice: true
reAuthenticationEveryXSeconds: 0
sendConfigurationToDevice: true
sendConfigurationToDeviceUsing: string
- name: Delete by name
cisco.ise.network_device:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: absent
name: string
- name: Update by id
cisco.ise.network_device:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
NetworkDeviceGroupList:
- string
NetworkDeviceIPList:
- getIpaddressExclude: string
ipaddress: string
mask: 0
authenticationSettings:
dtlsRequired: true
enableKeyWrap: true
enableMultiSecret: true
enabled: true
keyEncryptionKey: string
keyInputFormat: string
messageAuthenticatorCodeKey: string
networkProtocol: string
radiusSharedSecret: string
secondRadiusSharedSecret: string
coaPort: 0
description: string
dtlsDnsName: string
id: string
modelName: string
name: string
profileName: string
snmpsettings:
linkTrapQuery: true
macTrapQuery: true
originatingPolicyServicesNode: string
pollingInterval: 0
roCommunity: string
version: string
softwareVersion: string
tacacsSettings:
connectModeOptions: string
sharedSecret: string
trustsecsettings:
deviceAuthenticationSettings:
sgaDeviceId: string
sgaDevicePassword: string
deviceConfigurationDeployment:
enableModePassword: string
execModePassword: string
execModeUsername: string
includeWhenDeployingSGTUpdates: true
pushIdSupport: true
sgaNotificationAndUpdates:
coaSourceHost: string
downlaodEnvironmentDataEveryXSeconds: 0
downlaodPeerAuthorizationPolicyEveryXSeconds: 0
downloadSGACLListsEveryXSeconds: 0
otherSGADevicesToTrustThisDevice: true
reAuthenticationEveryXSeconds: 0
sendConfigurationToDevice: true
sendConfigurationToDeviceUsing: string
- name: Delete by id
cisco.ise.network_device:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: absent
id: string
- name: Create
cisco.ise.network_device:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
NetworkDeviceGroupList:
- string
NetworkDeviceIPList:
- getIpaddressExclude: string
ipaddress: string
mask: 0
authenticationSettings:
dtlsRequired: true
enableKeyWrap: true
enableMultiSecret: true
enabled: true
keyEncryptionKey: string
keyInputFormat: string
messageAuthenticatorCodeKey: string
networkProtocol: string
radiusSharedSecret: string
secondRadiusSharedSecret: string
coaPort: 0
description: string
dtlsDnsName: string
modelName: string
name: string
profileName: string
snmpsettings:
linkTrapQuery: true
macTrapQuery: true
originatingPolicyServicesNode: string
pollingInterval: 0
roCommunity: string
version: string
softwareVersion: string
tacacsSettings:
connectModeOptions: string
sharedSecret: string
trustsecsettings:
deviceAuthenticationSettings:
sgaDeviceId: string
sgaDevicePassword: string
deviceConfigurationDeployment:
enableModePassword: string
execModePassword: string
execModeUsername: string
includeWhenDeployingSGTUpdates: true
pushIdSupport: true
sgaNotificationAndUpdates:
coaSourceHost: string
downlaodEnvironmentDataEveryXSeconds: 0
downlaodPeerAuthorizationPolicyEveryXSeconds: 0
downloadSGACLListsEveryXSeconds: 0
otherSGADevicesToTrustThisDevice: true
reAuthenticationEveryXSeconds: 0
sendConfigurationToDevice: true
sendConfigurationToDeviceUsing: string
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"UpdatedFieldsList": {
"updatedField": {
"field": "string",
"oldValue": "string",
"newValue": "string"
},
"field": "string",
"oldValue": "string",
"newValue": "string"
}
}
"""
|
class OrderCodeAlreadyExists(Exception):
pass
class DealerDoesNotExist(Exception):
pass
class OrderDoesNotExist(Exception):
pass
class StatusNotAllowed(Exception):
pass
|
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
_DIGITS = {
' ': 0x00,
'-': 0x01,
'_': 0x08,
'\'': 0x02,
'0': 0x7e,
'1': 0x30,
'2': 0x6d,
'3': 0x79,
'4': 0x33,
'5': 0x5b,
'6': 0x5f,
'7': 0x70,
'8': 0x7f,
'9': 0x7b,
'a': 0x7d,
'b': 0x1f,
'c': 0x0d,
'd': 0x3d,
'e': 0x6f,
'f': 0x47,
'g': 0x7b,
'h': 0x17,
'i': 0x10,
'j': 0x18,
# 'k': cant represent
'l': 0x06,
# 'm': cant represent
'n': 0x15,
'o': 0x1d,
'p': 0x67,
'q': 0x73,
'r': 0x05,
's': 0x5b,
't': 0x0f,
'u': 0x1c,
'v': 0x1c,
# 'w': cant represent
# 'x': cant represent
'y': 0x3b,
'z': 0x6d,
'A': 0x77,
'B': 0x7f,
'C': 0x4e,
'D': 0x7e,
'E': 0x4f,
'F': 0x47,
'G': 0x5e,
'H': 0x37,
'I': 0x30,
'J': 0x38,
# 'K': cant represent
'L': 0x0e,
# 'M': cant represent
'N': 0x76,
'O': 0x7e,
'P': 0x67,
'Q': 0x73,
'R': 0x46,
'S': 0x5b,
'T': 0x0f,
'U': 0x3e,
'V': 0x3e,
# 'W': cant represent
# 'X': cant represent
'Y': 0x3b,
'Z': 0x6d,
',': 0x80,
'.': 0x80
}
def regular(text, notfound="_"):
try:
undefined = _DIGITS[notfound]
iterator = iter(text)
while True:
char = next(iterator)
yield _DIGITS.get(char, undefined)
except StopIteration:
pass
def dot_muncher(text, notfound="_"):
undefined = _DIGITS[notfound]
iterator = iter(text)
last = _DIGITS.get(next(iterator), undefined)
try:
while True:
curr = _DIGITS.get(next(iterator), undefined)
if curr == 0x80:
yield curr | last
elif last != 0x80:
yield last
last = curr
except StopIteration:
if last != 0x80:
yield last
|
"""Hex Grid, by Al Sweigart al@inventwithpython.com
Displays a simple tessellation of a hexagon grid.
This and other games are available at https://nostarch.com/XX
Tags: tiny, beginner, artistic"""
__version__ = 0
# Set up the constants:
# (!) Try changing these values to other numbers:
X_REPEAT = 19 # How many times to tessellate horizontally.
Y_REPEAT = 12 # How many times to tessellate vertically.
for y in range(Y_REPEAT):
# Display the top half of the hexagon:
for x in range(X_REPEAT):
print(r'/ \_', end='')
print()
# Display the bottom half of the hexagon:
for x in range(X_REPEAT):
print(r'\_/ ', end='')
print()
|
class FlameTextEdit(QtWidgets.QTextEdit):
"""
Custom Qt Flame Text Edit Widget
To use:
text_edit = FlameTextEdit('some_text_here', True_or_False, window)
"""
def __init__(self, text, read_only, parent_window, *args, **kwargs):
super(FlameTextEdit, self).__init__(*args, **kwargs)
self.setMinimumHeight(50)
self.setMinimumWidth(150)
self.setReadOnly(read_only)
if read_only:
self.setStyleSheet('color: #9a9a9a; selection-color: #262626; selection-background-color: #b8b1a7; border: 1px inset #404040; font: 14px "Discreet"')
else:
self.setStyleSheet('QTextEdit {color: #9a9a9a; background-color: #373e47; selection-color: #262626; selection-background-color: #b8b1a7; border: 1px inset #404040; font: 14px "Discreet"}'
'QTextEdit:focus {background-color: #474e58}')
self.verticalScrollBar().setStyleSheet('color: #818181; background-color: #313131')
self.horizontalScrollBar().setStyleSheet('color: #818181; background-color: #313131')
|
# -*- coding: utf-8 -*-
# 服务市场服务
class MarketService:
__client = None
def __init__(self, client):
self.__client = client
def sync_market_messages(self, start, end, offset, limit):
"""
同步某一段时间内的服务市场消息
:param start:开始时间
:param end:结束时间
:param offset:消息偏移量
:param limit:查询消息数
"""
return self.__client.call("eleme.market.syncMarketMessages", {"start": start, "end": end, "offset": offset, "limit": limit})
def create_order(self, request):
"""
创建内购项目订单
:param request:创建订单请求信息
"""
return self.__client.call("eleme.market.createOrder", {"request": request})
def query_order(self, order_no):
"""
查询服务市场订单
:param orderNo:服务市场订单编号
"""
return self.__client.call("eleme.market.queryOrder", {"orderNo": order_no})
def confirm_order(self, order_no):
"""
服务市场确认订单
:param orderNo:服务市场订单编号
"""
return self.__client.call("eleme.market.confirmOrder", {"orderNo": order_no})
|
# merge sort
# h/t https://www.thecrazyprogrammer.com/2017/12/python-merge-sort.html
# h/t https://www.youtube.com/watch?v=Nso25TkBsYI
def merge_sort(array):
n = len(array)
if n > 1:
mid = n//2
left = array[0:mid]
right = array[mid:n]
print(mid, left, right, array)
merge_sort(left)
merge_sort(right)
merge(left, right, array, n)
def merge(left, right, array, array_length):
right_length = len(right)
left_length = len(left)
left_index = right_index = 0
for array_index in range(0, array_length):
if right_index == right_length:
array[array_index:array_length] = left[left_index:left_length]
break
elif left_index == left_length:
array[array_index:array_length] = right[right_index:right_length]
break
elif left[left_index] <= right[right_index]:
array[array_index] = left[left_index]
left_index += 1
else:
array[array_index] = right[right_index]
right_index += 1
array = [99,2,3,3,12,4,5]
arr_len = len(array)
merge_sort(array)
print(array)
assert len(array) == arr_len
|
def ATWGetListKeyTxt(KeyTxt,List,NewTxt,sel):
global ATWGetListKeyTxt0
global ATWGetListKeyTxt1Nb
ATWGetListKeyTxt0 = []
ATWGetListKeyTxt0.clear()
if sel == 'LGT':
# kw = List 中所有
for kw in List:
# 如 關鍵字在 add list
if KeyTxt in kw:
ATWGetListKeyTxt0.append(kw)
if sel == 'LCT':
# List 轉新 關鍵字
i = 0
while i < len(List):
ttt = List[i] # QQQQQQQQ
if KeyTxt == ttt:
#print(' List[',i,'] =\n{',List[i],'}\n')
List[i] = NewTxt+"\n"
ATWGetListKeyTxt1Nb = i
#print(' List[',i,'] =\n{',List[i],'}\n')
i+=1
for kw in List:
ATWGetListKeyTxt0.append(kw)
#print(' ATWGetListKeyTxt0 =\n{',ATWGetListKeyTxt0,'}\n')
###########################################
# sel == 'LGT' == List中找關鍵字
# sel == 'LCT' == List 轉新 關鍵字
|
# Lucas Sequence Using Recursion
def recur_luc(n):
if n == 1:
return n
if n == 0:
return 2
return (recur_luc(n-1) + recur_luc(n-2))
limit = int(input("How many terms to include in Lucas series:"))
print("Lucas series:")
for i in range(limit):
print(recur_luc(i))
|
# encoding: utf-8
"""Exceptions used by marrow.mailer to report common errors."""
__all__ = [
'MailException',
'MailConfigurationException',
'TransportException',
'TransportFailedException',
'MessageFailedException',
'TransportExhaustedException',
'ManagerException'
]
class MailException(Exception):
"""The base for all marrow.mailer exceptions."""
pass
# Application Exceptions
class DeliveryException(MailException):
"""The base class for all public-facing exceptions."""
pass
class DeliveryFailedException(DeliveryException):
"""The message stored in args[0] could not be delivered for the reason
given in args[1]. (These can be accessed as e.msg and e.reason.)"""
def __init__(self, message, reason):
self.msg = message
self.reason = reason
super(DeliveryFailedException, self).__init__(message, reason)
# Internal Exceptions
class MailerNotRunning(MailException):
"""Raised when attempting to deliver messages using a dead interface."""
pass
class MailConfigurationException(MailException):
"""There was an error in the configuration of marrow.mailer."""
pass
class TransportException(MailException):
"""The base for all marrow.mailer Transport exceptions."""
pass
class TransportFailedException(TransportException):
"""The transport has failed to deliver the message due to an internal
error; a new instance of the transport should be used to retry."""
pass
class MessageFailedException(TransportException):
"""The transport has failed to deliver the message due to a problem with
the message itself, and no attempt should be made to retry delivery of
this message. The transport may still be re-used, however.
The reason for the failure should be the first argument.
"""
pass
class TransportExhaustedException(TransportException):
"""The transport has successfully delivered the message, but can no longer
be used for future message delivery; a new instance should be used on the
next request."""
pass
class ManagerException(MailException):
"""The base for all marrow.mailer Manager exceptions."""
pass
|
#
# PySNMP MIB module RBN-SYS-SECURITY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-SYS-SECURITY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:53:26 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")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint")
CounterBasedGauge64, = mibBuilder.importSymbols("HCNUM-TC", "CounterBasedGauge64")
rbnModules, = mibBuilder.importSymbols("RBN-SMI", "rbnModules")
RbnUnsigned64, = mibBuilder.importSymbols("RBN-TC", "RbnUnsigned64")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
MibIdentifier, ModuleIdentity, Bits, Gauge32, NotificationType, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Counter64, iso, Unsigned32, IpAddress, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "ModuleIdentity", "Bits", "Gauge32", "NotificationType", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Counter64", "iso", "Unsigned32", "IpAddress", "Integer32", "ObjectIdentity")
DisplayString, TextualConvention, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "DateAndTime")
rbnSysSecurityMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 2352, 5, 54))
rbnSysSecurityMib.setRevisions(('2009-11-09 18:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rbnSysSecurityMib.setRevisionsDescriptions(('Initial version',))
if mibBuilder.loadTexts: rbnSysSecurityMib.setLastUpdated('200911091800Z')
if mibBuilder.loadTexts: rbnSysSecurityMib.setOrganization('Ericsson Inc.')
if mibBuilder.loadTexts: rbnSysSecurityMib.setContactInfo(' Ericsson Inc. 100 Headquarters Drive San Jose, CA 95134 USA Phone: +1 408 750 5000 Fax: +1 408 750 5599 ')
if mibBuilder.loadTexts: rbnSysSecurityMib.setDescription('This MIB module defines attributes and notifications related to system and network level security issues. All mib objects defined in the module are viewed within the context identified in the SNMP protocol (i.e. the community string in v1/v2c or the contextName in v3). ')
rbnSysSecNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 0))
rbnSysSecObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1))
rbnSysSecConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2))
rbnSysSecThresholdObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 1))
rbnSysSecNotifyEnable = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 1, 1), Bits().clone(namedValues=NamedValues(("maliciousPkt", 0)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rbnSysSecNotifyEnable.setStatus('current')
if mibBuilder.loadTexts: rbnSysSecNotifyEnable.setDescription('The bit mask to enable/disable notifications for crossing specific threshold.')
rbnMeasurementInterval = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 1, 2), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(1, 3600)).clone(60)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rbnMeasurementInterval.setStatus('current')
if mibBuilder.loadTexts: rbnMeasurementInterval.setDescription('Data is sampled at the start and end of a specified interval. The difference between the start and end values |end - start| is called the delta value. When setting the interval, care should be taken that the interval should be short enough that the sampled variable is very unlikely to increase or decrease by more than range of the variable. ')
rbnMaliciousPktsThresholdHi = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 1, 3), RbnUnsigned64()).setUnits('Packets').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rbnMaliciousPktsThresholdHi.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktsThresholdHi.setDescription('When the current sampling interval delta value of the malicious packets counter is greater than or equal to this threshold, and the delta value at the last sampling interval was less than this threshold, a single high threshold exceeded event will be generated. A single high threshold exceeded event will also be generated if the first sampling interval delta value of the malicious IP packets counter is greater than or equal to this threshold. After a high threshold exceeded event is generated, another such event will not be generated until the delta value falls below this threshold and reaches the rbnMaliciousPktsThresholdLow, generating a low threshold exceeded event. In other words there cannot be successive high threshold events without an intervening low threshold event. ')
rbnMaliciousPktsThresholdLow = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 1, 4), RbnUnsigned64()).setUnits('Packets').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rbnMaliciousPktsThresholdLow.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktsThresholdLow.setDescription('When the current sampling interval delta value of the malicious packets counter is less than or equal to this threshold, and the delta value at the last sampling interval was greater than this threshold, a single low threshold exceeded event will be generated. In addition, a high threshold exceeded event must occur before a low threshold exceeded event can be generated. ')
rbnSysSecStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 2))
rbnMaliciousPktsCounter = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 2, 1), Counter64()).setUnits('Packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: rbnMaliciousPktsCounter.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktsCounter.setDescription('A count of all malicious pkts. This includes but is not limited to malformed IP packets, malformed layer 4 IP, packets filtered by ACLs for specific faults, IP packets identified as attempting to spoof a system, and IP packets which failed reassembly.')
rbnMaliciousPktsDelta = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 2, 2), CounterBasedGauge64()).setUnits('packets').setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: rbnMaliciousPktsDelta.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktsDelta.setDescription('The delta value of rbnMaliciousPktsCounter at the most recently completed measurement interval.')
rbnSysSecNotifyObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 4))
rbnThresholdNotifyTime = MibScalar((1, 3, 6, 1, 4, 1, 2352, 5, 54, 1, 4, 1), DateAndTime()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: rbnThresholdNotifyTime.setStatus('current')
if mibBuilder.loadTexts: rbnThresholdNotifyTime.setDescription('The DateAndTime of the notification.')
rbnMaliciousPktThresholdHiExceeded = NotificationType((1, 3, 6, 1, 4, 1, 2352, 5, 54, 0, 1))
if mibBuilder.loadTexts: rbnMaliciousPktThresholdHiExceeded.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktThresholdHiExceeded.setDescription('This notification signifies that one of the delta values is equal to or greater than the corresponding high threshold value. The specific delta value is the last object in the notification varbind list. ')
rbnMaliciousPktThresholdLowExceeded = NotificationType((1, 3, 6, 1, 4, 1, 2352, 5, 54, 0, 2)).setObjects(("RBN-SYS-SECURITY-MIB", "rbnThresholdNotifyTime"))
if mibBuilder.loadTexts: rbnMaliciousPktThresholdLowExceeded.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktThresholdLowExceeded.setDescription('This notification signifies that one of the delta values is less than or equal to the corresponding low threshold value. The specific delta value is the last object in the notification varbind list. ')
rbnSysSecCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 1))
rbnSysSecGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 2))
rbnMaliciousPktGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 2, 1)).setObjects(("RBN-SYS-SECURITY-MIB", "rbnSysSecNotifyEnable"), ("RBN-SYS-SECURITY-MIB", "rbnMeasurementInterval"), ("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktsThresholdHi"), ("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktsThresholdLow"), ("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktsCounter"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnMaliciousPktGroup = rbnMaliciousPktGroup.setStatus('current')
if mibBuilder.loadTexts: rbnMaliciousPktGroup.setDescription('Set of objects for the group.')
rbnSysSecNotifyObjectsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 2, 4)).setObjects(("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktsDelta"), ("RBN-SYS-SECURITY-MIB", "rbnThresholdNotifyTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnSysSecNotifyObjectsGroup = rbnSysSecNotifyObjectsGroup.setStatus('current')
if mibBuilder.loadTexts: rbnSysSecNotifyObjectsGroup.setDescription('Set of objects for the group.')
rbnSysSecNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 2, 5)).setObjects(("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktThresholdHiExceeded"), ("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktThresholdLowExceeded"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnSysSecNotificationGroup = rbnSysSecNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: rbnSysSecNotificationGroup.setDescription('Set of notifications for the group.')
rbnSysSecCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2352, 5, 54, 2, 1, 1)).setObjects(("RBN-SYS-SECURITY-MIB", "rbnMaliciousPktGroup"), ("RBN-SYS-SECURITY-MIB", "rbnSysSecNotifyObjectsGroup"), ("RBN-SYS-SECURITY-MIB", "rbnSysSecNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnSysSecCompliance = rbnSysSecCompliance.setStatus('current')
if mibBuilder.loadTexts: rbnSysSecCompliance.setDescription('The compliance statement for support of this mib module.')
mibBuilder.exportSymbols("RBN-SYS-SECURITY-MIB", rbnMeasurementInterval=rbnMeasurementInterval, rbnSysSecConformance=rbnSysSecConformance, rbnMaliciousPktThresholdHiExceeded=rbnMaliciousPktThresholdHiExceeded, rbnSysSecNotifications=rbnSysSecNotifications, rbnSysSecCompliances=rbnSysSecCompliances, rbnSysSecGroups=rbnSysSecGroups, rbnSysSecNotifyObjectsGroup=rbnSysSecNotifyObjectsGroup, rbnMaliciousPktGroup=rbnMaliciousPktGroup, rbnSysSecObjects=rbnSysSecObjects, rbnMaliciousPktsThresholdHi=rbnMaliciousPktsThresholdHi, rbnSysSecCompliance=rbnSysSecCompliance, rbnSysSecNotifyObjects=rbnSysSecNotifyObjects, rbnSysSecThresholdObjects=rbnSysSecThresholdObjects, rbnSysSecNotificationGroup=rbnSysSecNotificationGroup, PYSNMP_MODULE_ID=rbnSysSecurityMib, rbnSysSecNotifyEnable=rbnSysSecNotifyEnable, rbnMaliciousPktsCounter=rbnMaliciousPktsCounter, rbnMaliciousPktsThresholdLow=rbnMaliciousPktsThresholdLow, rbnSysSecStatsObjects=rbnSysSecStatsObjects, rbnMaliciousPktThresholdLowExceeded=rbnMaliciousPktThresholdLowExceeded, rbnThresholdNotifyTime=rbnThresholdNotifyTime, rbnSysSecurityMib=rbnSysSecurityMib, rbnMaliciousPktsDelta=rbnMaliciousPktsDelta)
|
lines = open('input.txt').read().splitlines()
matches = {'(': ')', '[': ']', '{': '}', '<': '>'}
penalty = {')': 3, ']': 57, '}': 1197, '>': 25137}
costs = {')': 1, ']': 2, '}': 3, '>': 4}
errors = []
incpl_costs = []
for i, l in enumerate(lines):
expected_closings = []
for c in l:
if c in matches.keys():
expected_closings.append(matches[c])
else:
if expected_closings[-1] != c:
# corrupted
errors.append((i, c))
break
else:
del expected_closings[-1]
if not errors or errors[-1][0] != i:
# incomplete
cur_costs = 0
for c in expected_closings[::-1]:
cur_costs = cur_costs * 5 + costs[c]
incpl_costs.append(cur_costs)
print(sum(penalty[c] for _, c in errors))
print(sorted(incpl_costs)[len(incpl_costs) // 2])
|
# Time: O(n^2)
# Space: O(1)
# 892
# On a N * N grid, we place some 1 * 1 * 1 cubes.
#
# Each value v = grid[i][j] represents a tower of v cubes
# placed on top of grid cell (i, j).
#
# Return the total surface area of the resulting shapes.
#
# Example 1:
#
# Input: [[2]]
# Output: 10
# Example 2:
#
# Input: [[1,2],[3,4]]
# Output: 34
# Example 3:
#
# Input: [[1,0],[0,2]]
# Output: 16
# Example 4:
#
# Input: [[1,1,1],[1,0,1],[1,1,1]]
# Output: 32
# Example 5:
#
# Input: [[2,2,2],[2,1,2],[2,2,2]]
# Output: 46
#
# Note:
# - 1 <= N <= 50
# - 0 <= grid[i][j] <= 50
class Solution(object):
def surfaceArea(self, grid): # USE THIS: minus joint surface, 36 ms
"""
:type grid: List[List[int]]
:rtype: int
"""
result = 0
for i in xrange(len(grid)):
for j in xrange(len(grid)):
if grid[i][j]:
result += 2 + grid[i][j]*4
if i:
result -= min(grid[i][j], grid[i-1][j])*2
if j:
result -= min(grid[i][j], grid[i][j-1])*2
return result
# look at 4 neighbors of each cell, add contribution if higher than neighbor. Avoid double count
# 56 ms
def surfaceArea2(self, grid):
n, ans = len(grid), 0
for i in xrange(n):
for j in xrange(n):
if grid[i][j]:
ans += 2
for nx, ny in [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]:
if 0<=nx<n and 0<=ny<n:
nei_val = grid[nx][ny]
else:
nei_val = 0
ans += max(0, grid[i][j]-nei_val)
return ans
# add difference between neighboring cells: iterate more times
def surfaceArea3(self, grid):
ans = 0
for row in grid:
ans += 2*sum(c>0 for c in row)
rrow = [0]+row+[0]
ans += sum(abs(rrow[i]-rrow[i+1]) for i in xrange(len(rrow)-1))
for col in zip(*grid):
col = (0,)+col+(0,) # KENG: zip's result is tuple which cannot concatenate to list
ans += sum(abs(col[i]-col[i+1]) for i in xrange(len(col)-1))
return ans
|
# 1109. Corporate Flight Bookings
# Weekly Contest 144
# Time: O(len(n))
# Space: O(n)
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
"""
Shorter solution:
"""
res = [0]*(n+1)
for i,j,k in bookings:
res[i-1]+=k
res[j]-=k
for i in range(1,n):
res[i]+=res[i-1]
return res[:-1]
"""
Longer Solution
"""
result = [{} for _ in range(n)]
for booking in bookings:
i,j,k = booking[0],booking[1],booking[2]
if 'start' in result[i-1]:
result[i-1]['start']+=k
else:
result[i-1]['start']=k
if 'end' in result[j-1]:
result[j-1]['end']+=k
else:
result[j-1]['end']=k
adder = 0
seats = [0]*n
for index,flight in enumerate(result):
if 'start' in flight:
adder+=flight['start']
seats[index]+=adder
if 'end' in flight:
adder-=flight['end']
return seats
|
# Given a sorted array of integers, find the starting and ending position of a given target value.
# Your algorithm's runtime complexity must be in the order of O(log n).
# If the target is not found in the array, return [-1, -1].
# For example,
# Given [5, 7, 7, 8, 8, 10] and target value 8,
# return [3, 4].
def search_range(numbers, target):
result = [-1, -1]
if len(numbers) == 0:
return result
low = 0
high = len(numbers) - 1
while low <= high:
mid = low + (high - low) // 2
if numbers[mid] >= target:
high = mid - 1
else:
low = mid + 1
if low < len(numbers) and numbers[low] == target:
result[0] = low
else:
return result
high = len(numbers) - 1
while low <= high:
mid = low + (high - low) // 2
if numbers[mid] <= target:
low = mid + 1
else:
high = mid - 1
result[1] = high
return result
if __name__ == '__main__':
array = [5, 7, 7, 8, 8, 10]
target = 8
print('The range of', target, 'in array',
array, 'is:', search_range(array, target))
|
# Foi colocado a função strip() no final da primeira linha para já garantir a eliminação dos espaços no começo
# e final do nome caso alguém digite na hora de inserir o nome
nome = str(input('Digite seu nome completo: ')).strip()
print('\033[31mTodas as letras maiúsculas\033[m {}'.format(nome.upper()))
print('\033[32mTodas as letras minúsculas\033[m {}'.format(nome.lower()))
print('\033[33mQuantidade de letras sem espaço\033[m {}'.format(len(''.join(nome.split()))))
# Outra forma de contar a quantidade de letras sem contar os espaços
#print('Quantidade de letras sem espaço {}'.format(len(nome) - nome.count(' ')))
print('\033[34mQuantidade de letras no primeiro nome {}\033[m'.format(len(nome.split()[0])))
# Outra forma de contar a quantidade de letras do primeiro nome
#print('Quantidade de letas no primeiro nome {}'.format(nome.find(' ')))
|
# -*- coding: utf-8 -*-
"""
flaskbb.core.exceptions
~~~~~~~~~~~~~~~~~~~~~~~
Exceptions raised by flaskbb.core,
forms the root of all exceptions in
FlaskBB.
:copyright: (c) 2014-2018 the FlaskBB Team
:license: BSD, see LICENSE for more details
"""
class BaseFlaskBBError(Exception):
"""
Root exception for FlaskBB.
"""
class ValidationError(BaseFlaskBBError):
"""
Used to signal validation errors for things such as
token verification, user registration, etc.
:param str attribute: The attribute the validation error applies to,
if the validation error applies to multiple attributes or to
the entire object, this should be set to None
:param str reason: Why the attribute, collection of attributes or object
is invalid.
"""
def __init__(self, attribute, reason):
self.attribute = attribute
self.reason = reason
super(ValidationError, self).__init__((attribute, reason))
class StopValidation(BaseFlaskBBError):
"""
Raised from validation handlers to signal that
validation should end immediately and no further
processing should be done.
Can also be used to communicate all errors
raised during a validation run.
:param reasons: A sequence of `(attribute, reason)` pairs explaining
why the object is invalid.
"""
def __init__(self, reasons):
self.reasons = reasons
super(StopValidation, self).__init__(reasons)
class PersistenceError(BaseFlaskBBError):
"""
Used to catch down errors when persisting models to the database instead
of letting all issues percolate up, this should be raised from those
exceptions without smashing their tracebacks. Example::
try:
db.session.add(new_user)
db.session.commit()
except Exception:
raise PersistenceError("Couldn't save user account")
"""
def accumulate_errors(caller, validators, throw=True):
errors = []
for validator in validators:
try:
caller(validator)
except ValidationError as e:
errors.append((e.attribute, e.reason))
if len(errors) and throw:
raise StopValidation(errors)
return errors
|
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
lm2int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500,
"M": 1000}
s_len_num = len(s)
ans = 0
# for i in range(s_len_num-1):
# if lm2int[s[i]] < lm2int[s[i+1]]:
# ans -= lm2int[s[i]]
# else:
# ans += lm2int[s[i]]
# return ans+lm2int[s[-1]]
lm2int = {'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L': 50,
'XC': 80, 'C': 100, 'CD': 300, 'D': 500, 'CM': 800, 'M': 1000}
alist = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']
s_len_num = len(s)
i,ans = 0,0
while i < s_len_num - 1:
if s[i]+s[i+1] in alist:
ans += lm2int[s[i]+s[i+1]]
print('2--',i,s[i:i+2],lm2int.get(s[i:i+2]),ans)
i += 2
else:
ans += lm2int[s[i]]
print('1--',i,s[i],lm2int.get(s[i]),ans)
i += 1
return ans+lm2int[s[-1]]
s = "LVIII"
sl = Solution()
print(sl.romanToInt(s))
|
name = input ("Please enter your name:\t")
age = int(input ("how old are you, {0}? ".format(name)))
if age > 100:
print ("Nice Try 🙄 ")
else:
if age < 0:
print ("I don`t beleve you.... as if your age is in minus (lol)")
if age >= 18:
print ("You are old enough vote (yay!) ")
print("Loading...")
print ("Please put an 'X' in the box")
else:
print ("Please come back in {} years".format( 18 - age ))
endkey = input ("press enter to exit the program\t\t\t\t")
print ("exiting program...")
|
# https://leetcode.com/problems/climbing-stairs/
# ---------------------------------------------------
# Runtime Complexity: O(n)
# Space Complexity: O(1)
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev_prev = 1
prev = 2
cur = 0
for i in range(3, n + 1):
cur = prev_prev + prev
prev_prev, prev = prev, cur
return cur
# ---------------------------------------------------
# Test Cases
# ---------------------------------------------------
solution = Solution()
# 0
print(solution.climbStairs(0))
# 1
print(solution.climbStairs(1))
# 2
print(solution.climbStairs(2))
# 3
print(solution.climbStairs(3))
# 5
print(solution.climbStairs(4))
# 8
print(solution.climbStairs(5))
# 13
print(solution.climbStairs(6))
|
"""
Behavioral pattern:
Iterator => 1.Iterable 2.Iteration
Requirements that should know:
__iter__ , __next__
"""
class Iteration:
def __init__(self, value):
self.value = value
def __next__(self):
if self.value == 0:
raise StopIteration('End of sequence')
for item in range(0, self.value):
value = self.value
self.value -= 1
return value
class Iterable:
def __init__(self, value):
self.value = value
def __iter__(self):
return Iteration(self.value)
if __name__ == '__main__':
f1 = Iterable(5)
f2 = iter(f1)
print(next(f2))
print(next(f2))
print(next(f2))
print(next(f2))
print(next(f2))
"""we add raise error that don't show later than zero """
print(next(f2))
|
def urlify(s, i):
p1, p2 = len(s) - 1, i
while p1 >= 0 and p2 >= 0:
if s[p2] != " ":
s[p1] = s[p2]
else:
for i in reversed("%20"):
s[p1] = i
p1 -= 1
p1 -= 1
p2 -= 1
|
# Leia o Salario de um funcionario e mostre seu novo salário, com 15% de aumento #
vo = float(input('Salário = R$'))
des = int(input('Aumento = '))
print(' ')
des = des / 100
dg = vo * des
vd = vo * (1 + des)
print('Valor original: R${:.2f} \nAumento ganho: R${:.2f} \n Valor aumentado: R${:.2f}' .format(vo, dg, vd))
|
# Example 1:
# Input: candidates = [2,3,6,7], target = 7
# Output: [[2,2,3],[7]]
# Explanation:
# 2 and 3 are candidates, and 2 + 2 + 3 = 7.
# Note that 2 can be used multiple times.
# 7 is a candidate, and 7 = 7.
# These are the only two combinations.
# Example 2:
# Input: candidates = [2,3,5], target = 8
# Output: [[2,2,2,2],[2,3,3],[3,5]]
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
comb = [[] if i > 0 else [[]] for i in range(target + 1)]
for candidate in candidates:
for i in range(candidate, len(comb)):
comb[i].extend(comb + [candidate] for comb in comb[i - candidate])
return comb[-1]
|
"""
* Assignment: Type Int Time
* Required: yes
* Complexity: easy
* Lines of code: 12 lines
* Time: 8 min
English:
1. Calculate how many seconds is one day (24 hours)
2. Calculate how many minutes is one week (7 days)
3. Calculate how many hours is in one month (31 days)
4. Calculate how many seconds is work day (8 hours)
5. Calculate how many minutes is work week (5 work days)
6. Calculate how many hours is work month (22 work days)
7. In Calculations use floordiv (`//`)
8. Run doctests - all must succeed
Polish:
1. Oblicz ile sekund to jedna doba (24 godziny)
2. Oblicz ile minut to jeden tydzień (7 dni)
3. Oblicz ile godzin to jeden miesiąc (31 dni)
4. Oblicz ile sekund to dzień pracy (8 godzin)
5. Oblicz ile minut to tydzień pracy (5 dni pracy)
6. Oblicz ile godzin to miesiąc pracy (22 dni pracy)
7. W obliczeniach użyj floordiv (`//`)
8. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert day is not Ellipsis, \
'Assign result to variable: `day`'
>>> assert week is not Ellipsis, \
'Assign result to variable: `week`'
>>> assert month is not Ellipsis, \
'Assign result to variable: `month`'
>>> assert workday is not Ellipsis, \
'Assign result to variable: `workday`'
>>> assert workweek is not Ellipsis, \
'Assign result to variable: `workweek`'
>>> assert workmonth is not Ellipsis, \
'Assign result to variable: `workmonth`'
>>> assert type(day) is int, \
'Variable `day` has invalid type, should be int'
>>> assert type(week) is int, \
'Variable `week` has invalid type, should be int'
>>> assert type(month) is int, \
'Variable `month` has invalid type, should be int'
>>> assert type(workday) is int, \
'Variable `workday` has invalid type, should be int'
>>> assert type(workweek) is int, \
'Variable `workweek` has invalid type, should be int'
>>> assert type(workmonth) is int, \
'Variable `workmonth` has invalid type, should be int'
>>> day
86400
>>> week
10080
>>> month
744
>>> workday
28800
>>> workweek
2400
>>> workmonth
176
"""
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
# int: 1 day in seconds
day = ...
# int: 7 days in minutes
week = ...
# int: 31 days in hours
month = ...
# int: 8 hours in seconds
workday = ...
# int: 5 workdays in minutes
workweek = ...
# int: 22 workdays in hours
workmonth = ...
|
#################################################
# Unit helpers #
#################################################
class Length(float):
unit2m = dict(mm=0.001, cm=0.01, dm=0.1, m=1, km=1000)
def __new__(cls, val, unit):
return float.__new__(cls, val)
def __init__(self, val, unit):
assert unit in Length.unit2m, 'Unknown units'
self.unit = unit
def __str__(self):
return f'{float(self)} {self.unit}'
def __repr__(self):
return self.__str__()
def to(self, name):
if name in Length.unit2m:
return Length.unit2m[self.unit] * float(self) / Length.unit2m[name]
def __abs__(self):
return Length.unit2m[self.unit] * float(self)
class Time(float):
unit2s = dict(
s=1,
min=60,
h=3600,
d=24 * 3600,
y=365.25 * 24 * 3600,
ky=1e3 * 365.25 * 24 * 3600,
Ma=1e6 * 365.25 * 24 * 3600,
)
def __new__(cls, val, unit):
return float.__new__(cls, val)
def __init__(self, val, unit):
assert unit in Time.unit2s, 'Unknown units'
self.unit = unit
def __str__(self):
return f'{float(self)} {self.unit}'
def __repr__(self):
return self.__str__()
def to(self, name):
if name in Time.unit2s:
return Time.unit2s[self.unit] * float(self) / Time.unit2s[name]
def __abs__(self):
return Time.unit2s[self.unit] * float(self)
|
#entrada
resp = 'S'
media = cont = maior = menor = 0
while resp == 'S':
n = int(input('Digite um número: '))
#processamento
media += n
cont += 1
if cont == 1:
maior = menor = n
else:
if n > maior:
maior = n
elif n < menor:
menor = n
resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
media /= cont
#saida
print(f'Você digitou {cont} números e a média foi {media:.2f}')
print(f'O maior valor foi {maior} e o menor foi {menor}')
|
command = input()
student_ticket = 0
standard_ticket = 0
kid_ticket = 0
while command != "Finish":
seats = int(input())
ticket_type = input()
tickets_sold = 0
while seats > tickets_sold:
tickets_sold += 1
if ticket_type == "student":
student_ticket += 1
elif ticket_type == "standard":
standard_ticket += 1
elif ticket_type == "kid":
kid_ticket += 1
if tickets_sold == seats:
break
ticket_type = input()
if ticket_type == "End":
break
print(f"{command} - {tickets_sold / seats * 100:.2f}% full.")
command = input()
total_tickets = student_ticket + standard_ticket + kid_ticket
print(f"Total tickets: {total_tickets}")
print(f"{student_ticket / total_tickets * 100:.2f}% student tickets.")
print(f"{standard_ticket / total_tickets * 100:.2f}% standard tickets.")
print(f"{kid_ticket / total_tickets * 100:.2f}% kids tickets.")
|
META_SITE_DOMAIN = 'www.geocoptix.com'
META_USE_OG_PROPERTIES = True
META_USE_TWITTER_PROPERTIES = True
META_TWITTER_AUTHOR = 'geocoptix'
META_FB_AUTHOR_URL = 'https://facebook.com/geocoptix'
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class CompatibleBill(object):
def __init__(self, billId=None, pin=None, site=None, region=None, appCode=None, appCodeName=None, serviceCode=None, serviceCodeName=None, resourceId=None, billingType=None, billingTypeName=None, formula=None, formulaStr=None, startTime=None, endTime=None, createTime=None, billFee=None, billFee2=None, discountFee=None, couponId=None, couponFee=None, actualFee=None, cashCouponFee=None, balancePayFee=None, cashPayFee=None, arrearFee=None, paySate=None, systemType=None, resourceName=None):
"""
:param billId: (Optional) 账单ID
:param pin: (Optional) 用户pin
:param site: (Optional) 站点
:param region: (Optional) 区域
:param appCode: (Optional) appCode
:param appCodeName: (Optional) appCodeName
:param serviceCode: (Optional) serviceCode
:param serviceCodeName: (Optional) serviceCodeName
:param resourceId: (Optional) 资源id
:param billingType: (Optional) 计费类型
:param billingTypeName: (Optional) 计费类型描述
:param formula: (Optional) 规格
:param formulaStr: (Optional) 规格
:param startTime: (Optional) 开始时间
:param endTime: (Optional) 结束时间
:param createTime: (Optional) 创建时间
:param billFee: (Optional) 账单金额
:param billFee2: (Optional) 账单金额(保留小数点后2位)
:param discountFee: (Optional) 折扣金额
:param couponId: (Optional) 代金券id
:param couponFee: (Optional) 优惠券金额
:param actualFee: (Optional) 优惠后金额
:param cashCouponFee: (Optional) 代金券金额
:param balancePayFee: (Optional) 余额支付金额
:param cashPayFee: (Optional) 现金支付金额
:param arrearFee: (Optional) 欠费金额
:param paySate: (Optional) 支付状态
:param systemType: (Optional) 1:老计费 2:新计费
:param resourceName: (Optional) 资源名称
"""
self.billId = billId
self.pin = pin
self.site = site
self.region = region
self.appCode = appCode
self.appCodeName = appCodeName
self.serviceCode = serviceCode
self.serviceCodeName = serviceCodeName
self.resourceId = resourceId
self.billingType = billingType
self.billingTypeName = billingTypeName
self.formula = formula
self.formulaStr = formulaStr
self.startTime = startTime
self.endTime = endTime
self.createTime = createTime
self.billFee = billFee
self.billFee2 = billFee2
self.discountFee = discountFee
self.couponId = couponId
self.couponFee = couponFee
self.actualFee = actualFee
self.cashCouponFee = cashCouponFee
self.balancePayFee = balancePayFee
self.cashPayFee = cashPayFee
self.arrearFee = arrearFee
self.paySate = paySate
self.systemType = systemType
self.resourceName = resourceName
|
def extractMyFirstTimeTranslating(item):
"""
'My First Time Translating'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
return False
|
class Toggle_Button(QPushButton):
sent_fix = pyqtSignal(bool, int, bool)
def __init__(self, currentRowCount):
QPushButton.__init__(self, "ON")
# self.setFixedSize(100, 100)
self.currentRowCount = self.rowCount()
self.setStyleSheet("background-color: green")
self.setCheckable(True)
self.toggled.connect(self.slot_toggle)
# when toggled connect initial state is True in order to make first click as OFF then True state must be red and OFF
@pyqtSlot(bool)
def slot_toggle(self, state):
print(self.currentRowCount, state)
self.sent_fix.emit(False, self.currentRowCount, state)
self.setStyleSheet("background-color: %s" % ({True: "red", False: "green"}[state]))
self.setText({True: "OFF", False: "ON"}[state])
|
TBD = None
img_norm_cfg = dict(mean=TBD, std=TBD, to_rgb=TBD)
train_pipeline = TBD
test_pipeline = TBD
# dataset settings
dataset_type = 'VOCDataset'
data_root = 'data/VOCdevkit/'
dataset_repeats = 10
data = dict(
samples_per_gpu=TBD,
workers_per_gpu=TBD,
train=dict(
type='RepeatDataset',
times=dataset_repeats,
dataset=dict(
type=dataset_type,
ann_file=[
data_root + 'VOC2007/ImageSets/Main/trainval.txt',
data_root + 'VOC2012/ImageSets/Main/trainval.txt'
],
img_prefix=[data_root + 'VOC2007/', data_root + 'VOC2012/'],
pipeline=train_pipeline)),
val=dict(
type=dataset_type,
ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt',
img_prefix=data_root + 'VOC2007/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt',
img_prefix=data_root + 'VOC2007/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='mAP')
|
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load(
"//:coursier.bzl",
"add_netrc_entries_from_mirror_urls",
"compute_dependency_inputs_signature",
"extract_netrc_from_auth_url",
"get_coursier_cache_or_default",
"get_netrc_lines_from_entries",
"remove_auth_from_url",
"split_url",
infer = "infer_artifact_path_from_primary_and_repos",
)
ALL_TESTS = []
def add_test(test_impl_func):
test = unittest.make(test_impl_func)
ALL_TESTS.append(test)
return test
def _infer_doc_example_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"group/path/to/artifact/file.jar",
infer("http://a:b@c/group/path/to/artifact/file.jar", ["http://c"]),
)
return unittest.end(env)
infer_doc_example_test = add_test(_infer_doc_example_test_impl)
def _infer_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("https://base/group/artifact/version/foo.jar", ["https://base"]),
)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("http://base/group/artifact/version/foo.jar", ["http://base"]),
)
return unittest.end(env)
infer_basic_test = add_test(_infer_basic_test_impl)
def _infer_auth_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"group1/artifact/version/foo.jar",
infer("https://a@c/group1/artifact/version/foo.jar", ["https://a:b@c"]),
)
asserts.equals(
env,
"group2/artifact/version/foo.jar",
infer("https://a@c/group2/artifact/version/foo.jar", ["https://a@c"]),
)
asserts.equals(
env,
"group3/artifact/version/foo.jar",
infer("https://a@c/group3/artifact/version/foo.jar", ["https://c"]),
)
return unittest.end(env)
infer_auth_basic_test = add_test(_infer_auth_basic_test_impl)
def _infer_leading_repo_miss_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("https://a@c/group/artifact/version/foo.jar", ["https://a:b@c/missubdir", "https://a:b@c"]),
)
return unittest.end(env)
infer_leading_repo_miss_test = add_test(_infer_leading_repo_miss_test_impl)
def _infer_repo_trailing_slash_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("https://a@c/group/artifact/version/foo.jar", ["https://a:b@c"]),
)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("https://a@c/group/artifact/version/foo.jar", ["https://a:b@c/"]),
)
asserts.equals(
env,
"group/artifact/version/foo.jar",
infer("https://a@c/group/artifact/version/foo.jar", ["https://a:b@c//"]),
)
return unittest.end(env)
infer_repo_trailing_slash_test = add_test(_infer_repo_trailing_slash_test_impl)
def _remove_auth_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"https://c1",
remove_auth_from_url("https://a:b@c1"),
)
return unittest.end(env)
remove_auth_basic_test = add_test(_remove_auth_basic_test_impl)
def _remove_auth_basic_with_path_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"https://c1/some/random/path",
remove_auth_from_url("https://a:b@c1/some/random/path"),
)
return unittest.end(env)
remove_auth_basic_with_path_test = add_test(_remove_auth_basic_with_path_test_impl)
def _remove_auth_only_user_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"https://c1",
remove_auth_from_url("https://a@c1"),
)
return unittest.end(env)
remove_auth_only_user_test = add_test(_remove_auth_only_user_test_impl)
def _remove_auth_noauth_noop_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
"https://c1",
remove_auth_from_url("https://c1"),
)
return unittest.end(env)
remove_auth_noauth_noop_test = add_test(_remove_auth_noauth_noop_test_impl)
def _split_url_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
("https", ["c1"]),
split_url("https://c1"),
)
return unittest.end(env)
split_url_basic_test = add_test(_split_url_basic_test_impl)
def _split_url_basic_auth_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
("https", ["a:b@c1"]),
split_url("https://a:b@c1"),
)
asserts.equals(
env,
("https", ["a@c1"]),
split_url("https://a@c1"),
)
return unittest.end(env)
split_url_basic_auth_test = add_test(_split_url_basic_auth_test_impl)
def _split_url_with_path_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
("https", ["c1", "some", "path"]),
split_url("https://c1/some/path"),
)
return unittest.end(env)
split_url_with_path_test = add_test(_split_url_with_path_test_impl)
def _extract_netrc_from_auth_url_noop_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{},
extract_netrc_from_auth_url("https://c1"),
)
asserts.equals(
env,
{},
extract_netrc_from_auth_url("https://c2/useless@inurl"),
)
return unittest.end(env)
extract_netrc_from_auth_url_noop_test = add_test(_extract_netrc_from_auth_url_noop_test_impl)
def _extract_netrc_from_auth_url_with_auth_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{"machine": "c", "login": "a", "password": "b"},
extract_netrc_from_auth_url("https://a:b@c"),
)
asserts.equals(
env,
{"machine": "c", "login": "a", "password": "b"},
extract_netrc_from_auth_url("https://a:b@c/some/other/stuff@thisplace/for/testing"),
)
asserts.equals(
env,
{"machine": "c", "login": "a", "password": None},
extract_netrc_from_auth_url("https://a@c"),
)
asserts.equals(
env,
{"machine": "c", "login": "a", "password": None},
extract_netrc_from_auth_url("https://a@c/some/other/stuff@thisplace/for/testing"),
)
return unittest.end(env)
extract_netrc_from_auth_url_with_auth_test = add_test(_extract_netrc_from_auth_url_with_auth_test_impl)
def _extract_netrc_from_auth_url_at_in_password_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{"machine": "c", "login": "a", "password": "p@ssword"},
extract_netrc_from_auth_url("https://a:p@ssword@c"),
)
return unittest.end(env)
extract_netrc_from_auth_url_at_in_password_test = add_test(_extract_netrc_from_auth_url_at_in_password_test_impl)
def _add_netrc_entries_from_mirror_urls_noop_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{},
add_netrc_entries_from_mirror_urls({}, ["https://c1", "https://c1/something@there"]),
)
return unittest.end(env)
add_netrc_entries_from_mirror_urls_noop_test = add_test(_add_netrc_entries_from_mirror_urls_noop_test_impl)
def _add_netrc_entries_from_mirror_urls_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{"c1": {"a": "b"}},
add_netrc_entries_from_mirror_urls({}, ["https://a:b@c1"]),
)
asserts.equals(
env,
{"c1": {"a": "b"}},
add_netrc_entries_from_mirror_urls(
{"c1": {"a": "b"}},
["https://a:b@c1"],
),
)
return unittest.end(env)
add_netrc_entries_from_mirror_urls_basic_test = add_test(_add_netrc_entries_from_mirror_urls_basic_test_impl)
def _add_netrc_entries_from_mirror_urls_multi_login_ignored_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{"c1": {"a": "b"}},
add_netrc_entries_from_mirror_urls({}, ["https://a:b@c1", "https://a:b2@c1", "https://a2:b3@c1"]),
)
asserts.equals(
env,
{"c1": {"a": "b"}},
add_netrc_entries_from_mirror_urls(
{"c1": {"a": "b"}},
["https://a:b@c1", "https://a:b2@c1", "https://a2:b3@c1"],
),
)
return unittest.end(env)
add_netrc_entries_from_mirror_urls_multi_login_ignored_test = add_test(_add_netrc_entries_from_mirror_urls_multi_login_ignored_test_impl)
def _add_netrc_entries_from_mirror_urls_multi_case_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
{
"foo": {"bar": "baz"},
"c1": {"a1": "b1"},
"c2": {"a2": "b2"},
},
add_netrc_entries_from_mirror_urls(
{"foo": {"bar": "baz"}},
["https://a1:b1@c1", "https://a2:b2@c2", "https://a:b@c1", "https://a:b2@c1", "https://a2:b3@c1"],
),
)
return unittest.end(env)
add_netrc_entries_from_mirror_urls_multi_case_test = add_test(_add_netrc_entries_from_mirror_urls_multi_case_test_impl)
def _get_netrc_lines_from_entries_noop_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
[],
get_netrc_lines_from_entries({}),
)
return unittest.end(env)
get_netrc_lines_from_entries_noop_test = add_test(_get_netrc_lines_from_entries_noop_test_impl)
def _get_netrc_lines_from_entries_basic_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
["machine c", "login a", "password b"],
get_netrc_lines_from_entries({
"c": {"a": "b"},
}),
)
return unittest.end(env)
get_netrc_lines_from_entries_basic_test = add_test(_get_netrc_lines_from_entries_basic_test_impl)
def _get_netrc_lines_from_entries_no_pass_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
["machine c", "login a"],
get_netrc_lines_from_entries({
"c": {"a": ""},
}),
)
return unittest.end(env)
get_netrc_lines_from_entries_no_pass_test = add_test(_get_netrc_lines_from_entries_no_pass_test_impl)
def _get_netrc_lines_from_entries_multi_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(
env,
[
"machine c",
"login a",
"password b",
"machine c2",
"login a2",
"password p@ssword",
],
get_netrc_lines_from_entries({
"c": {"a": "b"},
"c2": {"a2": "p@ssword"},
}),
)
return unittest.end(env)
get_netrc_lines_from_entries_multi_test = add_test(_get_netrc_lines_from_entries_multi_test_impl)
def _mock_repo_path(path):
if path.startswith("/"):
return path
else:
return "/mockroot/" + path
def _mock_which(path):
return False
def _get_coursier_cache_or_default_disabled_test(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct(
os = struct(
environ = {
"COURSIER_CACHE": _mock_repo_path("/does/not/matter"),
},
name = "linux",
),
which = _mock_which,
)
asserts.equals(
env,
"v1",
get_coursier_cache_or_default(mock_repository_ctx, False),
)
return unittest.end(env)
get_coursier_cache_or_default_disabled_test = add_test(_get_coursier_cache_or_default_disabled_test)
def _get_coursier_cache_or_default_enabled_with_default_location_linux_test(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct(
os = struct(
environ = {
"HOME": "/home/testuser",
},
name = "linux",
),
which = _mock_which,
)
asserts.equals(
env,
"/home/testuser/.cache/coursier/v1",
get_coursier_cache_or_default(mock_repository_ctx, True),
)
return unittest.end(env)
get_coursier_cache_or_default_enabled_with_default_location_linux_test = add_test(_get_coursier_cache_or_default_enabled_with_default_location_linux_test)
def _get_coursier_cache_or_default_enabled_with_default_location_mac_test(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct(
os = struct(
environ = {
"HOME": "/Users/testuser",
},
name = "mac",
),
which = _mock_which,
)
asserts.equals(
env,
"/Users/testuser/Library/Caches/Coursier/v1",
get_coursier_cache_or_default(mock_repository_ctx, True),
)
return unittest.end(env)
get_coursier_cache_or_default_enabled_with_default_location_mac_test = add_test(_get_coursier_cache_or_default_enabled_with_default_location_mac_test)
def _get_coursier_cache_or_default_enabled_with_custom_location_test(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct(
os = struct(
environ = {
"COURSIER_CACHE": _mock_repo_path("/custom/location"),
},
name = "linux",
),
which = _mock_which,
)
asserts.equals(
env,
"/custom/location",
get_coursier_cache_or_default(mock_repository_ctx, True),
)
return unittest.end(env)
get_coursier_cache_or_default_enabled_with_custom_location_test = add_test(_get_coursier_cache_or_default_enabled_with_custom_location_test)
def _mock_which_true(path):
return True
def _mock_execute(args):
if args[-1] == "/Users/testuser/Library/Caches/Coursier/v1":
return struct(return_code = 1)
else:
return struct(return_code = 0)
def _get_coursier_cache_or_default_enabled_with_home_dot_coursier_directory_test(ctx):
env = unittest.begin(ctx)
mock_repository_ctx = struct(
os = struct(
environ = {
"HOME": "/Users/testuser",
},
name = "mac",
),
which = _mock_which_true,
execute = _mock_execute,
)
asserts.equals(
env,
"/Users/testuser/.coursier/cache/v1",
get_coursier_cache_or_default(mock_repository_ctx, True),
)
return unittest.end(env)
get_coursier_cache_or_default_enabled_with_home_dot_coursier_directory_test = add_test(_get_coursier_cache_or_default_enabled_with_home_dot_coursier_directory_test)
def _calculate_inputs_hash_does_not_care_about_input_order_test(ctx):
env = unittest.begin(ctx)
# Order of artifacts is switched in each hash
hash1 = compute_dependency_inputs_signature([
"""{"group": "first", "artifact": "artifact", "version": "version"}""",
"""{"group": "second", "artifact": "artifact", "version": "version"}""",
])
hash2 = compute_dependency_inputs_signature([
"""{"group": "second", "artifact": "artifact", "version": "version"}""",
"""{"group": "first", "artifact": "artifact", "version": "version"}""",
])
return unittest.end(env)
calculate_inputs_hash_does_not_care_about_input_order_test = add_test(_calculate_inputs_hash_does_not_care_about_input_order_test)
def coursier_test_suite():
unittest.suite(
"coursier_tests",
*ALL_TESTS
)
|
# ------------------------------------------------------------------------------
#
class Attributes (object) :
# FIXME: add method sigs
# --------------------------------------------------------------------------
#
def __init__ (self, vals={}) :
raise Exception ("%s is not implemented" % self.__class__.__name__)
# ------------------------------------------------------------------------------
#
|
class IdGenerator(object):
number = 0
@staticmethod
def next():
tmp = IdGenerator.number
IdGenerator.number += 1
return str(tmp)
|
# Copyright (c) 2016 Vivaldi Technologies AS. All rights reserved
{
'targets': [
{
'target_name': 'vivaldi_browser',
'type': 'static_library',
'dependencies': [
'app/vivaldi_resources.gyp:*',
'chromium/base/base.gyp:base',
'chromium/components/components.gyp:search_engines',
'chromium/chrome/chrome_resources.gyp:chrome_resources',
'chromium/chrome/chrome_resources.gyp:chrome_strings',
'chromium/crypto/crypto.gyp:crypto',
'chromium/chrome/chrome.gyp:browser_extensions',
'chromium/components/components.gyp:os_crypt',
'chromium/skia/skia.gyp:skia',
'extensions/vivaldi_api_resources.gyp:*',
'vivaldi_extensions',
'vivaldi_preferences',
],
'include_dirs': [
'.',
'chromium',
],
'sources': [
'app/vivaldi.rc',
'app/vivaldi_commands.h',
'app/vivaldi_command_controller.cpp',
'app/vivaldi_command_controller.h',
'clientparts/vivaldi_content_browser_client_parts.h',
'clientparts/vivaldi_content_browser_client_parts.cc',
'extraparts/vivaldi_browser_main_extra_parts.h',
'extraparts/vivaldi_browser_main_extra_parts.cc',
'importer/imported_notes_entry.cpp',
'importer/imported_notes_entry.h',
'importer/viv_importer.cpp',
'importer/viv_importer.h',
'importer/chrome_importer_bookmark.cpp',
'importer/chromium_importer.cpp',
'importer/chromium_importer.h',
'importer/chromium_profile_importer.h',
'importer/chromium_profile_importer.cpp',
'importer/chromium_profile_lock.cpp',
'importer/chromium_profile_lock.h',
'importer/viv_importer_bookmark.cpp',
'importer/viv_importer_notes.cpp',
'importer/viv_importer_utils.h',
'importer/chrome_importer_utils.h',
'importer/viv_importer_wand.cpp',
'importer/viv_opera_reader.cpp',
'importer/viv_opera_reader.h',
'importer/chrome_bookmark_reader.cpp',
'importer/chrome_bookmark_reader.h',
'notes/notes_attachment.cpp',
'notes/notes_attachment.h',
'notes/notesnode.cpp',
'notes/notesnode.h',
'notes/notes_factory.cpp',
'notes/notes_factory.h',
'notes/notes_model.cpp',
'notes/notes_model.h',
'notes/notes_model_observer.h',
'notes/notes_model_loaded_observer.cpp',
'notes/notes_model_loaded_observer.h',
'notes/notes_storage.cpp',
'notes/notes_storage.h',
'notifications/notification_permission_context_extensions.cc',
'notifications/notification_permission_context_extensions.h',
'ui/webgui/notes_ui.cpp',
'ui/webgui/notes_ui.h',
'ui/webgui/vivaldi_web_ui_controller_factory.cpp',
'ui/webgui/vivaldi_web_ui_controller_factory.h',
'ui/views/vivaldi_pin_shortcut.cpp',
'ui/views/vivaldi_pin_shortcut.h',
],
# Disables warnings about size_t to int conversions when the types
# have different sizes
'msvs_disabled_warnings': [ 4267 ],
'conditions': [
['OS=="linux"', {
"sources":[
'extraparts/vivaldi_browser_main_extra_parts_linux.cc',
'importer/viv_importer_util_linux.cpp',
'importer/chromium_importer_util_linux.cpp',
'importer/chromium_profile_lock_posix.cpp',
],
}],
['OS=="win"', {
"sources":[
'browser/vivaldi_download_status.cpp',
'browser/vivaldi_download_status.h',
'extraparts/vivaldi_browser_main_extra_parts_win.cc',
'importer/viv_importer_util_win.cpp',
'importer/chrome_importer_util_win.cpp',
'importer/chromium_profile_lock_win.cpp',
],
}],
['OS=="mac"', {
"sources":[
'extraparts/vivaldi_browser_main_extra_parts_mac.mm',
'importer/viv_importer_util_mac.mm',
'importer/chromium_importer_util_mac.mm',
'importer/chromium_profile_lock_mac.mm',
],
}, { #'OS!="mac"
"dependencies":[
'chromium/chrome/chrome.gyp:utility',
],
}],
],
},
{
'target_name': 'vivaldi_extensions',
'type': 'static_library',
'dependencies': [
'extensions/api/vivaldi_chrome_extensions.gyp:*',
'extensions/schema/vivaldi_api.gyp:vivaldi_chrome_api',
],
'sources': [
'extensions/permissions/vivaldi_api_permissions.cpp',
'extensions/permissions/vivaldi_api_permissions.h',
'extensions/vivaldi_extensions_client.cpp',
'extensions/vivaldi_extensions_client.h',
'extensions/vivaldi_extensions_init.cpp',
'extensions/vivaldi_extensions_init.h',
],
'include_dirs': [
'.',
'chromium',
],
},
{
'target_name': 'vivaldi_packaged_app',
'type': 'none',
'dependencies': [
'vivapp/vivaldi_app.gypi:*',
],
},
{
'target_name': 'vivaldi_helper_script',
'type': 'none',
'conditions': [
['OS=="win"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'app/vivaldi_local_profile.bat',
],
}],
}],
['OS=="win" and target_arch == "ia32"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'third_party/_winsparkle_lib/WinSparkle.dll',
'third_party/_winsparkle_lib/WinSparkle.lib',
],
}],
}],
['OS=="win" and target_arch == "x64"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'third_party/_winsparkle_lib/x64/WinSparkle.dll',
'third_party/_winsparkle_lib/x64/WinSparkle.lib',
],
}],
}],
],
},
{
'target_name': 'vivaldi_preferences',
'type': 'static_library',
'dependencies': [
'chromium/base/base.gyp:base',
],
'sources': [
'prefs/vivaldi_pref_names.h',
'prefs/vivaldi_pref_names.cc',
],
'conditions': [
['OS=="linux"', {
"sources":[
'prefs/vivaldi_browser_prefs_linux.cc',
],
}],
['OS=="win"', {
"sources":[
'prefs/vivaldi_browser_prefs_win.cc',
],
}],
['OS=="mac"', {
"sources":[
'prefs/vivaldi_browser_prefs_mac.mm',
],
}],
],
'include_dirs': [
'.',
'chromium',
],
},
],
}
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
current = head
length = 0
while current :
length+=1
breakhere =current
current= current.next
if k ==0 or length<=1 : return head
k= k% length
breakAt = length-k-1
current = head
while current.next:
if breakAt==0:
breakhere = current
breakAt-=1
current = current.next
current.next = head
head = breakhere.next
breakhere.next = None
return head;
"""
linkedlist = 1->2->3->4->5
rotate = 2
Step 1 : traverse through array and to avoid edge cases keep pointer breakHere on last Node
Step 2 : find the length and calculate the Break Point
In above example the length of linked list is 5 and rotate is 2 hence the node to be break is ahead of 3
breakAt = length -k-1
Step 3 : Go to that node and keep a pointer breakHere on that Node and traverse till last node
Step 4 : Attach last node to head by doing "current.next = head"
Step 5 : Now make the new head from the point where we are going to break it
"head = breakHere.next" Do this step first so you will not lose reference
Step 6 : Break the Node
head breakHere breakHere head
| | | |
1->2->3->4->5 --- current will look like 1->2->->3 4->5
|_____________|
"""
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
def split(arr, size):
"""Splits an array to smaller arrays of size"""
arrays = []
while len(arr) > size:
piece = arr[:size]
arrays.append(piece)
arr = arr[size:]
arrays.append(arr)
return arrays
def take_out_elements(list_object, indices):
"""Removes elements from list in specified indices"""
removed_elements = []
indices = sorted(indices, reverse=True)
for idx in indices:
if idx < len(list_object):
removed_elements.append(list_object.pop(idx))
return removed_elements
|
# -*- coding: utf-8 -*-
"""
1287. Element Appearing More Than 25% In Sorted Array
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Constraints:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
"""
class Solution:
def findSpecialInteger(self, arr):
occur = len(arr) / 4
count = 0
last = -1
for val in arr:
if val == last:
count += 1
else:
last = val
count = 1
if count > occur:
return val
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" ib.ext.cfg.CommissionReport -> config module for CommissionReport.java.
"""
|
class Solution:
def plusOne(self, digits):
"""
66. Plus One
https://leetcode.com/problems/plus-one
"""
for i in range(len(digits)):
if digits[-i] < 9:
digits[-i] += 1
return digits
digits[-i] = 0
return [1] + [0] * len(digits)
|
# Copyright 2015 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,
},
'targets': [],
'conditions': [
# The CrNet build is ninja-only because of the hack in
# ios/build/packaging/link_dependencies.py.
['OS=="ios" and "<(GENERATOR)"=="ninja"', {
'targets': [
{
'target_name': 'crnet_test',
'type': 'executable',
'dependencies': [
'../../../ios/crnet/crnet.gyp:crnet',
'../../../ios/third_party/gcdwebserver/gcdwebserver.gyp:gcdwebserver',
'../../../testing/gtest.gyp:gtest',
],
'sources': [
'crnet_http_tests.mm',
'crnet_test_runner.mm',
],
'include_dirs': [
'../../..',
'..',
],
'link_settings': {
},
},
],
}],
],
}
|
input = """
d(1).
d(2).
d(3).
d(4) :- #count{V : d(V)} > 2.
"""
output = """
d(1).
d(2).
d(3).
d(4) :- #count{V : d(V)} > 2.
"""
|
def parse_map(in_file):
with open(in_file) as f:
lines = f.read().splitlines()
width = len(lines[0])
height = len(lines)
points = {}
for x in range(width):
for y in range(height):
points[(x, y)] = lines[y][x]
return points, width, height
def solve(in_file):
(points, width, height) = parse_map(in_file)
trees = 0
x = 0
y = 0
while y < height:
if points[(x, y)] == "#":
trees += 1
x = (x + 3) % width
y += 1
return trees
# print(solve('sample.txt'))
print(solve("input.txt"))
|
tick = "✓"
cross = "✘"
enter_key = "⏎"
up = "↑"
down = "↓"
left = "←"
right = "→"
division = "÷"
multiplication = "×"
_sum = "∑"
_lambda = "λ"
|
"""125. Backpack II
"""
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@param V: Given n items with value V[i]
@return: The maximum value
"""
def backPackII(self, m, A, V):
# write your code here
dp = [[float('-inf')] * (m + 1) for _ in range(len(A) + 1)]
dp[0][0] = 0
for i in range(1, len(A) + 1):
for j in range(m, -1, -1):
if j < A[i - 1]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - A[i - 1]] + V[i - 1])
return max(dp[-1])
#####
n = len(A)
dp = [[float('-inf')] * (m + 1) for _ in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
for j in rnage(m , -1, -1):
if j < A[i - 1]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - A[i - 1]] + V[i - 1])
return max(dp[n][j] for j in range(m + 1))
|
a1=input("whats your age")
a2=input("whats your age")
int(a1)
int(a2)
age=int(a1)-int(a2)
print(abs(age))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 05/09/2015
Updated: 28/09/2017
# Description
Ternary-search tries (or trees) combine the time efficiency of other tries with
the space efficiency of binary-search trees.
An advantage compared to hash maps is that ternary search tries support sorting,
but the keys of a ternary-search trie can only be strings, whereas a hash map
supports any kind of hashable keys.
## TSTs vs Hashing
### Hashing
- Need to examine entire key
- Search miss and hits cost about the same
- Performance relies on hash function
- Does not support ordered symbol table operations
### TSTs
- Works only for strings (or digital keys)
- Only examines just enough key characters
- Search miss may involve only a few characters
- Supports ordered symbol table operations:
- keys-that-match
- keys-with-prefix
- longest-prefix-of
### Bottom line
TSTs are:
- faster than hashing (especially for search misses)
- more flexible than red-black trees
# TODO
- Improve is_tst function
# References
- https://www.cs.upc.edu/~ps/downloads/tst/tst.html
- https://www.cs.princeton.edu/~rs/strings/
- http://algs4.cs.princeton.edu/52trie/TST.java.html
- https://www.youtube.com/watch?v=CIGyewO7868
- https://en.wikipedia.org/wiki/Ternary_search_tree
- http://stackoverflow.com/a/27178771/3924118
"""
__all__ = ["TST"]
class _TSTNode:
"""A _TSTNode has 6 fields:
- key, which is a character;
- value, which is None if self is not a terminal node (of an inserted
string in the TST);
- parent, which is a pointer to a _TSTNode representing the parent of
self;
- left, which is a pointer to a _TSTNode whose key is smaller
lexicographically than key;
- right, which is similarly a pointer to a _TSTNode whose key is greater
lexicographically than key;
- mid, which is a pointer to a _TSTNode whose key is the following
character of key in an inserted string."""
def __init__(self, key, value=None, parent=None, left=None, mid=None,
right=None):
if not isinstance(key, str):
raise TypeError("key must be an instance of str.")
if not key:
raise ValueError("key must be a string of length >= 1.")
self.key = key
self.value = value
self.parent = parent
self.left = left
self.mid = mid
self.right = right
def is_left_child(self) -> bool:
if not self.parent:
raise AttributeError("self does not have a parent.")
if self.parent.left:
return self.parent.left == self
else:
return False
def is_right_child(self) -> bool:
if not self.parent:
raise AttributeError("self does not have a parent.")
if self.parent.right:
return self.parent.right == self
else:
return False
def is_mid_child(self) -> bool:
if not self.parent:
raise AttributeError("self does not have a parent.")
if self.parent.mid:
return self.parent.mid == self
else:
return False
def has_children(self) -> bool:
return self.left or self.right or self.mid
def __str__(self):
return "{0}: {1}".format(self.key, self.value)
def __repr__(self):
return self.__str__()
class TST:
"""An implementation of a typical ternary-search trie (or tree).
It does not allow (through public methods) empty strings to be inserted.
In general, the way the ternary search tree looks like highly depends on the
order of insertion of the keys, that is, inserting the same keys but in
different orders produces internally a different structure or shape of the
ternary-search tree."""
def __init__(self):
self._n = 0
self._root = None
@property
def size(self) -> int:
return self._n
def is_empty(self) -> bool:
"""Time complexity: O(1)."""
return self.size == 0
def _is_root(self, u: _TSTNode) -> bool:
result = (self._root == u)
if result:
assert u.parent is None
else:
assert u.parent is not None
return result
def count(self) -> int:
"""Counts the number of strings in this TST.
This method recursively passes through all the nodes and counts the ones
which have a non None value.
YOU SHOULD CLEARLY USE size INSTEAD: THIS METHOD IS HERE ONLY FOR THE
FUN OF WRITING CODE!
Time complexity: O(n), where n is the number of nodes in this TST."""
c = self._count(self._root, 0)
assert c == self.size
return c
def _count(self, node: _TSTNode, counter: int) -> int:
"""Helper method to self.count.
Time complexity: O(m), where m is the number of nodes under node."""
if node is None: # Base case.
return counter
counter = self._count(node.left, counter)
if node.value is not None:
counter += 1
counter = self._count(node.mid, counter)
counter = self._count(node.right, counter)
return counter
def insert(self, key: str, value: object) -> None:
"""Inserts the key into the symbol table and associates with it value,
overwriting an eventual associated old value, if the key is already in
this ternary-search tree.
If key is not an instance of str, TypeError is raised.
If key is an empty string, ValueError is raised.
If value is None, ValueError is raised.
Nodes whose value is not None represent the last character of an
inserted word.
Time complexity: O(m + h), where m = length(key), which also represents
how many times we follow the middle link, and h is the number of left
and right turns. So, a lower bound of the complexity would be Ω(m)."""
assert is_tst(self)
if not isinstance(key, str):
raise TypeError("key must be an instance of type str.")
if not key:
raise ValueError("key must be a string of length >= 1.")
if value is None:
raise ValueError("value cannot be None.")
self._root = self._insert(self._root, key, value, 0)
assert is_tst(self)
def _insert(self, node: _TSTNode, key: str, value: object,
index: int) -> _TSTNode:
"""Inserts key with value into this TST starting from node."""
if node is None:
node = _TSTNode(key[index])
if key[index] < node.key:
node.left = self._insert(node.left, key, value, index)
node.left.parent = node
elif key[index] > node.key:
node.right = self._insert(node.right, key, value, index)
node.right.parent = node
else: # key[index] == node.key
if index < len(key) - 1:
# If we are not at the end of the key, this is a match, so we
# recursively call self._insert from index + 1, and we move to
# the mid node (char) of node.
#
# Note: the last index of the key is len(key) - 1.
node.mid = self._insert(node.mid, key, value, index + 1)
node.mid.parent = node
else:
if node.value is None:
self._n += 1
node.value = value
return node
def search(self, key: str) -> object:
"""Returns the value associated with key, if key is in this TST, else
None.
If key is not an instance of str, TypeError is raised.
If key is an empty string, ValueError is raised.
The search in a TST works as follows.
We start at the root and we compare its character with the first
character of key.
- If they are the same, we follow the middle link of the root node.
- If the first character of key is smaller lexicographically than
the key at the root, then we take the left link or pointer.
We do this because we know that all strings that start with
characters that are smaller lexicographically than key[0] are on its
left subtree.
- If the first character of key is greater lexicographically
than the key at the root, we take similarly the right link.
We keep applying this idea at every node.
Moreover, when there is a match, next time we compare the key of the
next node with the next character of key.
For example, if there's a match between the first node (the root) and
key[0], we follow the middle link, and the next comparison is between
the key of the specific next node and key[1] (not key[0]).
Time complexity: O(m + h). Check self.insert to see what m and h are."""
if not isinstance(key, str):
raise TypeError("key must be an instance of type str.")
if not key:
raise ValueError("key must be a string of length >= 1.")
node = self._search(self._root, key, 0)
if node is not None:
assert self.search_iteratively(key) == node.value
return node.value
else:
assert self.search_iteratively(key) is None
return None
def _search(self, node: _TSTNode, key: str, index: int) -> _TSTNode:
"""Searches for the node containing the value associated with key
starting from node.
If returns None or a node with value None if there's no such node."""
if node is None:
return None
if key[index] < node.key:
return self._search(node.left, key, index)
elif key[index] > node.key:
return self._search(node.right, key, index)
elif index < len(key) - 1:
# This is a match, but we are not at the last character of key.
return self._search(node.mid, key, index + 1)
else: # This is a match and we are at the last character of key.
return node # node could be None!!
def search_iteratively(self, key: str) -> object:
"""Iterative alternative to self.search."""
if not isinstance(key, str):
raise TypeError("key must be an instance of type str.")
if not key:
raise ValueError("key must be a string of length >= 1.")
node = self._root
if node is None:
return None
# Up to the penultimate index (i.e. len(key) - 1), because if we reach
# the penultimate character and it's a match, then we follow the mid
# node (i.e. we end up in what's possibly the last node).
index = 0
while index < len(key) - 1:
while node and key[index] != node.key:
if key[index] < node.key:
node = node.left
else:
node = node.right
if node is None: # Unsuccessful search.
return None
else:
# Arriving here only if exited from the while loop because the
# condition key[i] != node.key was false, that is
# key[index] == node.key, thus we follow the middle link.
node = node.mid
index += 1
assert index == len(key) - 1
# If node is not None, then we may still need to go left or right, and
# we stop when either we find a node which has the same key as the last
# character of key, or when node ends up being set to None, i.e. the key
# does not exist in this TST.
while node and key[index] != node.key:
if key[index] < node.key:
node = node.left
else:
node = node.right
if node is None: # Unsuccessful search.
return None
else: # We exit the previous while loop because key[index] == node.key.
return node.value # This can be None!!
def contains(self, key: str) -> bool:
"""Returns true if key is in this TST, False otherwise.
Time complexity: O(m + h). See the complexity analysis of self.insert
for more info about m and h."""
return self.search(key) is not None
def delete(self, key: str) -> object:
"""Deletes and returns the value associated with key in this TST, if key
is in this TST, otherwise it returns None.
If key is not an instance of str, TypeError is raised.
If key is an empty string, ValueError is raised.
Time complexity: O(m + h + k). Check self.search to see what m and h
are. k is the number of "no more necessary" cleaned up after deletion of
the node associated with key. Unnecessary nodes are nodes with no
children and value equal to None."""
assert is_tst(self)
if not isinstance(key, str):
raise TypeError("key must be an instance of type str.")
if not key:
raise ValueError("key must be a string of length >= 1.")
# Note: calling self._search, since self.search does not return a Node,
# but the value associated with the key passed as parameter.
node = self._search(self._root, key, 0)
if node is not None and node.value is not None:
result = node.value # Forget the string tracked by node.
node.value = None
self._n -= 1
self._delete_fix(node)
else:
result = None
assert is_tst(self)
return result
def _delete_fix(self, u: _TSTNode) -> None:
"""Does the clean up of this TST after deletion of node u."""
assert u.value is None
# While u has no children and his value is None, forget about u and
# start from his parent. So, this while loop terminates when either u is
# None, u has at least one child, or u's value is not None.
while u and not u.has_children() and u.value is None:
if self._is_root(u):
assert self._n == 0
self._root = None
break
if u.is_left_child():
u.parent.left = None
elif u.is_right_child():
u.parent.right = None
else:
u.parent.mid = None
p = u.parent
u.parent = None
u = p
if u.has_children() and u.value is None:
assert self._count(u, 0) > 0
def traverse(self) -> None:
"""Traverses all nodes in this TST and prints the key: value
associations.
Time complexity: O(n), where n is the number of nodes in self."""
self._traverse(self._root, "")
def _traverse(self, node: _TSTNode, prefix: str) -> None:
"""Helper method to self.traverse.
Time complexity: O(m), where m is the number of nodes under node."""
if node is None: # Base case.
return
self._traverse(node.left, prefix)
if node.value is not None:
print(prefix + node.key, ": ", node.value)
self._traverse(node.mid, prefix + node.key)
self._traverse(node.right, prefix)
def keys_with_prefix(self, prefix: str) -> list:
"""Returns all keys in this TST that start with prefix.
If prefix is not an instance of str, TypeError is raised.
If prefix is an empty string, then all keys in this TST that start with
an empty string, thus all keys are returned."""
if not isinstance(prefix, str):
raise TypeError("prefix must be an instance of str!")
kwp = []
if not prefix:
self._keys_with_prefix(self._root, [], kwp)
else:
node = self._search(self._root, prefix, 0)
if node is not None:
if node.value is not None:
# A key equals to prefix was found in the TST with an
# associated value.
kwp.append(prefix)
self._keys_with_prefix(node.mid, list(prefix), kwp)
return kwp
def _keys_with_prefix(self, node: _TSTNode, prefix_list: list,
kwp: list) -> None:
"""Returns all keys rooted at node given the prefix given as a list of
characters prefix_list."""
if node is None:
return
self._keys_with_prefix(node.left, prefix_list, kwp)
if node.value is not None:
kwp.append("".join(prefix_list + [node.key]))
prefix_list.append(node.key)
self._keys_with_prefix(node.mid, prefix_list, kwp)
prefix_list.pop()
self._keys_with_prefix(node.right, prefix_list, kwp)
def all_pairs(self) -> dict:
"""Returns all pairs of (key: value) from this TST as a Python dict."""
pairs = {}
self._all_pairs(self._root, [], pairs)
return pairs
def _all_pairs(self, node: _TSTNode, key_list: list,
all_dict: list) -> None:
if node is None:
return
self._all_pairs(node.left, key_list, all_dict)
if node.value is not None:
key = "".join(key_list + [node.key])
assert key not in all_dict
all_dict[key] = node.value
key_list.append(node.key)
self._all_pairs(node.mid, key_list, all_dict)
key_list.pop()
self._all_pairs(node.right, key_list, all_dict)
def longest_prefix_of(self, query: str) -> str:
"""Returns the key in this TST which is the longest prefix of query, if
such a key exists, else it returns None.
If query is not a string TypeError is raised.
If query is a string but empty, ValueError is raised.
If this TST is empty, it returns an empty string."""
if not isinstance(query, str):
raise TypeError("query is not an instance of str!")
if not query:
raise ValueError("empty strings not allowed in this TST!")
# It keeps track of the length of the longest prefix of query.
length = 0
x = self._root
i = 0
while x is not None and i < len(query):
c = query[i]
if c < x.key:
x = x.left
elif c > x.key:
x = x.right
else:
i += 1
if x.value is not None:
length = i
x = x.mid
return query[:length]
def keys_that_match(self, pattern: str) -> list:
"""Returns a list of keys of this TST that match pattern.
A key k of length m matches pattern if:
1. m = length(pattern), and
2. Either k[i] == pattern[i] or k[i] == '.'.
- Example: if pattern == ".ood", then k == "good" would match, but
not k == "foodie".
If pattern is not a str, TypeError is raised.
If pattern is an empty string, ValueError is raised."""
if not isinstance(pattern, str):
raise TypeError("pattern is not an instance of str!")
if not pattern:
raise ValueError("pattern cannot be an empty string")
keys = []
self._keys_that_match(self._root, [], 0, pattern, keys)
return keys
def _keys_that_match(self, node: _TSTNode, prefix_list: list, i: int,
pattern: str, keys: list) -> None:
"""Stores in the list keys the keys that match pattern starting from
node."""
if node is None:
return
c = pattern[i]
if c == "." or c < node.key:
self._keys_that_match(node.left, prefix_list, i, pattern, keys)
if c == "." or c == node.key:
if i == len(pattern) - 1 and node.value is not None:
# If i is the last index and its value is not None.
keys.append("".join(prefix_list + [node.key]))
if i < len(pattern) - 1:
prefix_list.append(node.key)
self._keys_that_match(node.mid, prefix_list, i + 1, pattern,
keys)
prefix_list.pop()
if c == "." or c > node.key:
self._keys_that_match(node.right, prefix_list, i, pattern, keys)
def is_tst(t: TST) -> bool:
"""These propositions should always be true at the BEGINNING
and END of every PUBLIC method of this TST.
Call this method if you want to ensure the invariants are holding."""
if not isinstance(t, TST):
return False
if t._n < 0:
return False
if t._n == 0:
return t._root is None
if not isinstance(t._root, _TSTNode) or t._root.parent is not None:
return False
return True
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# This combines configurable build-time constants (documented on REPO_CFG
# below), and non-configurable constants that are currently not namespaced.
#
# Note that there's no deep reason for this struct / non-struct split, so we
# could easily move everything into the struct.
#
load("//antlir/bzl:oss_shim.bzl", "do_not_use_repo_cfg")
load("//antlir/bzl:shape.bzl", "shape")
DO_NOT_USE_BUILD_APPLIANCE = "__DO_NOT_USE_BUILD_APPLIANCE__"
VERSION_SET_ALLOW_ALL_VERSIONS = "__VERSION_SET_ALLOW_ALL_VERSIONS__"
CONFIG_KEY = "antlir"
# This needs to be kept in sync with
# `antlir.nspawn_in_subvol.args._QUERY_TARGETS_AND_OUTPUTS_SEP`
QUERY_TARGETS_AND_OUTPUTS_SEP = "|"
# This is used as standard demiliter in .buckconfig while using
# flavor names under a specific config group
BUCK_CONFIG_FLAVOR_NAME_DELIMITER = "#"
def _get_flavor_config(flavor_name = None):
flavor_to_config = do_not_use_repo_cfg.get("flavor_to_config", {})
for flavor, flavor_config in flavor_to_config.items():
config_key = CONFIG_KEY + BUCK_CONFIG_FLAVOR_NAME_DELIMITER + flavor
for key, v in flavor_config.items():
val = native.read_config(config_key, key, None)
if val != None:
flavor_config[key] = val
return flavor_to_config
# Use `_get_str_cfg` or `_get_str_list_cfg` instead.
def _do_not_use_directly_get_cfg(name, default = None):
# Allow `buck -c` overrides from the command-line
val = native.read_config(CONFIG_KEY, name)
if val != None:
return val
val = do_not_use_repo_cfg.get(name)
if val != None:
return val
return default
# We don't have "globally required" configs because code that requires a
# config will generally loudly fail on a config value that is None.
def _get_str_cfg(name, default = None, allow_none = False):
ret = _do_not_use_directly_get_cfg(name, default = default)
if not allow_none and ret == None:
fail("Repo config must set key {}".format(name))
return ret
# Defaults to the empty list if the config is not set.
#
# We use space to separate plurals because spaces are not allowed in target
# paths, and also because that's what `.buckconfig` is supposed to support
# for list configs (but does not, due to bugs).
def _get_str_list_cfg(name, separator = " ", default = None):
s = _do_not_use_directly_get_cfg(name)
return s.split(separator) if s else (default or [])
# Defaults to the empty list if the config is not set
def _get_version_set_to_path():
lst = _get_str_list_cfg("version_set_to_path")
vs_to_path = dict(zip(lst[::2], lst[1::2]))
if 2 * len(vs_to_path) != len(lst):
fail("antlir.version_set_to_path is a space-separated dict: k1 v1 k2 v2")
# A layer can turn off version locking
# via `version_set = VERSION_SET_ALLOW_ALL_VERSIONS`.
vs_to_path[VERSION_SET_ALLOW_ALL_VERSIONS] = "TROLLING TROLLING TROLLING"
return vs_to_path
# Defaults to the empty list if the config is not set
def _get_artifact_key_to_path():
lst = _get_str_list_cfg("artifact_key_to_path")
key_to_path = dict(zip(lst[::2], lst[1::2]))
if 2 * len(key_to_path) != len(lst):
fail("antlir.artifact_key_to_path is a space-separated dict: k1 v1 k2 v2")
return key_to_path
# These are configuration keys that can be grouped under a specific
# common name called flavor. This way, during run-time, we can choose
# default values for set of configuration keys based on selected flavor
# name
flavor_config_t = shape.shape(
build_appliance = shape.field(str, optional = True),
rpm_installer = shape.field(str, optional = True),
rpm_repo_snapshot = shape.field(str, optional = True),
version_set_path = shape.field(str, optional = True),
)
#
# These are repo-specific configuration keys, which can be overridden via
# the Buck CLI for debugging / development purposes.
#
# We do not want to simply use `.buckconfig` for these, because in FBCode,
# the CI cost to updating `.buckconfig` is quite high (every project
# potentially needs to be tested and rebuilt).
#
# Instead, we keep the per-repo configuration in `oss_shim_impl.bzl`, and
# the global defaults here, in `constants.bzl`.
#
# Our underlying configs use the simple type signature of `Mapping[str,
# str]` because we want to support overrides via `buck -c`. So, some very
# simple parsing of structured configuration keys happens in this file.
#
# Configuration sources have the following precedence order:
# - `buck -c antlir.CONFIG_NAME='foo bar'` -- note that our lists are
# generally space-separated, so you'll want to bash quote those.
# - `.buckconfig` -- DO NOT PUT OUR CONFIGS THERE!
# - `do_not_use_repo_cfg` loaded via `oss_shim.bzl`
# - the defaults below -- these have to be reasonable since this is what a
# clean open-source install will use
#
# A note on naming: please put the "topic" of the constant before the
# details, so that buildifier-required lexicographic ordering of dictionary
# keys results in related keys being grouped together.
#
#
# DANGER! ACHTUNG! PELIGRO! PERICRLRM!
# Modifications to this shape's attributes or the values in the instance
# of it below (`REPO_CFG`) could (and likely will) cause excessive
# rebuilding and incur significant build cost. These attributes and values
# are effectively global and should be treated with extreme caution.
# Don't be careless.
repo_config_t = shape.shape(
artifacts_require_repo = bool,
artifact = shape.dict(str, str),
host_mounts_allowed_in_targets = shape.field(shape.list(str), optional = True),
host_mounts_for_repo_artifacts = shape.field(shape.list(str), optional = True),
flavor_available = shape.list(str),
flavor_default = str,
flavor_to_config = shape.dict(str, flavor_config_t),
antlir_linux_flavor = str,
)
REPO_CFG = shape.new(
repo_config_t,
# This one is not using the access methods to provide the precedence order
# because the way this is determined is *always* based on the build mode
# provided, ie `@mode/opt` vs `@mode/dev`. And the build mode provided
# determines the value of the `.buckconfig` properties used. There is no
# way to override this value except to use a different build mode.
artifacts_require_repo = (
(native.read_config("defaults.cxx_library", "type") == "shared") or
(native.read_config("python", "package_style") == "inplace")
),
# This is a dictionary that allow for looking up configurable artifact
# targets by a key.
artifact = _get_artifact_key_to_path(),
# At FB, the Antlir team tightly controls the usage of host mounts,
# since they are a huge footgun, and are a terrible idea for almost
# every application. To create an easy-to-review code bottleneck, any
# feature target using a host-mount must be listed in this config.
host_mounts_allowed_in_targets = _get_str_list_cfg("host_mounts_allowed_in_targets"),
# Enumerates host mounts required to execute FB binaries in @mode/dev.
#
# This is turned into json and loaded by the python side of the
# `nspawn_in_subvol` sub system. In the future this would be
# implemented via a `Shape` so that the typing can be maintained across
# bzl/python.
host_mounts_for_repo_artifacts = _get_str_list_cfg(
"host_mounts_for_repo_artifacts",
),
flavor_available = _get_str_list_cfg("flavor_available"),
flavor_default = _get_str_cfg("flavor_default"),
flavor_to_config = _get_flavor_config(),
# KEEP THIS DICTIONARY SMALL.
#
# For each `feature`, we have to emit as many targets as there are
# elements in this list, because we do not know the version set that the
# including `image.layer` will use. This would be fixable if Buck
# supported providers like Bazel does.
antlir_linux_flavor = _get_str_cfg("antlir_linux_flavor", allow_none = True),
)
|
# -*- coding: utf-8 -*-
DESC = "cpdp-2019-08-20"
INFO = {
"BindAcct": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "BindType",
"desc": "1 – 小额转账验证\n2 – 短信验证\n每个结算账户每天只能使用一次小额转账验证"
},
{
"name": "SettleAcctNo",
"desc": "用于提现\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "SettleAcctName",
"desc": "结算账户户名\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "SettleAcctType",
"desc": "1 – 本行账户\n2 – 他行账户"
},
{
"name": "IdType",
"desc": "证件类型,见《证件类型》表"
},
{
"name": "IdCode",
"desc": "证件号码\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "AcctBranchName",
"desc": "开户行名称"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "Mobile",
"desc": "用于短信验证\nBindType==2时必填\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "CnapsBranchId",
"desc": "超级网银行号和大小额行号\n二选一"
},
{
"name": "EiconBankBranchId",
"desc": "超级网银行号和大小额行号\n二选一"
}
],
"desc": "商户绑定提现银行卡,每个商户只能绑定一张提现银行卡"
},
"BindRelateAcctSmallAmount": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(若需要把一个待绑定账户关联到两个会员名下,此字段可上送两个会员的交易网代码,并且须用“|::|”(右侧)进行分隔)"
},
{
"name": "MemberName",
"desc": "STRING(150),见证子账户的户名(首次绑定的情况下,此字段即为待绑定的提现账户的户名。非首次绑定的情况下,须注意带绑定的提现账户的户名须与留存在后台系统的会员户名一致)"
},
{
"name": "MemberGlobalType",
"desc": "STRING(5),会员证件类型(详情见“常见问题”)"
},
{
"name": "MemberGlobalId",
"desc": "STRING(32),会员证件号码"
},
{
"name": "MemberAcctNo",
"desc": "STRING(50),会员的待绑定账户的账号(提现的银行卡)"
},
{
"name": "BankType",
"desc": "STRING(10),会员的待绑定账户的本他行类型(1: 本行; 2: 他行)"
},
{
"name": "AcctOpenBranchName",
"desc": "STRING(150),会员的待绑定账户的开户行名称"
},
{
"name": "Mobile",
"desc": "STRING(30),会员的手机号(手机号须由长度为11位的数字构成)"
},
{
"name": "CnapsBranchId",
"desc": "STRING(20),会员的待绑定账户的开户行的联行号(本他行类型为他行的情况下,此字段和下一个字段至少一个不为空)"
},
{
"name": "EiconBankBranchId",
"desc": "STRING(20),会员的待绑定账户的开户行的超级网银行号(本他行类型为他行的情况下,此字段和上一个字段至少一个不为空)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),转账方式(1: 往账鉴权(默认值); 2: 来账鉴权)"
}
],
"desc": "会员绑定提现账户-小额鉴权。会员申请绑定提现账户,绑定后从会员子账户中提现到绑定账户。\n转账鉴权有两种形式:往账鉴权和来账鉴权。\n往账鉴权:该接口发起成功后,银行会向提现账户转入小于等于0.5元的随机金额,并短信通知客户查看,客户查看后,需将收到的金额大小,在电商平台页面上回填,并通知银行。银行验证通过后,完成提现账户绑定。\n来账鉴权:该接口发起成功后,银行以短信通知客户查看,客户查看后,需通过待绑定的账户往市场的监管账户转入短信上指定的金额。银行检索到该笔指定金额的来账是源自待绑定账户,则绑定成功。平安银行的账户,即BankType送1时,大小额行号和超级网银号都不用送。"
},
"ApplyWithdrawal": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "SettleAcctNo",
"desc": "用于提现\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "SettleAcctName",
"desc": "结算账户户名\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "CurrencyType",
"desc": "币种 RMB"
},
{
"name": "CurrencyUnit",
"desc": "单位,1:元,2:角,3:分"
},
{
"name": "CurrencyAmt",
"desc": "金额"
},
{
"name": "TranWebName",
"desc": "交易网名称"
},
{
"name": "IdType",
"desc": "会员证件类型"
},
{
"name": "IdCode",
"desc": "会员证件号码\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
}
],
"desc": "商户提现"
},
"ModifyMntMbrBindRelateAcctBankCode": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子账户的账号"
},
{
"name": "MemberBindAcctNo",
"desc": "STRING(50),会员绑定账号"
},
{
"name": "AcctOpenBranchName",
"desc": "STRING(150),开户行名称(若大小额行号不填则送超级网银号对应的银行名称,若填大小额行号则送大小额行号对应的银行名称)"
},
{
"name": "CnapsBranchId",
"desc": "STRING(20),大小额行号(CnapsBranchId和EiconBankBranchId两者二选一必填)"
},
{
"name": "EiconBankBranchId",
"desc": "STRING(20),超级网银行号"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "维护会员绑定提现账户联行号。此接口可以支持市场修改会员的提现账户的开户行信息,具体包括开户行行名、开户行的银行联行号(大小额联行号)和超级网银行号。"
},
"QueryMemberBind": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "QueryFlag",
"desc": "STRING(4),查询标志(1: 全部会员; 2: 单个会员; 3: 单个会员的证件信息)"
},
{
"name": "PageNum",
"desc": "STRING (10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子账户的账号(若SelectFlag为2或3时,子账户账号必输)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "会员绑定信息查询。查询标志为“单个会员”的情况下,返回该会员的有效的绑定账户信息。\n查询标志为“全部会员”的情况下,返回市场下的全部的有效的绑定账户信息。查询标志为“单个会员的证件信息”的情况下,返回市场下的指定的会员的留存在电商见证宝系统的证件信息。"
},
"ReviseMbrProperty": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子账户的账号"
},
{
"name": "MemberProperty",
"desc": "STRING(10),会员属性(00-普通子账号; SH-商户子账户。暂时只支持00-普通子账号改为SH-商户子账户)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "修改会员属性-普通商户子账户。修改会员的会员属性。"
},
"QueryOrder": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主 MidasAppId"
},
{
"name": "UserId",
"desc": "用户ID,长度不小于5位, 仅支持字母和数字的组合"
},
{
"name": "Type",
"desc": "type=by_order根据订单号 查订单;\ntype=by_user根据用户id 查订单 。"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "Count",
"desc": "每页返回的记录数。根据用户 号码查询订单列表时需要传。 用于分页展示。Type=by_order时必填"
},
{
"name": "Offset",
"desc": "记录数偏移量,默认从0开 始。根据用户号码查询订单列 表时需要传。用于分页展示。Type=by_order时必填"
},
{
"name": "StartTime",
"desc": "查询开始时间,Unix时间戳。Type=by_order时必填"
},
{
"name": "EndTime",
"desc": "查询结束时间,Unix时间戳。Type=by_order时必填"
},
{
"name": "OutTradeNo",
"desc": "业务订单号,OutTradeNo与 TransactionId不能同时为 空,都传优先使用 OutTradeNo"
},
{
"name": "TransactionId",
"desc": "聚鑫订单号,OutTradeNo与 TransactionId不能同时为 空,都传优先使用 OutTradeNo"
}
],
"desc": "根据订单号,或者用户Id,查询支付订单状态 "
},
"QueryMerchantInfoForManagement": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID"
},
{
"name": "Offset",
"desc": "页码"
},
{
"name": "Limit",
"desc": "页大小"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填sandbox。"
}
],
"desc": "智慧零售-查询管理端商户"
},
"CreateCustAcctId": {
"params": [
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 开户; 3: 销户)"
},
{
"name": "FundSummaryAcctNo",
"desc": "STRING(50),资金汇总账号(即收单资金归集入账的账号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(平台端的用户ID,需要保证唯一性,可数字字母混合,如HY_120)"
},
{
"name": "MemberProperty",
"desc": "STRING(10),会员属性(00-普通子账户(默认); SH-商户子账户)"
},
{
"name": "Mobile",
"desc": "STRING(30),手机号码"
},
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "SelfBusiness",
"desc": "String(2),是否为自营业务(0位非自营,1为自营)"
},
{
"name": "ContactName",
"desc": "String(64),联系人"
},
{
"name": "SubAcctName",
"desc": "String(64),子账户名称"
},
{
"name": "SubAcctShortName",
"desc": "String(64),子账户简称"
},
{
"name": "SubAcctType",
"desc": "String(4),子账户类型(0: 个人子账户; 1: 企业子账户)"
},
{
"name": "UserNickname",
"desc": "STRING(150),用户昵称"
},
{
"name": "Email",
"desc": "STRING(150),邮箱"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "会员子账户开立。会员在银行注册,并开立会员子账户,交易网会员代码即会员在平台端系统的会员编号。\n平台需保存银行返回的子账户账号,后续交易接口都会用到。会员属性字段为预留扩展字段,当前必须送默认值。"
},
"QueryBalance": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "QueryFlag",
"desc": "2:普通会员子账号\n3:功能子账号"
},
{
"name": "PageOffset",
"desc": "起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
}
],
"desc": "子商户余额查询"
},
"BindRelateAcctUnionPay": {
"params": [
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(若需要把一个待绑定账户关联到两个会员名下,此字段可上送两个会员的交易网代码,并且须用“|::|”(右侧)进行分隔)"
},
{
"name": "MemberName",
"desc": "STRING(150),见证子账户的户名(首次绑定的情况下,此字段即为待绑定的提现账户的户名。非首次绑定的情况下,须注意带绑定的提现账户的户名须与留存在后台系统的会员户名一致)"
},
{
"name": "MemberGlobalType",
"desc": "STRING(5),会员证件类型(详情见“常见问题”)"
},
{
"name": "MemberGlobalId",
"desc": "STRING(32),会员证件号码"
},
{
"name": "MemberAcctNo",
"desc": "STRING(50),会员的待绑定账户的账号(提现的银行卡)"
},
{
"name": "BankType",
"desc": "STRING(10),会员的待绑定账户的本他行类型(1: 本行; 2: 他行)"
},
{
"name": "AcctOpenBranchName",
"desc": "STRING(150),会员的待绑定账户的开户行名称(若大小额行号不填则送超级网银号对应的银行名称,若填大小额行号则送大小额行号对应的银行名称)"
},
{
"name": "Mobile",
"desc": "STRING(30),会员的手机号(手机号须由长度为11位的数字构成)"
},
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "CnapsBranchId",
"desc": "STRING(20),会员的待绑定账户的开户行的联行号(本他行类型为他行的情况下,此字段和下一个字段至少一个不为空)"
},
{
"name": "EiconBankBranchId",
"desc": "STRING(20),会员的待绑定账户的开户行的超级网银行号(本他行类型为他行的情况下,此字段和上一个字段至少一个不为空)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "会员绑定提现账户-银联鉴权。用于会员申请绑定提现账户,申请后银行前往银联验证卡信息:姓名、证件、卡号、银行预留手机是否相符,相符则发送给会员手机动态验证码并返回成功,不相符则返回失败。\n平台接收到银行返回成功后,进入输入动态验证码的页面,有效期120秒,若120秒未输入,客户可点击重新发送动态验证码,这个步骤重新调用该接口即可。\n平安银行的账户,大小额行号和超级网银号都不用送。\n超级网银号:单笔转账金额不超过5万,不限制笔数,只用选XX银行,不用具体到支行,可实时知道对方是否收款成功。\n大小额联行号:单笔转账可超过5万,需具体到支行,不能实时知道对方是否收款成功。金额超过5万的,在工作日的8点30-17点间才会成功。"
},
"WithdrawCashMembership": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranWebName",
"desc": "STRING(150),交易网名称(市场名称)"
},
{
"name": "MemberGlobalType",
"desc": "STRING(5),会员证件类型(详情见“常见问题”)"
},
{
"name": "MemberGlobalId",
"desc": "STRING(32),会员证件号码"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码"
},
{
"name": "MemberName",
"desc": "STRING(150),会员名称"
},
{
"name": "TakeCashAcctNo",
"desc": "STRING(50),提现账号(银行卡)"
},
{
"name": "OutAmtAcctName",
"desc": "STRING(150),出金账户名称(银行卡户名)"
},
{
"name": "Ccy",
"desc": "STRING(3),币种(默认为RMB)"
},
{
"name": "CashAmt",
"desc": "STRING(20),可提现金额"
},
{
"name": "Remark",
"desc": "STRING(300),备注(建议可送订单号,可在对账文件的备注字段获取到)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
},
{
"name": "WebSign",
"desc": "STRING(300),网银签名"
}
],
"desc": "会员提现-不验证。此接口受理会员发起的提现申请。会员子账户的可提现余额、可用余额会减少,市场的资金汇总账户(监管账户)会减少相应的发生金额,提现到会员申请的收款账户。\t\t"
},
"QueryBankTransactionDetails": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 当日; 2: 历史)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子帐户的帐号"
},
{
"name": "QueryFlag",
"desc": "STRING(4),查询标志(1: 全部; 2: 转出; 3: 转入 )"
},
{
"name": "PageNum",
"desc": "STRING(10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "StartDate",
"desc": "STRING(8),开始日期(若是历史查询,则必输,当日查询时,不起作用。格式:20190101)"
},
{
"name": "EndDate",
"desc": "STRING(8),终止日期(若是历史查询,则必输,当日查询时,不起作用。格式:20190101)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询银行时间段内交易明细。查询时间段的会员成功交易。"
},
"QueryMemberTransaction": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 下单预支付; 2: 确认并付款; 3: 退款; 6: 直接支付T+1; 9: 直接支付T+0)"
},
{
"name": "OutSubAcctNo",
"desc": "STRING(50),转出方的见证子账户的账号(付款方)"
},
{
"name": "OutMemberCode",
"desc": "STRING(32),转出方的交易网会员代码"
},
{
"name": "OutSubAcctName",
"desc": "STRING(150),转出方的见证子账户的户名(户名是绑卡时上送的账户名称,如果未绑卡,就送OpenCustAcctId接口上送的用户昵称UserNickname)"
},
{
"name": "InSubAcctNo",
"desc": "STRING(50),转入方的见证子账户的账号(收款方)"
},
{
"name": "InMemberCode",
"desc": "STRING(32),转入方的交易网会员代码"
},
{
"name": "InSubAcctName",
"desc": "STRING(150),转入方的见证子账户的户名(户名是绑卡时上送的账户名称,如果未绑卡,就送OpenCustAcctId接口上送的用户昵称UserNickname)"
},
{
"name": "TranAmt",
"desc": "STRING(20),交易金额"
},
{
"name": "TranFee",
"desc": "STRING(20),交易费用(平台收取交易费用)"
},
{
"name": "TranType",
"desc": "STRING(20),交易类型(01: 普通交易)"
},
{
"name": "Ccy",
"desc": "STRING(3),币种(默认: RMB)"
},
{
"name": "OrderNo",
"desc": "STRING(50),订单号(功能标志为1,2,3时必输)"
},
{
"name": "OrderContent",
"desc": "STRING(500),订单内容"
},
{
"name": "Remark",
"desc": "STRING(300),备注(建议可送订单号,可在对账文件的备注字段获取到)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域(若需短信验证码则此项必输短信指令号)"
},
{
"name": "WebSign",
"desc": "STRING(300),网银签名(若需短信验证码则此项必输)"
}
],
"desc": "会员间交易-不验证。此接口可以实现会员间的余额的交易,实现资金在会员之间流动。"
},
"QueryInvoiceForManagement": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID"
},
{
"name": "InvoiceStatus",
"desc": "开票状态"
},
{
"name": "RedInvoiceStatus",
"desc": "红冲状态"
},
{
"name": "BeginTime",
"desc": "开始时间"
},
{
"name": "EndTime",
"desc": "结束时间"
},
{
"name": "Offset",
"desc": "页码"
},
{
"name": "Limit",
"desc": "页大小"
},
{
"name": "OrderId",
"desc": "订单号"
},
{
"name": "InvoiceId",
"desc": "发票ID"
},
{
"name": "OrderSn",
"desc": "业务开票号"
},
{
"name": "InvoiceSn",
"desc": "发票号码"
},
{
"name": "InvoiceCode",
"desc": "发票代码"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填 sandbox。"
}
],
"desc": "智慧零售-查询管理端发票"
},
"QueryCommonTransferRecharge": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1为查询当日数据,0查询历史数据)"
},
{
"name": "StartDate",
"desc": "STRING(8),开始日期(格式:20190101)"
},
{
"name": "EndDate",
"desc": "STRING(8),终止日期(格式:20190101)"
},
{
"name": "PageNum",
"desc": "STRING(10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询普通转账充值明细。接口用于查询会员主动转账进资金汇总账户的明细情况。若会员使用绑定账号转入,则直接入账到会员子账户。若未使用绑定账号转入,则系统无法自动清分到对应子账户,则转入挂账子账户由平台自行清分。若是 “见证+收单充值”T0充值记录时备注Note为“见证+收单充值,订单号” 此接口可以查到T0到账的“见证+收单充值”充值记录。"
},
"DownloadBill": {
"params": [
{
"name": "StateDate",
"desc": "请求下载对账单日期"
},
{
"name": "MidasAppId",
"desc": "聚鑫分配的MidasAppId"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的SecretId"
},
{
"name": "MidasSignature",
"desc": "使用聚鑫安全密钥计算的签名"
}
],
"desc": "账单下载接口,根据本接口返回的URL地址,在D+1日下载对账单。注意,本接口返回的URL地址有时效,请尽快下载。URL超时时效后,请重新调用本接口再次获取。"
},
"QueryAcctBinding": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "MidasSecretId",
"desc": "由平台客服提供的计费密钥Id"
},
{
"name": "MidasSignature",
"desc": "计费签名"
}
],
"desc": "聚鑫-查询子账户绑定银行卡"
},
"CloseOrder": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "UserId",
"desc": "用户ID,长度不小于5位, 仅支持字母和数字的组合"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "OutTradeNo",
"desc": "业务订单号,OutTradeNo , TransactionId二选一,不能都为空,优先使用 OutTradeNo"
},
{
"name": "TransactionId",
"desc": "聚鑫订单号,OutTradeNo , TransactionId二选一,不能都为空,优先使用 OutTradeNo"
}
],
"desc": "通过此接口关闭此前已创建的订单,关闭后,用户将无法继续付款。仅能关闭创建后未支付的订单"
},
"CreateInvoice": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID。0:高灯"
},
{
"name": "TitleType",
"desc": "抬头类型:1:个人/政府事业单位;2:企业"
},
{
"name": "BuyerTitle",
"desc": "购方名称"
},
{
"name": "OrderId",
"desc": "业务开票号"
},
{
"name": "AmountHasTax",
"desc": "含税总金额(单位为分)"
},
{
"name": "TaxAmount",
"desc": "总税额(单位为分)"
},
{
"name": "AmountWithoutTax",
"desc": "不含税总金额(单位为分)"
},
{
"name": "SellerTaxpayerNum",
"desc": "销方纳税人识别号"
},
{
"name": "SellerName",
"desc": "销方名称。(不填默认读取商户注册时输入的信息)"
},
{
"name": "SellerAddress",
"desc": "销方地址。(不填默认读取商户注册时输入的信息)"
},
{
"name": "SellerPhone",
"desc": "销方电话。(不填默认读取商户注册时输入的信息)"
},
{
"name": "SellerBankName",
"desc": "销方银行名称。(不填默认读取商户注册时输入的信息)"
},
{
"name": "SellerBankAccount",
"desc": "销方银行账号。(不填默认读取商户注册时输入的信息)"
},
{
"name": "BuyerTaxpayerNum",
"desc": "购方纳税人识别号(购方票面信息),若抬头类型为2时,必传"
},
{
"name": "BuyerAddress",
"desc": "购方地址。开具专用发票时必填"
},
{
"name": "BuyerBankName",
"desc": "购方银行名称。开具专用发票时必填"
},
{
"name": "BuyerBankAccount",
"desc": "购方银行账号。开具专用发票时必填"
},
{
"name": "BuyerPhone",
"desc": "购方电话。开具专用发票时必填"
},
{
"name": "BuyerEmail",
"desc": "收票人邮箱。若填入,会收到发票推送邮件"
},
{
"name": "TakerPhone",
"desc": "收票人手机号。若填入,会收到发票推送短信"
},
{
"name": "InvoiceType",
"desc": "开票类型:\n1:增值税专用发票;\n2:增值税普通发票;\n3:增值税电子发票;\n4:增值税卷式发票;\n5:区块链电子发票。\n若该字段不填,或值不为1-5,则认为开具”增值税电子发票”"
},
{
"name": "CallbackUrl",
"desc": "发票结果回传地址"
},
{
"name": "Drawer",
"desc": "开票人姓名。(不填默认读取商户注册时输入的信息)"
},
{
"name": "Payee",
"desc": "收款人姓名。(不填默认读取商户注册时输入的信息)"
},
{
"name": "Checker",
"desc": "复核人姓名。(不填默认读取商户注册时输入的信息)"
},
{
"name": "TerminalCode",
"desc": "税盘号"
},
{
"name": "LevyMethod",
"desc": "征收方式。开具差额征税发票时必填2。开具普通征税发票时为空"
},
{
"name": "Deduction",
"desc": "差额征税扣除额(单位为分)"
},
{
"name": "Remark",
"desc": "备注(票面信息)"
},
{
"name": "Items",
"desc": "项目商品明细"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填sandbox。"
}
],
"desc": "智慧零售-发票开具"
},
"QueryCustAcctIdBalance": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "QueryFlag",
"desc": "STRING(4),查询标志(2: 普通会员子账号; 3: 功能子账号)"
},
{
"name": "PageNum",
"desc": "STRING(10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子账户的账号(若SelectFlag为2时,子账号必输)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询银行子账户余额。查询会员子账户以及平台的功能子账户的余额。"
},
"QueryRefund": {
"params": [
{
"name": "UserId",
"desc": "用户ID,长度不小于5位,仅支持字母和数字的组合。"
},
{
"name": "RefundId",
"desc": "退款订单号,仅支持数字、字母、下划线(_)、横杠字符(-)、点(.)的组合。"
},
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
}
],
"desc": "提交退款申请后,通过调用该接口查询退款状态。退款可能有一定延时,用微信零钱支付的退款约20分钟内到账,银行卡支付的退款约3个工作日后到账。"
},
"RegisterBillSupportWithdraw": {
"params": [
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码"
},
{
"name": "OrderNo",
"desc": "STRING(50),订单号"
},
{
"name": "SuspendAmt",
"desc": "STRING(20),挂账金额(包含交易费用)"
},
{
"name": "TranFee",
"desc": "STRING(20),交易费用(暂未使用,默认传0.0)"
},
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "Remark",
"desc": "STRING(300),备注"
},
{
"name": "ReservedMsgOne",
"desc": "STRING(300),保留域1"
},
{
"name": "ReservedMsgTwo",
"desc": "STRING(300),保留域2"
},
{
"name": "ReservedMsgThree",
"desc": "STRING(300),保留域3"
}
],
"desc": "登记挂账(支持撤销)。此接口可实现把不明来账或自有资金等已登记在挂账子账户下的资金调整到普通会员子账户。即通过申请调用此接口,将会减少挂账子账户的资金,调增指定的普通会员子账户的可提现余额及可用余额。此接口不支持把挂账子账户资金清分到功能子账户。"
},
"QueryBankClear": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 全部; 2: 指定时间段)"
},
{
"name": "PageNum",
"desc": "STRING (10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "StartDate",
"desc": "STRING(8),开始日期(若是指定时间段查询,则必输,当查询全部时,不起作用。格式: 20190101)"
},
{
"name": "EndDate",
"desc": "STRING(8),终止日期(若是指定时间段查询,则必输,当查询全部时,不起作用。格式:20190101)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询银行在途清算结果。查询时间段内交易网的在途清算结果。"
},
"QuerySingleTransactionStatus": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(2: 会员间交易; 3: 提现; 4: 充值)"
},
{
"name": "TranNetSeqNo",
"desc": "STRING(52),交易网流水号(提现,充值或会员交易请求时的CnsmrSeqNo值)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子帐户的帐号(未启用)"
},
{
"name": "TranDate",
"desc": "STRING(8),交易日期(未启用)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询银行单笔交易状态。查询单笔交易的状态。"
},
"UnBindAcct": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "SettleAcctNo",
"desc": "用于提现\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
}
],
"desc": "商户解除绑定的提现银行卡"
},
"BindRelateAccReUnionPay": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(若需要把一个待绑定账户关联到两个会员名下,此字段可上送两个会员的交易网代码,并且须用“|::|”(右侧)进行分隔)"
},
{
"name": "MemberAcctNo",
"desc": "STRING(50),会员的待绑定账户的账号(即 BindRelateAcctUnionPay接口中的“会员的待绑定账户的账号”)"
},
{
"name": "MessageCheckCode",
"desc": "STRING(20),短信验证码(即 BindRelateAcctUnionPay接口中的手机所接收到的短信验证码)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "会员绑定提现账户-回填银联鉴权短信码。用于会员填写动态验证码后,发往银行进行验证,验证成功则完成绑定。"
},
"CreateRedInvoice": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID"
},
{
"name": "Invoices",
"desc": "红冲明细"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填 sandbox。"
}
],
"desc": "智慧零售-发票红冲"
},
"CheckAmount": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(若需要把一个待绑定账户关联到两个会员名下,此字段可上送两个会员的交易网代码,并且须用“|::|”(右侧)进行分隔)"
},
{
"name": "TakeCashAcctNo",
"desc": "STRING(50),会员的待绑定账户的账号(即 BindRelateAcctSmallAmount接口中的“会员的待绑定账户的账号”)"
},
{
"name": "AuthAmt",
"desc": "STRING(20),鉴权验证金额(即 BindRelateAcctSmallAmount接口中的“会员的待绑定账户收到的验证金额。原小额转账鉴权方式为来账鉴权的情况下此字段须赋值为0.00)"
},
{
"name": "Ccy",
"desc": "STRING(3),币种(默认为RMB)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),原小额转账方式(1: 往账鉴权,此为默认值; 2: 来账鉴权)"
}
],
"desc": "验证鉴权金额。此接口可受理BindRelateAcctSmallAmount接口发起的转账金额(往账鉴权方式)的验证处理。若所回填的验证金额验证通过,则会绑定原申请中的银行账户作为提现账户。通过此接口也可以查得BindRelateAcctSmallAmount接口发起的来账鉴权方式的申请的当前状态。"
},
"RevResigterBillSupportWithdraw": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码"
},
{
"name": "OldOrderNo",
"desc": "STRING(30),原订单号(RegisterBillSupportWithdraw接口中的订单号)"
},
{
"name": "CancelAmt",
"desc": "STRING(20),撤销金额(支持部分撤销,不能大于原订单可用金额,包含交易费用)"
},
{
"name": "TranFee",
"desc": "STRING(20),交易费用(暂未使用,默认传0.0)"
},
{
"name": "Remark",
"desc": "STRING(300),备注"
},
{
"name": "ReservedMsgOne",
"desc": "STRING(300),保留域1"
},
{
"name": "ReservedMsgTwo",
"desc": "STRING(300),保留域2"
},
{
"name": "ReservedMsgThree",
"desc": "STRING(300),保留域3"
}
],
"desc": "登记挂账撤销。此接口可以实现把RegisterBillSupportWithdraw接口完成的登记挂账进行撤销,即调减普通会员子账户的可提现和可用余额,调增挂账子账户的可用余额。"
},
"RevokeMemberRechargeThirdPay": {
"params": [
{
"name": "OldFillFrontSeqNo",
"desc": "STRING(52),原充值的前置流水号"
},
{
"name": "OldFillPayChannelType",
"desc": "STRING(20),原充值的支付渠道类型"
},
{
"name": "OldPayChannelTranSeqNo",
"desc": "STRING(52),原充值的支付渠道交易流水号"
},
{
"name": "OldFillEjzbOrderNo",
"desc": "STRING(52),原充值的电商见证宝订单号"
},
{
"name": "ApplyCancelMemberAmt",
"desc": "STRING(20),申请撤销的会员金额"
},
{
"name": "ApplyCancelCommission",
"desc": "STRING(20),申请撤销的手续费金额"
},
{
"name": "MrchCode",
"desc": "String(22),商户号"
},
{
"name": "Remark",
"desc": "STRING(300),备注"
},
{
"name": "ReservedMsgOne",
"desc": "STRING(300),保留域1"
},
{
"name": "ReservedMsgTwo",
"desc": "STRING(300),保留域2"
},
{
"name": "ReservedMsgThree",
"desc": "STRING(300),保留域3"
}
],
"desc": "撤销会员在途充值(经第三方支付渠道)"
},
"Refund": {
"params": [
{
"name": "UserId",
"desc": "用户ID,长度不小于5位, 仅支持字母和数字的组合"
},
{
"name": "RefundId",
"desc": "退款订单号,仅支持数字、 字母、下划线(_)、横杠字 符(-)、点(.)的组合"
},
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "TotalRefundAmt",
"desc": "退款金额,单位:分。备注:当该字段为空或者为0 时,系统会默认使用订单当 实付金额作为退款金额"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "OutTradeNo",
"desc": "商品订单,仅支持数字、字 母、下划线(_)、横杠字符 (-)、点(.)的组合。 OutTradeNo ,TransactionId 二选一,不能都为空,优先使用 OutTradeNo"
},
{
"name": "MchRefundAmt",
"desc": "结算应收金额,单位:分"
},
{
"name": "TransactionId",
"desc": "调用下单接口获取的聚鑫交 易订单。 OutTradeNo ,TransactionId 二选一,不能都为空,优先使用 OutTradeNo"
},
{
"name": "PlatformRefundAmt",
"desc": "平台应收金额,单位:分"
},
{
"name": "SubOrderRefundList",
"desc": "支持多个子订单批量退款单 个子订单退款支持传 SubOutTradeNo ,也支持传 SubOutTradeNoList ,都传的时候以 SubOutTradeNoList 为准。 如果传了子单退款细节,外 部不需要再传退款金额,平 台应退,商户应退金额,我 们可以直接根据子单退款算出来总和。"
}
],
"desc": "如交易订单需退款,可以通过本接口将支付款全部或部分退还给付款方,聚鑫将在收到退款请求并且验证成功之后,按照退款规则将支付款按原路退回到支付帐号。最长支持1年的订单退款。在订单包含多个子订单的情况下,如果使用本接口传入OutTradeNo或TransactionId退款,则只支持全单退款;如果需要部分退款,请通过传入子订单的方式来指定部分金额退款。 "
},
"QuerySmallAmountTransfer": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "OldTranSeqNo",
"desc": "STRING(52),原交易流水号(小额鉴权交易请求时的CnsmrSeqNo值)"
},
{
"name": "TranDate",
"desc": "STRING(8),交易日期(格式:20190101)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询小额鉴权转账结果。查询小额往账鉴权的转账状态。"
},
"RechargeMemberThirdPay": {
"params": [
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会代码"
},
{
"name": "MemberFillAmt",
"desc": "STRING(20),会员充值金额"
},
{
"name": "Commission",
"desc": "STRING(20),手续费金额"
},
{
"name": "Ccy",
"desc": "STRING(3),币种。如RMB"
},
{
"name": "PayChannelType",
"desc": "STRING(20),支付渠道类型。\n0001-微信\n0002-支付宝\n0003-京东支付"
},
{
"name": "PayChannelAssignMerNo",
"desc": "STRING(50),支付渠道所分配的商户号"
},
{
"name": "PayChannelTranSeqNo",
"desc": "STRING(52),支付渠道交易流水号"
},
{
"name": "EjzbOrderNo",
"desc": "STRING(52),电商见证宝订单号"
},
{
"name": "MrchCode",
"desc": "String(22),商户号"
},
{
"name": "EjzbOrderContent",
"desc": "STRING(500),电商见证宝订单内容"
},
{
"name": "Remark",
"desc": "STRING(300),备注"
},
{
"name": "ReservedMsgOne",
"desc": "STRING(300),保留域1"
},
{
"name": "ReservedMsgTwo",
"desc": "STRING(300),保留域2"
},
{
"name": "ReservedMsgThree",
"desc": "STRING(300),保留域3"
}
],
"desc": "见证宝-会员在途充值(经第三方支付渠道)"
},
"QueryInvoice": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID"
},
{
"name": "OrderId",
"desc": "订单号"
},
{
"name": "OrderSn",
"desc": "业务开票号"
},
{
"name": "IsRed",
"desc": "发票种类:\n0:蓝票\n1:红票【该字段默认为0, 如果需要查询红票信息,本字段必须传1,否则可能查询不到需要的发票信息】。"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填sandbox。"
}
],
"desc": "智慧零售-发票查询"
},
"CreateMerchant": {
"params": [
{
"name": "InvoicePlatformId",
"desc": "开票平台ID"
},
{
"name": "TaxpayerName",
"desc": "企业名称"
},
{
"name": "TaxpayerNum",
"desc": "销方纳税人识别号"
},
{
"name": "LegalPersonName",
"desc": "注册企业法人代表名称"
},
{
"name": "ContactsName",
"desc": "联系人"
},
{
"name": "Phone",
"desc": "联系人手机号"
},
{
"name": "Address",
"desc": "不包含省市名称的地址"
},
{
"name": "RegionCode",
"desc": "地区编码"
},
{
"name": "CityName",
"desc": "市(地区)名称"
},
{
"name": "Drawer",
"desc": "开票人"
},
{
"name": "TaxRegistrationCertificate",
"desc": "税务登记证图片(Base64)字符串,需小于 3M"
},
{
"name": "Email",
"desc": "联系人邮箱地址"
},
{
"name": "BusinessMobile",
"desc": "企业电话"
},
{
"name": "BankName",
"desc": "银行名称"
},
{
"name": "BankAccount",
"desc": "银行账号"
},
{
"name": "Reviewer",
"desc": "复核人"
},
{
"name": "Payee",
"desc": "收款人"
},
{
"name": "RegisterCode",
"desc": "注册邀请码"
},
{
"name": "State",
"desc": "不填默认为1,有效状态\n0:表示无效;\n1:表示有效;\n2:表示禁止开蓝票;\n3:表示禁止冲红。"
},
{
"name": "CallbackUrl",
"desc": "接收推送的消息地址"
},
{
"name": "Profile",
"desc": "接入环境。沙箱环境填 sandbox。"
}
],
"desc": "智慧零售-商户注册"
},
"CreateAcct": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫平台分配的支付MidasAppId"
},
{
"name": "SubMchId",
"desc": "业务平台的子商户ID,唯一"
},
{
"name": "SubMchName",
"desc": "子商户名称"
},
{
"name": "Address",
"desc": "子商户地址"
},
{
"name": "Contact",
"desc": "子商户联系人\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "Mobile",
"desc": "联系人手机号\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "Email",
"desc": "邮箱 \n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "SubMchType",
"desc": "子商户类型:\n个人: personal\n企业:enterprise\n缺省: enterprise"
},
{
"name": "ShortName",
"desc": "不填则默认子商户名称"
},
{
"name": "SubMerchantMemberType",
"desc": "子商户会员类型:\ngeneral:普通子账户\nmerchant:商户子账户\n缺省: general"
}
],
"desc": "子商户入驻聚鑫平台"
},
"UnifiedOrder": {
"params": [
{
"name": "CurrencyType",
"desc": "ISO 货币代码,CNY"
},
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "OutTradeNo",
"desc": "支付订单号,仅支持数字、字母、下划线(_)、横杠字符(-)、点(.)的组合"
},
{
"name": "ProductDetail",
"desc": "商品详情,需要URL编码"
},
{
"name": "ProductId",
"desc": "商品ID,仅支持数字、字母、下划线(_)、横杠字符(-)、点(.)的组合"
},
{
"name": "ProductName",
"desc": "商品名称,需要URL编码"
},
{
"name": "TotalAmt",
"desc": "支付金额,单位: 分"
},
{
"name": "UserId",
"desc": "用户ID,长度不小于5位,仅支持字母和数字的组合"
},
{
"name": "RealChannel",
"desc": "银行真实渠道.如:bank_pingan"
},
{
"name": "OriginalAmt",
"desc": "原始金额"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "CallbackUrl",
"desc": "Web端回调地址"
},
{
"name": "Channel",
"desc": "指定支付渠道: wechat:微信支付 qqwallet:QQ钱包 \n bank:网银支付 只有一个渠道时需要指定"
},
{
"name": "Metadata",
"desc": "透传字段,支付成功回调透传给应用,用于业务透传自定义内容"
},
{
"name": "Quantity",
"desc": "购买数量,不传默认为1"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "SubOrderList",
"desc": "子订单信息列表,格式:子订单号、子应用ID、金额。 压缩后最长不可超过65535字节(去除空格,换行,制表符等无意义字符)\n注:接入银行或其他支付渠道服务商模式下,必传"
},
{
"name": "TotalMchIncome",
"desc": "结算应收金额,单位:分"
},
{
"name": "TotalPlatformIncome",
"desc": "平台应收金额,单位:分"
},
{
"name": "WxOpenId",
"desc": "微信公众号/小程序支付时为必选,需要传微信下的openid"
},
{
"name": "WxSubOpenId",
"desc": "在服务商模式下,微信公众号/小程序支付时wx_sub_openid和wx_openid二选一"
}
],
"desc": "应用需要先调用本接口生成支付订单号,并将应答的PayInfo透传给聚鑫SDK,拉起客户端(包括微信公众号/微信小程序/客户端App)支付。"
},
"RevRegisterBillSupportWithdraw": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码"
},
{
"name": "OldOrderNo",
"desc": "STRING(30),原订单号(RegisterBillSupportWithdraw接口中的订单号)"
},
{
"name": "CancelAmt",
"desc": "STRING(20),撤销金额(支持部分撤销,不能大于原订单可用金额,包含交易费用)"
},
{
"name": "TranFee",
"desc": "STRING(20),交易费用(暂未使用,默认传0.0)"
},
{
"name": "Remark",
"desc": "STRING(300),备注"
},
{
"name": "ReservedMsgOne",
"desc": "STRING(300),保留域1"
},
{
"name": "ReservedMsgTwo",
"desc": "STRING(300),保留域2"
},
{
"name": "ReservedMsgThree",
"desc": "STRING(300),保留域3"
}
],
"desc": "登记挂账撤销。此接口可以实现把RegisterBillSupportWithdraw接口完成的登记挂账进行撤销,即调减普通会员子账户的可提现和可用余额,调增挂账子账户的可用余额。"
},
"UnbindRelateAcct": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 解绑)"
},
{
"name": "TranNetMemberCode",
"desc": "STRING(32),交易网会员代码(若需要把一个待绑定账户关联到两个会员名下,此字段可上送两个会员的交易网代码,并且须用“|::|”(右侧)进行分隔)"
},
{
"name": "MemberAcctNo",
"desc": "STRING(50),待解绑的提现账户的账号(提现账号)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "会员解绑提现账户。此接口可以支持会员解除名下的绑定账户关系。"
},
"QueryBankWithdrawCashDetails": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号(签约客户号)"
},
{
"name": "FunctionFlag",
"desc": "STRING(2),功能标志(1: 当日; 2: 历史)"
},
{
"name": "SubAcctNo",
"desc": "STRING(50),见证子帐户的帐号"
},
{
"name": "QueryFlag",
"desc": "STRING(4),查询标志(2: 提现; 3: 清分)"
},
{
"name": "PageNum",
"desc": "STRING(10),页码(起始值为1,每次最多返回20条记录,第二页返回的记录数为第21至40条记录,第三页为41至60条记录,顺序均按照建立时间的先后)"
},
{
"name": "BeginDate",
"desc": "STRING(8),开始日期(若是历史查询,则必输,当日查询时,不起作用。格式:20190101)"
},
{
"name": "EndDate",
"desc": "STRING(8),结束日期(若是历史查询,则必输,当日查询时,不起作用。格式:20190101)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询银行时间段内清分提现明细。查询银行时间段内清分提现明细接口:若为“见证+收单退款”“见证+收单充值”记录时备注Note为“见证+收单充值,订单号”“见证+收单退款,订单号”,此接口可以查到T0/T1的充值明细和退款记录。查询标志:充值记录仍用3清分选项查询,退款记录同提现用2选项查询。"
},
"QueryReconciliationDocument": {
"params": [
{
"name": "MrchCode",
"desc": "String(22),商户号"
},
{
"name": "FileType",
"desc": "STRING(10),文件类型(充值文件-CZ; 提现文件-TX; 交易文件-JY; 余额文件-YE; 合约文件-HY)"
},
{
"name": "FileDate",
"desc": "STRING(8),文件日期(格式:20190101)"
},
{
"name": "ReservedMsg",
"desc": "STRING(1027),保留域"
}
],
"desc": "查询对账文件信息。平台调用该接口获取需下载对账文件的文件名称以及密钥。 平台获取到信息后, 可以再调用OPENAPI的文件下载功能。"
},
"CheckAcct": {
"params": [
{
"name": "MidasAppId",
"desc": "聚鑫分配的支付主MidasAppId"
},
{
"name": "SubAppId",
"desc": "聚鑫计费SubAppId,代表子商户"
},
{
"name": "BindType",
"desc": "1:小额鉴权\n2:短信校验鉴权"
},
{
"name": "SettleAcctNo",
"desc": "结算账户账号\n<敏感信息>加密详见《商户端接口敏感信息加密说明》"
},
{
"name": "MidasSecretId",
"desc": "聚鑫分配的安全ID"
},
{
"name": "MidasSignature",
"desc": "按照聚鑫安全密钥计算的签名"
},
{
"name": "CheckCode",
"desc": "短信验证码\nBindType==2必填"
},
{
"name": "CurrencyType",
"desc": "币种 RMB\nBindType==1必填"
},
{
"name": "CurrencyUnit",
"desc": "单位\n1:元,2:角,3:分\nBindType==1必填"
},
{
"name": "CurrencyAmt",
"desc": "金额\nBindType==1必填"
}
],
"desc": "商户绑定提现银行卡的验证接口"
}
}
|
# 比较两个版本号 version1 和 version2。
# 如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1, 除此之外返回 0。
# 你可以假设版本字符串非空,并且只包含数字和 . 字符。
# . 字符不代表小数点,而是用于分隔数字序列。
# 例如,2.5 不是“两个半”,也不是“差一半到三”,而是第二版中的第五个小版本。
# 你可以假设版本号的每一级的默认修订版号为 0。
# 例如,版本号 3.4 的第一级(大版本)和第二级(小版本)修订号分别为 3 和 4。其第三级和第四级修订号均为 0。
#
# 示例 1:
# 输入: version1 = "0.1", version2 = "1.1"
# 输出: -1
# 示例 2:
# 输入: version1 = "1.0.1", version2 = "1"
# 输出: 1
# 示例 3:
# 输入: version1 = "7.5.2.4", version2 = "7.5.3"
# 输出: -1
# 示例 4:
# 输入:version1 = "1.01", version2 = "1.001"
# 输出:0
# 解释:忽略前导零,“01” 和 “001” 表示相同的数字 “1”。
# 示例 5:
# 输入:version1 = "1.0", version2 = "1.0.0"
# 输出:0
# 解释:version1 没有第三级修订号,这意味着它的第三级修订号默认为 “0”。
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
version1 = version1.split(".")
version2 = version2.split(".")
l1 = len(version1)
l2 = len(version2)
# 补充 0 使两列表长度相等
if l1 > l2:
version2.extend(['0' for _ in range(l1 - l2)])
elif l2 > l1:
version1.extend(['0' for _ in range(l2 - l1)])
# 按规则比较
for i1, i2 in zip(version1, version2):
if int(i1) > int(i2):
return 1
elif int(i1) < int(i2):
return -1
return 0
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if len(x) >= 5 and x[3] == x[1] and x[4] + x[0] >= x[2]:
# Crossing in a loop:
# 2
# 3 ┌────┐
# └─══>┘1
# 4 0 (overlapped)
return True
for i in xrange(3, len(x)):
if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]:
# Case 1:
# i-2
# i-1┌─┐
# └─┼─>i
# i-3
return True
elif i >= 5 and x[i - 4] <= x[i - 2] and x[i] + x[i - 4] >= x[i - 2] and \
x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]:
# Case 2:
# i-4
# ┌──┐
# │i<┼─┐
# i-3│ i-5│i-1
# └────┘
# i-2
return True
return False
|
"""
Erik Meijer. 2014. The curse of the excluded middle.
Commun. ACM 57, 6 (June 2014), 50-55. DOI=10.1145/2605176
http://doi.acm.org/10.1145/2605176
"""
with open('citation.txt', encoding='ascii') as fp:
get_contents = lambda: fp.read()
print(get_contents())
|
t=int(input())
P=[]
answer=[]
while(t!=0):
N,K=map(int, input().split())
P=list(map(int, input().split()))
P.sort()
for j in range(N):
if(P[j]<=K and K%P[j]==0):
answer.append(P[j])
elif(P[j]>K):
break
else:
continue
#answer the position
answer.reverse()
if(len(answer)>0):
print(answer[0])
else:
print(-1)
answer.clear()
P.clear()
t-=1
|
class newsArticles:
'''
Class defining articles
'''
def __init__(self, source, author, title, description, url, image_url, publish_time, content):
self.source = source # Name of the source of news
self.author = author # Author of the news article
self.title = title # Title of the news article
self.description = description # Snippet of the news article
self.url = url # URL to the news article
self.image_url = image_url # URL for the news article image
self.publish_time = publish_time # Publication date of the news article
self.content = content # Content of the article
class newsSource:
'''
Class defining news sources
'''
pass
|
nota1=float(input('digite sua primeira nota:'))
nota2=float(input('digite sua segunda nota'))
media=(nota1+nota2)/2
print('sua média é ', media)
|
# There are three type methods
# Instance methods
# Class methods
# Static methods
class Student:
school = "Telusko"
@classmethod
def get_school(cls):
return cls.school
@staticmethod
def info():
print("This is Student Class")
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return (self.m1 + self.m2 + self.m3) / 3
def get_m1(self):
return self.m1
def set_m1(self, value):
self.m1 = value
s1 = Student(34, 47, 32)
s2 = Student(89, 32, 12)
print(s1.avg(), s2.avg())
print(Student.get_school())
Student.info()
|
def method1(arr: list, n: int) -> list:
longest = 1
cnt = 1
for i in range(n - 1):
if (arr[i] + arr[i + 1]) % 2 == 1:
cnt = cnt + 1
else:
longest = max(longest, cnt)
cnt = 1
if longest == 1:
return 0
return max(cnt, longest)
if __name__ == "__main__":
"""
arr = [ 1, 2, 3, 4, 5, 7, 8 ]
n = len(arr)
from timeit import timeit
print(timeit(lambda: method1(arr, n), number=10000)) # 0.01877671800320968
"""
|
# Find the Access Codes
# =====================
# In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that includes the locks' access codes, but only she knows how to figure out which of several lists contains the access codes. You need to find a way to determine which list contains the access codes once you're ready to go in.
# Fortunately, now that you're Commander Lambda's personal assistant, she's confided to you that she made all the access codes "lucky triples" in order to help her better find them in the lists. A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4). With that information, you can figure out which list contains the number of access codes that matches the number of locks on the door when you're ready to go in (for example, if there's 5 passcodes, you'd need to find a list with 5 "lucky triple" access codes).
# Write a function solution(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet the requirement i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0.
# For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total.
# Languages
# =========
# To provide a Java solution, edit Solution.java
# To provide a Python solution, edit solution.py
# Test cases
# ==========
# Your code should pass the following test cases.
# Note that it may also be run against hidden test cases not shown here.
# -- Java cases --
# Input:
# Solution.solution([1, 1, 1])
# Output:
# 1
# Input:
# Solution.solution([1, 2, 3, 4, 5, 6])
# Output:
# 3
# -- Python cases --
# Input:
# solution.solution([1, 2, 3, 4, 5, 6])
# Output:
# 3
# Input:
# solution.solution([1, 1, 1])
# Output:
# 1
# Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.
# foobar:~/find-the-access-codes narayananajay99$
def solution_brute(l):
# Brute force
n = len(l)
count = 0
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
# (i, j, k)
if( l[j] % l[i] == 0 and l[k] % l[j] == 0):
count += 1
return count
def solution(l):
# Brute force solution doesn't pass.
# Let counts[j] represent the number of pairs <i, j> with i < j, l[j] % l[i] == 0 and i >= 0 ; for each j in 0 <= j < n
# Now for each pair <j, k> with j < k, j >= 0 and l[k] % l[j] == 0,
# there exits counts[j] of triplets <i, j, k> such that l[j] % l[i] == 0
n = len(l)
counts = [0]*n
triplets = 0
# counts[j] computation
for j in range(n):
for i in range(j):
# <i, j> pair
if( l[j] % l[i] == 0):
counts[j] += 1
# total triplets count computation
for k in range(n):
for j in range(k):
# All <i, j, k> pair with
# l[j] % l[i] == 0
# l[k] % l[j] == 0
# i < j < k and i, j, k >= 0
if(l[k] % l[j] == 0):
triplets += counts[j]
return triplets
|
a,b,c=list(map(int, input().split()))
arr=[a,b,c]
arr=sorted(arr)
print(arr[0],arr[1],arr[2])
|
class TaskDTO:
task_id = None
name = None
args = None
running = None
def __init__(self, task):
self.task_id = task["id"]
self.name = task["name"].split(".")[-1]
self.args = task["args"]
self.running = task["time_start"] is not None
|
class Socks5Error(Exception):
pass
class NoVersionAllowed(Socks5Error):
pass
class NoCommandAllowed(Socks5Error):
pass
class NoATYPAllowed(Socks5Error):
pass
class AuthenticationError(Socks5Error):
pass
class NoAuthenticationAllowed(AuthenticationError):
pass
|
"""Slide"""
|
"""Linkedlist implementation."""
class Node(object):
"""Node class."""
def __init__(self, initdata=None):
"""Initialization."""
self.data = initdata
self.next = None
def getData(self):
"""Get node's data."""
return self.data
def setData(self, data):
"""Set node's data."""
self.data = data
def getNext(self):
"""Get next node."""
return self.next
def setNext(self, node):
"""Set next node."""
self.next = node
class UnorderedList(object):
"""Linkedlist implementation."""
def __init__(self):
"""Initialization of list."""
self.head = None
self.end = None
def isEmpty(self):
"""Tests if the list is empty."""
"""
:rtype: Bool
"""
return self.head == None
def add(self, item):
"""Adds a new item to the list. Assumes item is not present."""
"""
:type item: Node()
"""
if self.head == None:
self.head = Node(item)
elif self.end == None:
self.end = self.head
self.head = Node(item)
self.head.setNext(self.end)
else:
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def remove(self, item):
"""Removes the item from the list. Assumes item is present."""
"""
:type item: Node()
"""
prev = self.head
curr = self.head
temp = Node(item)
while curr:
if self.head.getData() == temp.getData():
self.head = curr.getNext()
if self.end.getData() == temp.getData():
self.end = None
break
elif self.end.getData() == temp.getData():
self.end = prev
break
elif curr.getData() == temp.getData():
prev.setNext(curr.getNext())
curr = None
break
prev = curr
curr = curr.getNext()
def search(self, item):
"""Searches for the item in the list."""
"""
:type item: Node()
:rtype: Bool
"""
curr = self.head
while curr:
if curr.getData() == item.getData():
return True
curr = curr.getNext()
return False
def size(self):
"""Returns the number of items in the list."""
"""
:rtype: Int: size of list
"""
size = 0
curr = self.head
while curr:
curr = curr.getNext()
size += 1
return size
def append(self, item):
"""Adds a new item to the end of the list. Assumes item is not present."""
"""
:type item: Node()
"""
temp = Node(item)
self.end.setNext(temp)
self.end = temp
def index(self, item):
"""Returns the position of item in the list. Assumes item is present."""
"""
:type item: Node()
:rtype pos: Int
"""
curr = self.head
idx = 0
while curr:
if curr.getData() == item.getData():
return idx
idx += 1
curr = curr.getNext()
def insert(self, pos, item):
"""Adds a new item in the list at position pos. Assumes item is not present."""
"""
:type item: Node()
"""
if pos == 0:
item.setNext(self.head)
self.head = item
else:
prev = self.head
curr = self.head
idx = 0
while curr:
if idx == pos:
prev.setNext(item)
item.setNext(curr)
break
prev = curr
curr = curr.getNext()
idx += 1
def pop(self, pos=None):
"""
Removes and returns the item at position pos. It needs the position and returns the item.
Assumes the item is in the list.
"""
"""
:type pos: int
:rtype node: Node()
"""
if pos == None:
pos = self.size() - 1
if pos == 0:
h = self.head
self.head = None
return h
else:
prev = curr = self.head
idx = 0
while curr:
if idx == pos:
prev.setNext(curr.getNext())
return curr
idx += 1
prev = curr
curr = curr.getNext()
if __name__ == "__main__":
node = Node()
assert(node.data == None)
assert(node.next == None)
node.setData(1)
assert(node.getData() == 1)
node.setNext(Node(1000000000000))
assert(node.getNext().getData() == 1000000000000)
assert(node.next.getData() == 1000000000000)
list = UnorderedList()
assert(list.isEmpty())
n1 = 1
n2 = 2
n3 = 10000
n4 = 432424
list.add(n1)
list.add(n2)
list.add(n3)
assert(not list.isEmpty())
# Remove from middle
list.remove(n2)
# Remove from beginning
list.remove(n1)
list.remove(n3)
print('list size %d' % list.size())
assert(list.size() == 0)
# Remove from end of list
list.add(n3)
list.add(n4)
list.remove(n3)
assert(list.size() == 1)
assert(list.search(n4))
assert(not list.search(n3))
n5 = 1434134
list.append(n5)
assert(list.search(n5))
n6 = 16744
list.append(n6)
assert(list.index(n5) == 1)
assert(list.index(n6) == 2)
list.remove(n5)
assert(list.index(n6) == 1)
list.insert(0, n1)
assert(list.index(n1) == 0)
n10 = 12012030213
n40 = 123899031954
list.insert(2, n10)
list.insert(3, n40)
assert(list.index(n10) == 2)
assert(list.index(n40) == 3)
assert(list.pop(2) == n10)
assert(list.pop() == n6)
|
# Copy and rename this file to settings.py to be in effect.
# Maximum total number of files to maintain/copy in all of the batch/dst directories.
LIMIT = 1000
# How many seconds to sleep before checking for the above limit again.
# If the last number is reached and the check still fails,
# then the whole script will exit and the current file list will be saved as
# a csv at SAVED_FILE_LIST_PATH below.
# This is to prevent the script from hanging while Splunk is down.
SLEEP = [1, 1, 1, 1, 1, 5, 10, 30, 600]
SAVED_FILE_LIST_PATH = "/mnt/data/tmp/mass_index_saved_file_list.csv"
LOG_PATH = "/tmp/mass_index.log"
# Size of each log file.
# 1 MB = 1 * 1024 * 1024
LOG_ROTATION_BYTES = 25 * 1024 * 1024
# Maximum number of log files.
LOG_ROTATION_LIMIT = 100
DATA = [
{
"src": "/path/to/data/*.log",
"dst": "/some/path/foo/",
},
{
"src": "/path/to/another/data/*.log",
"dst": "/some/path/bar/",
},
]
|
"""
Constant values used throughout the app.
"""
CALLBACK_PATH = '/v1/das/callback'
ACQUISITION_PATH = '/rest/das/requests'
GET_REQUEST_PATH = ACQUISITION_PATH + '/{req_id}'
DOWNLOAD_CALLBACK_PATH = CALLBACK_PATH + '/downloader/{req_id}'
DOWNLOADER_PATH = '/rest/downloader/requests'
METADATA_PARSER_PATH = '/rest/metadata'
METADATA_PARSER_CALLBACK_PATH = CALLBACK_PATH + '/metadata/{req_id}'
UPLOADER_REQUEST_PATH = CALLBACK_PATH + '/uploader'
|
# @Title: 二叉树的最大深度 (Maximum Depth of Binary Tree)
# @Author: KivenC
# @Date: 2018-12-02 22:04:32
# @Runtime: 64 ms
# @Memory: N/A
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
|
matrix = [input().split() for row in range(int(input()))]
primary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += int(matrix[i][i])
print(primary_diagonal_sum)
|
class TaskMixin:
def _get_is_labeled_value(self):
n = self.completed_annotations.count()
return n >= self.overlap
|
class Vehicle:
DEFAULT_FUEL_CONSUMPTION = 1.25
def __init__(self, fuel, horse_power):
self.fuel = fuel
self.horse_power = horse_power
self.fuel_consumption = self.DEFAULT_FUEL_CONSUMPTION
def drive(self, kilometers):
fuel_needed = kilometers * self.fuel_consumption
if fuel_needed <= self.fuel:
self.fuel -= fuel_needed
|
"""Top-level package for climinteractive."""
__author__ = """Bjoern Mayer"""
__email__ = 'bjoern.mayer@mpimet.mpg.de'
__version__ = '0.1.0'
|
#dictionary
Person = {'personID': 0,
'firstName': "",
'lastName': "",
'Account': {'accountNumber': 0,
'accountType': 0,
'money': 0,
'limit': 0}
}
def inputPerson():
Person['personID'] = int(input("Enter Customer ID: "))
Person['firstName'] = str(input("Enter First Name: "))
Person['lastName'] = str(input("Enter Last Name: "))
#account detail
Person['Account']['accountNumber'] = int(input("Enter Account number: "))
Person['Account']['accountType'] = int(input("Enter Account type (1) or (2): "))
accountType = Person['Account']['money'] = int(input("Enter initial money: "))
#check account type 2
if(Person['Account']['accountType'] == 2):
Person['Account']['limit'] = int(input("Enter limit: "))
def showPerson():
print("Customer id: %d" %(Person['personID']))
print("Customer First Name: %s" %(Person['firstName']))
print("Customer Last Name: %s" %(Person['lastName']))
print("Account number: %d" %(Person['Account']['accountNumber']))
if(Person['Account']['accountType'] == 1):
print("Account type: (1) Saving account")
else:
print("Account type: (2) Current account")
print("Balance: %d" %(Person['Account']['money']))
if(Person['Account']['accountType'] == 2):
print("Limit: %d" %(Person['Account']['limit']))
def deposite():
money = int(input("Please enter the amount you want to deposit: "))
Person['Account']['money'] = Person['Account']['money'] + money;
def withdraw():
money = int(input("Please enter the amount you wish to withdraw: "))
Person['Account']['money'] = Person['Account']['money'] - money;
def main():
inputPerson()
while(True):
print("----------------------------------------------------")
print(" (1) Deposite (2) Withdraw (3) Exit ")
print("----------------------------------------------------")
choice = int(input())
if(choice == 1):
deposite()
elif(choice == 2):
withdraw()
elif(choice == 3):
showPerson()
break
else:
break
main()
|
for _ in range(int(input())):
a, b, c = map(int, input().split())
if a < b - c:
print("advertise")
elif a == b - c:
print("does not matter")
else:
print("do not advertise")
|
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if year%4==0:
if year%100==0:
if year%400==0:
isleap=True
else:
isleap=False
else:
isleap=True
else:
isleap=False
if isleap:
print("Leap year.")
else:
print("Not leap year.")
|
# define options
CONF_SPEC = {
'optgroup': None,
'urls_conf': None,
'public': False,
'plugins': [],
'widgets': [],
'apps': [],
'middlewares': [],
'context_processors': [],
'dirs': [],
'page_extensions': [],
'auth_backends': [],
'js_files': [],
'js_spec_files': [],
'angular_modules': [],
'css_files': [],
'scss_files': [],
'config': {},
'additional_fields': {},
'migration_modules': {},
'absolute_url_overrides': {},
'navigation_extensions': [],
'page_actions': [],
'widget_actions': [],
'ordering': 0,
'channel_routing': [],
'extra_context': {},
'demo_paths': [],
'requirements': [],
}
# just MAP - Django - Our spec
DJANGO_CONF = {
'INSTALLED_APPS': "apps",
'APPLICATION_CHOICES': "plugins",
'MIDDLEWARE': "middlewares",
'AUTHENTICATION_BACKENDS': "auth_backends",
'PAGE_EXTENSIONS': "page_extensions",
'ADD_PAGE_ACTIONS': "page_actions",
'ADD_WIDGET_ACTIONS': "widget_actions",
'MIGRATION_MODULES': "migration_modules",
'CONSTANCE_ADDITIONAL_FIELDS': "additional_fields",
}
|
a=int(input("enter a levels "))
u=0
lis=[]
i=1
while i<=a:
print("\n")
d=a
if(i==4):
u=0
if(i<=3):
#k=i
lis.append(i)
u=i
else:
u=u+sum(lis)
while d>=i:
print(" ",end="\t")
d=d-1
for j in range(1,i+1):
print(u,end="\t\t")
i=i+1
|
# URL of server application root
BASE_URL = 'https://printer.nsychev.ru/'
# Secret token, same as server one
TOKEN = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
# Path to print executable
PRINT_BIN = 'PDFtoPrinter.exe'
# Printer name
PRINTER = 'Hewlett-Packard HP LaserJet Pro MFP M125ra'
|
expected_output = {
'nodes': {
1: {
'te_router_id': '192.168.0.4',
'host_name': 'rtrD',
'isis_system_id': [
'1921.68ff.1004 level-1',
'1921.68ff.1004 level-2',
'1921.68ff.1004 level-2'],
'asn': [
65001,
65001,
65001],
'domain_id': [
1111,
1111,
9999],
'advertised_prefixes': [
'192.168.0.4',
'192.168.0.4',
'192.168.0.4',
'192.168.0.6']},
2: {
'te_router_id': '192.168.0.1',
'host_name': 'rtrA',
'isis_system_id': ['1921.68ff.1001 level-2'],
'advertised_prefixes': ['192.168.0.1']}}}
|
# @Author: shenmaoyuan
# @Date: 2018-07-30T04:37:01+09:00
# @Email: disovery.yuan@gmail.com
# @Last modified by: shenmaoyuan
# @Last modified time: 2018-08-01T04:23:59+09:00
# @License: Licensed under the Apache License, Version 2.0 (the "License")
# @Copyright: Copyright (c) 2017 XXXXXX, Inc.
class Maze(object):
"""Maze base class.
"""
def __init__(self, size, conn):
self.size = size
self.conn = conn
self.matrix = self._get_maze_matrix()
# if self.matrix == 'Maze format error.':
# return self.matrix
def _get_maze_matrix(self):
matrix = []
for i in range(self.size[0]):
matrix.append([0]*(2*self.size[1] + 1))
row = []
for j in range(self.size[1]):
row.append(0)
row.append(1)
row.append(0)
matrix.append(row)
matrix.append([0]*(2*self.size[1] + 1))
# print(matrix)
for con in self.conn:
vec = (con[1][0]-con[0][0], con[1][1]-con[0][1])
if abs(vec[0]) + abs(vec[1]) != 1:
print(' Maze format error.')
return 'Maze format error.'
"""Check if the connection of maze is correct.
"""
coordinate = (2*con[0][0] + 1 + vec[0], 2*con[0][1] + 1 + vec[1])
# print('vec',vec)
# print('coordinate',coordinate)
matrix[coordinate[0]][coordinate[1]] = 1
return matrix
def render(self):
"""Render the grid
"""
mazeText = ''
for i in range(len(self.matrix)):
for j in range(len(self.matrix[0])):
if self.matrix[i][j]:
mazeText += '[R] '
else:
mazeText += '[W] '
mazeText += '\n'
return mazeText
|
# Copyright 2010 OpenStack Foundation
# 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.
"""Possible vm states for instances.
Compute instance vm states represent the state of an instance as it pertains to
a user or administrator.
vm_state describes a VM's current stable (not transition) state. That is, if
there is no ongoing compute API calls (running tasks), vm_state should reflect
what the customer expect the VM to be. When combined with task states
(task_states.py), a better picture can be formed regarding the instance's
health and progress.
See http://wiki.openstack.org/VMState
"""
ACTIVE = 'active' # VM is running
BUILDING = 'building' # VM only exists in DB
PAUSED = 'paused'
SUSPENDED = 'suspended' # VM is suspended to disk.
STOPPED = 'stopped' # VM is powered off, the disk image is still there.
RESCUED = 'rescued' # A rescue image is running with the original VM image
# attached.
RESIZED = 'resized' # a VM with the new size is active. The user is expected
# to manually confirm or revert.
SOFT_DELETED = 'soft-delete' # VM is marked as deleted but the disk images are
# still available to restore.
DELETED = 'deleted' # VM is permanently deleted.
ERROR = 'error'
SHELVED = 'shelved' # VM is powered off, resources still on hypervisor
SHELVED_OFFLOADED = 'shelved_offloaded' # VM and associated resources are
# not on hypervisor
ALLOW_SOFT_REBOOT = [ACTIVE] # states we can soft reboot from
ALLOW_HARD_REBOOT = ALLOW_SOFT_REBOOT + [STOPPED, PAUSED, SUSPENDED, ERROR]
# states we allow hard reboot from
ALLOW_TRIGGER_CRASH_DUMP = [ACTIVE, PAUSED, RESCUED, RESIZED, ERROR]
# states we allow to trigger crash dump
ALLOW_RESOURCE_REMOVAL = [DELETED, SHELVED_OFFLOADED]
# states we allow resources to be freed in
|
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-11-15 11:14
# @Author : Fabrice LI
# @File : 20191115_binary_search.py
# @User : liyihao
# @Software : PyCharm
# @Description: default module binary search
#Reference:**********************************************
class Solution():
def binary_search_default(self, nums, target):
if len(nums) <= 0:
return -1
left = 0
right = len(nums) - 1
while left + 1 < right:
mid = int(left + (right - left) / 2)
if nums[mid] == target:
right = mid
elif nums[mid] < target:
left = mid
elif nums[mid] > target:
right = mid
if nums[right] == target:
return right
if nums[left] == target:
return left
return -1
def binary_search_left_edge(self, nums, target):
if len(nums) <= 0:
return -1
left = 0
# 重点
right = len(nums) - 1
# 重点
while left + 1 < right:
mid = int(left + (right - left) / 2)
if nums[mid] == target:
right = mid
elif nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid
if nums[left] == target:
return left
if nums[right] == target:
return right
return -1
def binary_search_right_edge(self, nums, target):
if len(nums) <= 0:
return -1
left = 0
right = len(nums) - 1
while left + 1 < right:
mid = int(left + (right - left) / 2)
if nums[mid] == target:
left = mid
elif nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid
if nums[right] == target:
return right
if nums[left] == target:
return left
return -1
if __name__ == '__main__':
s = Solution()
nums = [1, 2]
target = 2
print("left edge: " + str(s.binary_search_left_edge(nums, target)))
print("right edge: " + str(s.binary_search_right_edge(nums, target)))
|
# coding: utf-8
pedido, quant = input().split(" ")
pedido, quant = int(pedido), float(quant)
valor = 0
if pedido == 1:
valor = 4.0
elif pedido == 2:
valor = 4.5
elif pedido == 3:
valor = 5.0
elif pedido == 4:
valor = 2.0
elif pedido == 5:
valor = 1.5
print('Total: R$ {:.2f}'.format(valor * quant))
|
class SimpleList:
def __init__(self, items):
self._items = list(items)
def add(self, item):
self._items.append(item)
def __getitem__(self, index):
return self._items[index]
def sort(self):
self._items.sort()
def __len__(self):
return len(self._items)
def __repr__(self):
return "SimpleList({!r})".format(self._items)
class SortedList(SimpleList):
def __init__(self, items=()):
super().__init__(items)
self.sort()
def add(self, item):
super().add(item)
self.sort()
def __repr__(self):
return "SortedList({!r})".format(list(self))
class IntList(SimpleList):
def __init__(self, items=()):
print('in intlist')
for x in items: self._validate(x)
super().__init__(items)
@staticmethod
def _validate(x):
if not isinstance(x, int):
raise TypeError('IntList only supports integer values.')
def add(self, item):
self._validate(item)
super().add(item)
def __repr__(self):
return "IntList({!r})".format(list(self))
class SortedIntList(IntList, SortedList):
def __repr__(self):
return 'SortedIntList({!r})'.format(list(self))
|
class Solution:
"""
The Brute Force Solution
Time Complexity: O(N^3)
Space Complexity: O(1)
"""
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
triplet_count = 0
# for each i, for each j, check if the first condition is satisfied
for i in range(len(arr) - 2):
for j in range(i + 1, len(arr) - 1):
if abs(arr[i] - arr[j]) <= a:
# for each k, check if the last two conditions are satisfied
for k in range(j + 1, len(arr)):
if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
# the triplet is Good, increment the count!
triplet_count += 1
return triplet_count
|
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Parse(Error):
""" Error parsing the program"""
pass
class Output(Error):
""" Error parsing the program"""
pass
class Symbol(Error):
""" Error parsing the program"""
pass
|
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("@bazel_skylib//lib:paths.bzl", "paths")
daml_provider = provider(doc = "DAML provider", fields = {
"dalf": "The DAML-LF file.",
"dar": "The packaged archive.",
"srcjar": "The generated Scala sources as srcjar.",
})
def _daml_impl_compile_dalf(ctx):
# Call damlc compile
compile_args = ctx.actions.args()
compile_args.add("compile")
compile_args.add(ctx.file.main_src)
compile_args.add("--output", ctx.outputs.dalf.path)
if ctx.attr.target:
compile_args.add("--target", ctx.attr.target)
ctx.actions.run(
inputs = depset([ctx.file.main_src] + ctx.files.srcs),
outputs = [ctx.outputs.dalf],
arguments = [compile_args],
progress_message = "Compiling DAML into DAML-LF archive %s" % ctx.outputs.dalf.short_path,
executable = ctx.executable.damlc,
)
def _daml_impl_package_dar(ctx):
# Call damlc package
package_args = ctx.actions.args()
package_args.add("package")
package_args.add(ctx.file.main_src)
package_args.add(ctx.attr.name)
if ctx.attr.target:
package_args.add("--target", ctx.attr.target)
package_args.add("--output")
package_args.add(ctx.outputs.dar.path)
ctx.actions.run(
inputs = [ctx.file.main_src] + ctx.files.srcs,
outputs = [ctx.outputs.dar],
arguments = [package_args],
progress_message = "Creating DAR package %s" % ctx.outputs.dar.basename,
executable = ctx.executable.damlc,
)
def _daml_outputs_impl(name):
patterns = {
"dalf": "{name}.dalf",
"dar": "{name}.dar",
"srcjar": "{name}.srcjar",
}
return {
k: v.format(name = name)
for (k, v) in patterns.items()
}
def _daml_compile_impl(ctx):
_daml_impl_compile_dalf(ctx)
_daml_impl_package_dar(ctx)
# DAML provider
daml = daml_provider(
dalf = ctx.outputs.dalf,
dar = ctx.outputs.dar,
)
return [daml]
def _daml_compile_outputs_impl(name):
patterns = {
"dalf": "{name}.dalf",
"dar": "{name}.dar",
}
return {
k: v.format(name = name)
for (k, v) in patterns.items()
}
# TODO(JM): The daml_compile() is same as daml(), but without the codegen bits.
# All of this needs a cleanup once we understand the needs for daml related rules.
daml_compile = rule(
implementation = _daml_compile_impl,
attrs = {
"main_src": attr.label(
allow_single_file = [".daml"],
mandatory = True,
doc = "The main DAML file that will be passed to the compiler.",
),
"srcs": attr.label_list(
allow_files = [".daml"],
default = [],
doc = "Other DAML files that compilation depends on.",
),
"target": attr.string(doc = "DAML-LF version to output"),
"damlc": attr.label(
executable = True,
cfg = "host",
allow_files = True,
default = Label("//compiler/damlc"),
),
},
executable = False,
outputs = _daml_compile_outputs_impl,
)
def _daml_test_impl(ctx):
script = """
set -eou pipefail
DAMLC=$(rlocation $TEST_WORKSPACE/{damlc})
rlocations () {{ for i in $@; do echo $(rlocation $TEST_WORKSPACE/$i); done; }}
$DAMLC test --files $(rlocations "{files}")
""".format(
damlc = ctx.executable.damlc.short_path,
files = " ".join([f.short_path for f in ctx.files.srcs]),
)
ctx.actions.write(
output = ctx.outputs.executable,
content = script,
)
damlc_runfiles = ctx.attr.damlc[DefaultInfo].data_runfiles
runfiles = ctx.runfiles(
collect_data = True,
files = ctx.files.srcs,
).merge(damlc_runfiles)
return [DefaultInfo(runfiles = runfiles)]
daml_test = rule(
implementation = _daml_test_impl,
attrs = {
"srcs": attr.label_list(
allow_files = [".daml"],
default = [],
doc = "DAML source files to test.",
),
"damlc": attr.label(
executable = True,
cfg = "host",
allow_files = True,
default = Label("//compiler/damlc"),
),
},
test = True,
)
_daml_binary_script_template = """
#!/usr/bin/env sh
{java} -jar {sandbox} $@ {dar}
"""
def _daml_binary_impl(ctx):
script = _daml_binary_script_template.format(
java = ctx.executable._java.short_path,
sandbox = ctx.file._sandbox.short_path,
dar = ctx.file.dar.short_path,
)
ctx.actions.write(
output = ctx.outputs.executable,
content = script,
)
runfiles = ctx.runfiles(
files = [ctx.file.dar, ctx.file._sandbox, ctx.executable._java],
)
return [DefaultInfo(runfiles = runfiles)]
daml_binary = rule(
implementation = _daml_binary_impl,
attrs = {
"dar": attr.label(
allow_single_file = [".dar"],
mandatory = True,
doc = "The DAR to execute in the sandbox.",
),
"_sandbox": attr.label(
cfg = "target",
allow_single_file = [".jar"],
default = Label("//ledger/sandbox:sandbox-binary_deploy.jar"),
),
"_java": attr.label(
executable = True,
cfg = "target",
allow_files = True,
default = Label("@bazel_tools//tools/jdk:java"),
),
},
executable = True,
)
"""
Executable target that runs the DAML sandbox on the given DAR package.
Example:
```
daml_binary(
name = "example-exec",
dar = ":dar-out/com/digitalasset/sample/example/0.1/example-0.1.dar",
)
```
This target can be executed as follows:
```
$ bazel run //:example-exec
```
Command-line arguments can be passed to the sandbox as follows:
```
$ bazel run //:example-exec -- --help
```
"""
def _daml_compile_dalf_output_impl(name):
return {"dalf": name + ".dalf"}
dalf_compile = rule(
implementation = _daml_impl_compile_dalf,
attrs = {
"main_src": attr.label(
allow_single_file = [".daml"],
mandatory = True,
doc = "The main DAML file that will be passed to the compiler.",
),
"srcs": attr.label_list(
allow_files = [".daml"],
default = [],
doc = "Other DAML files that compilation depends on.",
),
"target": attr.string(doc = "DAML-LF version to output"),
"damlc": attr.label(
executable = True,
cfg = "host",
allow_files = True,
default = Label("//compiler/damlc"),
),
},
executable = False,
outputs = _daml_compile_dalf_output_impl,
)
"""
Stripped down version of daml_compile that does not package DALFs into DARs
"""
daml_sandbox_version = "6.0.0"
|
class ClientEvent(object):
AUTH = 1
MODEL_PARAM = 2
EVAL_PARAM = 3
DURATION_PARAM = 4
EXPERIMENT_START = 5
EXPERIMENT_END = 6
CODE_FILE = 7
COMPLETED = 10
GET_EXPERIMENT_METRIC_FILTER = 8
GET_EXPERIMENT_METRIC_DATA = 9
GET_EXPERIMENT_DURATION_FILTER = 11
GET_EXPERIMENT_DURATION_DATA = 12
HEART_BEAT = 13
DATASET_ID = 14
class ExperimentStatus(object):
IN_PROCESS = 1
COMPLETED = 2
|
input = """
num(2).
node(a).
p(N) :- num(N), #count{Y:node(Y)} = N1, <=(N,N1).
"""
output = """
{node(a), num(2)}
"""
|
class DNS:
def start(self):
raise NotImplemented()
def stop(self):
raise NotImplemented()
def restart(self):
raise NotImplemented()
def cleanCache(self):
raise NotImplemented()
def addRecord(self):
raise NotImplemented()
def deleteHost(self, host):
raise NotImplemented()
def updateHostIp(self, host, ip):
raise NotImplemented()
def zones(self):
raise NotImplemented()
def map(self):
raise NotImplemented()
def reversemap(self):
raise NotImplemented()
|
# Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel, and University of Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
# physical constants
GRAVITATION_CONSTANT = 9.81 # earth acceleration constant in m/s²
NORMAL_TEMPERATURE = 273.15 # normal temperature (= 0°C) in K
NORMAL_PRESSURE = 1.01325 # pressure under normal conditions (at sea level) in bar
MOLAR_MASS_AIR = 0.02896 # molar mass of air in m³/mol
R_UNIVERSAL = 8.314 # universal gas constant (molar) in J/(mol * K)
# specific constants
HEIGHT_EXPONENT = 5.255 # exponent for height correction (typical value of international equation)
TEMP_GRADIENT_KPM = 0.0065 # temperature gradient for moist air in K / m
AVG_TEMPERATURE_K = 288.15 # average global temperature at sea level
# calculation constants
P_CONVERSION = 1e5 # factor for conversion between Pa and bar --> relation between v and p
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.