content
stringlengths 7
1.05M
|
---|
'''
Given a sorted array of unknown length and a number to search for, return the index of the number in the array. Accessing an element out of bounds throws exception. If the number occurs multiple times, return the index of any occurrence. If it isn’t present, return -1.
int a[] = {1,2,3,4,5,6,7,8};
Find Value: 6
Return: 5 (index number of value 6)
Time Complexity: O(logn)
Space Complexity: O(1)
public static int findNumberInSortedArrayWithoutArrayLength(int arr[], int findNo) {
if(arr == null) return -1;
int startIdx = 0, endIdx = 1, midIdx = 0;
do {
midIdx = (startIdx + endIdx )/2;
try {
if(arr[midIdx] == findNo)
return midIdx;
}catch(ArrayIndexOutOfBoundsException e) {
endIdx = midIdx-1;
continue;
}
if(arr[midIdx] < findNo) {
startIdx = midIdx + 1;
try {
if(arr[endIdx]>findNo)
endIdx --;
else
endIdx *= 2;
}catch(ArrayIndexOutOfBoundsException e) {
endIdx --;
}
}else {
endIdx = midIdx - 1;
}
}while(startIdx<=endIdx);
return -1;
}
'''
# Time: O(logn)
# Space: O(1)
class Solution(object):
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
left, right = 0, 19999
while left <= right:
mid = left + (right-left)//2
response = reader.get(mid)
if response > target:
right = mid-1
elif response < target:
left = mid+1
else:
return mid
return -1
|
"""6.1.3 Circular Definition of Product ID
For each new defined Product ID (type /$defs/product_id_t) in items of relationships (/product_tree/relationships)
it must be tested that the product_id does not end up in a cirle.
The relevant path for this test is:
/product_tree/relationships[]/full_product_name/product_id
As this can be quite complex a program for large CSAF documents, a program could check first whether a Product ID
defined in a relationship item is used as product_reference or relates_to_product_reference.
Only for those which fulfill this condition it is necessary to run the full check following the references.
Example 42 which fails the test:
"product_tree": {
"full_product_names": [
{
"product_id": "CSAFPID-9080700",
"name": "Product A"
}
],
"relationships": [
{
"category": "installed_on",
"full_product_name": {
"name": "Product B",
"product_id": "CSAFPID-9080701"
},
"product_reference": "CSAFPID-9080700",
"relates_to_product_reference": "CSAFPID-9080701"
}
]
}
CSAFPID-9080701 refers to itself - this is a circular definition.
"""
ID = (6, 1, 3)
TOPIC = 'Circular Definition of Product ID'
PATHS = ('/product_tree/relationships[]/full_product_name/product_id',)
|
# # WAP to accept a number and display all the factors which are prime ( prime factors)
user_Inp = int(input("Enter number: "))
for i in range(1, user_Inp+1):
c = 0
if(user_Inp % i == 0):
for j in range(1, i+1):
if(i % j == 0):
c += 1
if(c <= 2):
print(i, end=' ')
|
N, K = list(map(int, input().split(' ')))
cnt = 0
while True:
if N == 1:
break;
if N % K == 0:
N /= K
else:
N -= 1
cnt += 1
print(cnt) |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 13:29:53 2018
@author: jel2
"""
def xval(x,y,g,mdl,params):
M=pd.DataFrame(g).join(y,how='outer').join(x,how='outer')
# Y=np.array(M[list(y)])
#### if Y is two columns with one binary column then treat it as survival data
# if(len(Y.shape)>1):
# surv=True
# ix=np.where(np.apply_along_axis(lambda z: len(set(z)),0,Y)==2)[0].item(0)
# tx=({0,1}-{ix}).pop()
# ix=Y[:,ix]
# tm=Y[:,tx]
# else:
# surv=False
# G=np.array(M[list(g)]).transpose()[0]
# X=np.array(M[list(x)])
M['xVal']=0
for i in set(M.grp):
ll= M.grp==i
mod=lsReg(M.loc[~ll,:].drop(['grp','xVal'],axis=1),params)
M.loc[ll,'xVal']=mod.predict_expectation(M.loc[ll,:].drop(['grp','xVal'],axis=1)).iloc[:,0]
return(M) |
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
st = []
res = []
while head:
while st and st[-1][1] < head.val:
idx, v = st.pop()
res[idx] = head.val
st.append((len(res), head.val))
res.append(0)
head = head.next
return res
|
def find_matches(match_info, results):
for target_match_info, obj in results:
if target_match_info.equals(match_info):
yield target_match_info, obj
|
#!/usr/bin/env python3
# coding: utf-8
# PSMN: $Id: 01.py 1.2 $
# SPDX-License-Identifier: CECILL-B OR BSD-2-Clause
""" https://github.com/OpenClassrooms-Student-Center/demarrez_votre_projet_avec_python/
fouiller dans les branches
"""
# P2C2
quotes = [
"Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !",
"On doit pouvoir choisir entre s'écouter parler et se faire entendre."
]
characters = [
"alvin et les Chipmunks",
"Babar",
"betty boop",
"calimero",
"casper",
"le chat potté",
"Kirikou"
]
|
def test():
print('testing basic math ops')
assert 1+1 == 2
assert 10-1 == 9
assert 10 / 2 == 5
assert int(100.9) == 100
print('testing bitwise ops')
print(100 ^ 0xd008)
assert 100 ^ 0xd008 == 53356
print( 100 & 199 )
assert (100 & 199) == 68
## TODO fixme
print('TODO fix `100 & 199 == 68`')
assert 100 & 199 == 68
test()
|
phrase = 'Coding For All'
phrase = phrase.split()
abrv = phrase[0][0] + phrase[1][0] + phrase[2][0]
print(abrv)
|
def increment(a):
return a+1
def decrement(a):
return a-1
|
# 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
# todo 上生产前需要修改
source_root = r'D:\Jupyter\tt_spider'
local_host = 'localhost'
local_port = 3306
local_user = 'root'
local_passwd = 'password'
db_host = 'hostname'
db_port = 3306
db_user = 'username'
db_passwd = 'password'
|
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
"""Molecule to atoms."""
def get_sub_molecule(molecule: list, atom: str) -> list:
molecule_copy = molecule[molecule.index(atom) + 1:]
sub_molecule = []
count_parent = 1
for el in molecule_copy:
if el in "([{":
count_parent += 1
elif el in ")]}":
count_parent -= 1
if count_parent == 0:
molecule.remove(el)
break
sub_molecule.append(el)
molecule.remove(el)
return sub_molecule
def parse_molecule(molecule):
molecule = [i for i in molecule]
element = ""
array_of_elements = []
atoms = {}
for atom in molecule:
if atom.isupper():
if element != "":
array_of_elements.append(element)
atoms[atom] = 0
atoms[atom] += 1
if molecule.index(atom) == len(molecule) - 1:
array_of_elements.append(atom)
else:
element = atom
elif atom.islower():
element += atom
elif atom.isdigit():
for i in range(int(atom)):
if isinstance(element, str):
array_of_elements.append(element)
elif isinstance(element, list):
array_of_elements.extend(element)
element = ""
if atom in "([{":
if element != "":
array_of_elements.append(element)
sub_molecule = get_sub_molecule(molecule, atom)
element = parse_molecule(sub_molecule)
return array_of_elements
if __name__ == "__main__":
molecule = "K4[ON(SO3)2]2"
amount_of_atoms = {}
array_of_elements = parse_molecule(molecule)
for atom in array_of_elements:
amount = array_of_elements.count(atom)
amount_of_atoms[atom] = amount
print(amount_of_atoms)
|
# Python 实现冒泡排序
def bubbleSort(alist):
for passnum in range(len(alist)-1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
return alist
alist = [54,26,93,17,77,31,44,55,20]
print(bubbleSort(alist))
# 改进的冒泡排序, 加入一个校验, 如果某次循环发现没有发生数值交换, 直接跳出循环
def modiBubbleSort(alist):
exchange = True
passnum = len(alist) - 1
while passnum >= 1 and exchange:
exchange = False
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
exchange = True
passnum -= 1
return alist
print(bubbleSort(alist)) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
# Do preorder traversal
count = self.preOrder(root, sum, {0: 1}, 0)
return count
def preOrder(self, root, sum, hash_map, pre_sum):
# First check if we are at an actual node
if not root:
# Return 0 so we don't affect the count
return 0
# Add current node's value to running sum
pre_sum += root.val
# Initialize count from history of running sum subtracted by the target sum
# If it doesn't exist in the dictionary, then initialize to 0
count = hash_map.setdefault(pre_sum - sum, 0)
# Increment visit count of running sum in dictionary
# Add running sum to dictionary if not already there
hash_map[pre_sum] = hash_map.setdefault(pre_sum, 0) + 1
# Go down the left subtree and increment the count of any solutions below
count += self.preOrder(root.left, sum, hash_map, pre_sum)
# Go down the right subtree and increment the count of any solutions below
count += self.preOrder(root.right, sum, hash_map, pre_sum)
# We're ready to go back up, so remove a visit count of the running sum from the dictionary
hash_map[pre_sum] -= 1
return count
|
class Referee:
def __init__(self, json_referee_info: dict) -> None:
self.id = json_referee_info.get("id")
self.bonuses = json_referee_info.get("bonuses")
self.bonuses_total = json_referee_info.get("bonuses_total")
self.email = json_referee_info.get("email")
class Referrals:
def __init__(self, json_referees_info) -> None:
self.referrals = []
self.referral_earnings = 0
self.total_referral_earnings = 0
for referee in json_referees_info:
self.referrals.append(Referee(referee))
self.number_of_referrals = len(self.referrals)
for referee in self.referrals:
self.referral_earnings += referee.bonuses
self.total_referral_earnings += referee.bonuses_total
|
def find_the_max_sum_of_subarray(arr, K):
# Input: [2, 1, 5, 1, 3, 2], k=3
# Output: 9
start_index = 0
sum_index = 0
target_sum = 0
for index, value in enumerate(arr):
sum_index += value
if index >= K-1:
if sum_index > target_sum:
target_sum = sum_index
sum_index -= arr[start_index]
start_index +=1
return target_sum
v = find_the_max_sum_of_subarray([2, 1, 20, 1, 3, 2], 3)
print(v) |
def addDynamic():
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/addDynamic.html
-----------------------------------------
addDynamic is undoable, NOT queryable, and NOT editable.
Makes the "object" specified as second argument the source of an existing
field or emitter specified as the first argument. In practical terms, what
this means is that a field will emanate its force from its owner object, and
an emitter will emit from its owner object.
addDynamic makes the specified field or emitter a child of the owner's
transform (adding it to the model if it was not already there), and makes the
necessary attribute connections.
If either of the arguments is omitted, addDynamic searches the selection list
for objects to use instead. If more than one possible owner or field/emitter
is selected, addDynamic will do nothing.
If the specified field/emitter already has a source, addDynamic will remove
the current source and replace it with the newly specified source.
If a subset of the owner object's cvs/particles/vertices is selected,
addDynamic will add the field/emitter to that subset only.
-----------------------------------------
Return Value:
string The name of the source object and the field or emitter which was
attached to it.
"""
def addPP(atr="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/addPP.html
-----------------------------------------
addPP is undoable, NOT queryable, and NOT editable.
Adds per-point (per-cv, per-vertex, or per-particle) attribute capability for
an attribute of an emitter or field. The -atr flag identifies the attribute.
If no attribute is named, addPP returns a warning and does nothing.
The command adds any other necessary attributes wherever they are needed, and
makes all necessary connections. If any of the attributes already exist, the
command simply connects to them. The command also toggles any relevant
attributes in the emitter or field to indicate that per-point capability is
being used.
The command adds a separate per-point attribute to the owning object for each
emitter/field. For example, for emission rate, there is a separate ratePP for
each emitter. These attributes are named according to the convention
<emitter/field name><attr name>PP. For example, if a particle shape owned an
emitter "smoke", that shape would get attribute "smokeRatePP."
The name of the object must be the emitter or field for which per-point
capability is to be added (or the name of its parent transform). The addPP
command adds the per-point capability for that emitter or field but not for
any others owned by the same object. If per-point capability is not supported
for a named object, the command will trigger a warning, but will continue
executing for any other objects which were valid.
If no objects are named, addPP uses any objects in the current selection list
for which the specified attribute is applicable. (For example, it would add
per-point rate for all selected emitters.)
If addPP detects that the owner object has left-over attributes from a deleted
emitter, it will remove those attributes before adding the new ones. Thus, you
can delete the emitter, make a new one, and run addPP again, and addPP will
clean up after the deleted emitter. This is most commonly used if you have a
geometry emitter and then decide to change the geometry. Likewise, if addPP
detects that some cvs or vertices have been added to the geometry, then it
will expand the corresponding multi-attributes as necessary. However, if it
detects that some cvs/vertices have been removed, it will not remove any
entries from the multi. See the user manual for more discussion.
-----------------------------------------
Return Value:
string[] Returns names of emitters/fields for which the per-point capability
was added for the specified attribute.
-----------------------------------------
Flags:
-----------------------------------------
atr : attribute [string]
Name of attribute to which you wish to add PP capability. Currently the only attribute supported is rate (for emitters).
"""
def air(q=1,e=1,att="float",dx="float",dy="float",dz="float",es=1,fs=1,iro=1,iv="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",s="float",sp="float",tsr="linear",vco=1,vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle",wks=1,wns=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/air.html
-----------------------------------------
air is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. The air field simulates the effects
of moving air. The affected objects will be accelerated or decelerated so that
their velocities match that of the air.
With the '-vco true' flag thrown, only accelerations are applied. By parenting
an air field to a moving part of an object (ie. a foot of a character) and
using '-i 1 -m 0 -s .5 -vco true' flags, one can simulate the movement of air
around the foot as it moves, since the TOTAL velocity vector of the field
would be only based on the movement of the foot. This can be done while the
character walks through leaves or dust on the ground.
For each listed object, the command creates a new field. The transform is the
associated dependency node. Use connectDynamic to cause the field to affect a
dynamic object.
If fields are created, this command returns the field names. If a field was
queried, the results of the query are returned. If a field was edited, the
field name is returned.
If the -pos flag is specified, a field is created at the position specified.
If not, if object names are provided or the active selection list is non-
empty, the command creates a field for every object in the list and calls
addDynamic to add it to the object; otherwise the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
dx : directionX [float] ['query', 'edit']
-----------------------------------------
dy : directionY [float] ['query', 'edit']
-----------------------------------------
dz : directionZ [float] ['query', 'edit']
Direction that the air will try to match the affected particles' velocity to. NOTE: This is not the velocity; this is only the direction. Use the -s flag to set the speed.
-----------------------------------------
es : enableSpread [boolean] ['query', 'edit']
This tells the system whether or not to use the spread angle given by '-sp'. If this is 'false' then all connected objectswithin the maximum distance will be affected. Also, if this is set to 'false', all affected objects are forced to match their velocities along the direction vector. If this is set to 'true' and spread is used, then the direction of the force is along the direction from the field to the object.
-----------------------------------------
fs : fanSetup [boolean] ['edit']
Similar to 'windSetup' except that the effects of a fan or a person blowing air are approximated. The user can pass the same flags on the command line to adjust them from the defaults. These are the values that get set to approximate a 'fan': inheritVelocity 1.0 inheritRotation true componentOnly false enableSpread true spread .5 (45 degrees from center )
-----------------------------------------
iro : inheritRotation [boolean] ['query', 'edit']
If this is set to 'true', then the direction vector described with -dx, -dy, and -dz will be considered local to the owning object. Therefore, if the owning object's transform undergoes any rotation (by itself or one of its parents), the direction vector of the air field will undergo that same rotation.
-----------------------------------------
iv : inheritVelocity [float] ['query', 'edit']
Amount (from 0 to 1) of the field-owner's velocity added to the vector determined by the direction and speed flags. The combination of these two vectors makes up the TOTAL velocity vector for the air field. This allows the air to be determined directly by the motion of the owning object.
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
s : speed [float] ['query', 'edit']
How fast the affected objects' speed reaches the speed (based on the -mag, -dx, -dy, -dz flags) of the air field. This value gets clamped internally to be between 0.0 and 1.0. A value of 0.0 will make the air field have no effect. A value of 1.0 will try to match the air field's speed much quicker, but not necessarily immediately.
-----------------------------------------
sp : spread [float] ['query', 'edit']
This represents the angle from the direction vector within which objects will be affected. The values are in the range of 0 to 1. A value of 0 will result in an effect only exactly in front of the air field along the direction vector. A value of 1 will result in any object in front of the owning object, 90 degrees in all direction from the direction vector.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vco : velocityComponentOnly [boolean] ['query', 'edit']
If this is 'false', the air will accelerate or decelerate the affected objects so that their velocities will eventually match the TOTAL velocity vector of the air field. If this is 'true', only ACCELERTION is applied to the affected objects so that their velocity component along the TOTAL velocity vector matches or is greater in magnitude than the TOTAL velocity vector. This will not slow objects down to match velocities, only speed them up to match components. This is most useful when using the -iv flag with a value >0\.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle] ['query', 'edit']
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
-----------------------------------------
wks : wakeSetup [boolean] ['edit']
Like the 'windSetup' and 'fanSetup', 'wakeSetup' sets certain values in the field to approximate the movement of air near a moving object, such as a character's foot or hand. The values that are set are: inheritVelocity 1.0 inheritRotation false componentOnly true enableSpread false speed 0.0
-----------------------------------------
wns : windSetup [boolean]
This will set some of the values above in a way that approximates the effects of a basic wind. This allows the user to then change certain values as he/she wishes on the same command line. First the preset values get set, and then any other flags that were passed get taken into account. These are the values that get set to approximate 'wind': inheritVelocity 0.0 inheritRotation true componentOnly false enableSpread false
"""
def arrayMapper(da="string",iu="string",iv="string",mt="string",t="string",ty="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/arrayMapper.html
-----------------------------------------
arrayMapper is undoable, NOT queryable, and NOT editable.
Create an arrayMapper node and connect it to a target object. If the -type
flag is used, then this command also creates an external node used for
computing the output values. If the input attribute does not already exist, it
will be created. The output attribute must exists. If a flag is omitted, the
selection list will be used to supply the needed objects. If none are found,
that action is omitted.
-----------------------------------------
Return Value:
string[] Names of created arrayMapper nodes.
-----------------------------------------
Flags:
-----------------------------------------
da : destAttr [string] []
Specifies the attribute which will be the downstream connection for the output data from the mapper node. The attribute type will be used to determine which output attribute to use: float array gets outValuePP, vector array gets outColorPP. If the flag is omitted, no output connection is made.
-----------------------------------------
iu : inputU [string] []
Specifies the upstream attribute to connect to the mapper's uCoordPP attribute. If the flag is omitted, no input connection is made.
-----------------------------------------
iv : inputV [string] []
Specifies the upstream attribute to connect to the mapper's vCoordPP attribute. If the flag is omitted, no input connection is made.
-----------------------------------------
mt : mapTo [string] []
Specifies an existing node to be used to compute the output values. This node must be of the appropriate type. Currently, only ramp nodes may be used.
-----------------------------------------
t : target [string] []
Specifies the target object to be connected to.
-----------------------------------------
ty : type [string]
Specifies the node type to create which will be used to compute the output values. Currently, only ramp is valid. If the flag is omitted, no connection is made and the external node is not created.
"""
def collision(q=1,e=1,f="float",n="string",o="float",r="float"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/collision.html
-----------------------------------------
collision is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. The collision command causes
particles to collide with geometry. It also allows you to specify values for
the surface properties (friction and resilience) of the collision. These
values are stored in the geoConnector node for the geometry object. Unlike
earlier versions of Maya, there is no separate "collision node."
If a soft object is in the selection list, the collision command assumes that
you want to make it a collider. In order to make the soft object collide with
something use, use connectDynamic -c. The collision menu option sorts this out
using the lead object rule and issues the necessary commands. On creation,
this command returns a string array of the geometry names that were setup for
particle collision.
When the command is used to query information, there are several possible
return types. These include:
* If the -resilience or -friction flag is passed on the command line and a single collision geometry is either selected or on the command line, then resilience or friction value for that collision geometry is returned as a single float value.
* If the -resilience or -friction flag is passed on the command line and a single collision geometry and a single particle object are either selected or on the command line, then two results might occur. If the particle object is not set up to collide with the geometry, then an error is displayed stating that. If the objects are set up to collide with each other, then the resilience or friction value that the particle object is using for collisions with the geometry is returned as a single float value. This can be different than the geometry's resilience and friction, because the user may break the connection from the geometry's geoConnector node's resilience or friction to the particle, and set a different value in the particle's collisionResilience, collisionFriction or collisionOffset attribute that is used for that geometry. This allows the user to make each particle respond to the same surface differently.
* If neither flag is pass on the command line and a single geometry and single particle object are either selected or on the command line, then a single integer value of 1 is returned if the objects are set up to collide with each other, and 0 is returned if they are not.
* Lastly, if no flags are passed on the command line and a single particle object is either selected or on the command line, then a string array with the names of all geometries that the particle object will collide against and the multiIndex that the geometries are connected to is returned. The array is formatted as follows:
pPlaneShape1:0 pPlaneShape2:2 nurbsSphereShape1:3
...where the number following the ":" is the multiIndex.
-----------------------------------------
Return Value:
string[] Geometry names that were setup for particle collision.
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
f : friction [float] ['query', 'edit']
Friction of the surface. This is the amount of the colliding particle's velocity parallel to the surface which is removed when the particle collides. A value of 0 will mean that no tangential velocity is lost, while a value of 1 will cause the particle to reflect straight along the normal of the surface.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
o : offset [float] ['query', 'edit']
Offset value for the connector.
-----------------------------------------
r : resilience [float]
Resilience of the surface. This is the amount of the colliding particle's velocity reflected along the normal of the surface. A value of 1 will give perfect reflection, while a value of 0 will have no reflection along the normal of the surface.
"""
def connectDynamic(ash="script",c="string",d=1,em="string",f="string",rsh="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/connectDynamic.html
-----------------------------------------
connectDynamic is undoable, NOT queryable, and NOT editable.
Dynamic connection specifies that the force fields, emitters, or collisions of
an object affect another dynamic object. The dynamic object that is connected
to a field, emitter, or collision object is influenced by those fields,
emitters and collision objects.
Connections are made to individual fields, emitters, collisions. So, if an
object owns several fields, if the user wants some of the fields to affect an
object, s/he can specify each field with a "-f" flag; but if the user wants to
connect all the fields owned by an object, s/he can specify the object name
with the "-f" flag. The same is true for emitters and collisions. Different
connection types (i.e., for fields vs. emitters) between the same pair of
objects are logically independent. In other words, an object can be influenced
by another object's fields without being influenced by its emitters or
collisions.
Each connected object must be a dynamic object. The object connected to can be
any object that owns fields, emitters, etc.; it need not be dynamic. Objects
that can own influences are particles, geometry objects (nurbs and polys) and
lattices. You can specify either the shape name or the transform name of the
object to be influenced.
-----------------------------------------
Return Value:
string Command result
-----------------------------------------
Flags:
-----------------------------------------
ash : addScriptHandler [script] []
Registers a script that will be given a chance to handle calls to the dynamicConnect command. This flag allows other dynamics systems to override the behaviour of the connectDynamic command. You must pass a Python function as the argument for this flag, and that function must take the following keyword arguments: fields, emitters, collisionObjects and objects. The python function must return True if it has handled the call to connectDynamic. In the case that the script returns true, the connectDynamic command will not do anything as it assumes that the work was handled by the script. If all of the callbacks return false, the connectDynamic command will proceed as normal. The addScriptHandler flag may not be used with any other flags. When the flag is used, the command will return a numerical id that can be used to deregister the callback later (see the removeScriptHandler flag)
-----------------------------------------
c : collisions [string] []
Connects each object to the collision models of the given object.
-----------------------------------------
d : delete [boolean] []
Deletes existing connections.
-----------------------------------------
em : emitters [string] []
Connects each object to the emitters of the given object.
-----------------------------------------
f : fields [string] []
Connects each object to the fields of the given object.
-----------------------------------------
rsh : removeScriptHandler [int]
This flag is used to remove a callback that was previously registered with the addScriptHandler flag. The argument to this flag is the numerical id returned by dynamicConnect when the addScriptHandler flag was used. If this flag is called with an invalid id, then the command will do nothing. This flag may not be used with any other flag.
"""
def constrain(q=1,e=1,br=1,d="float",dhi=1,hi=1,i=1,na=1,n="string",o="[float, float, float]",pin=1,p="[float, float, float]",rl="float",s=1,st="float"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/constrain.html
-----------------------------------------
constrain is undoable, queryable, and editable.
This command constrains rigid bodies to the world or other rigid bodies.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
br : barrier [boolean] ['query']
Creates a barrier constraint. This command requires one rigid bodies.
-----------------------------------------
d : damping [float] ['query', 'edit']
Sets the damping constant. Default value: 0.1 Range: -1000.0 to 1000.0
-----------------------------------------
dhi : directionalHinge [boolean] ['query']
Creates a directional hinge constraint. This command requires two rigid bodies. The directional hinge always maintains the initial direction of its axis.
-----------------------------------------
hi : hinge [boolean] ['query']
Creates a hinge constraint. This command requires one or two rigid bodies.
-----------------------------------------
i : interpenetrate [boolean] ['query', 'edit']
Allows (or disallows) the rigid bodies defined in the constrain to ipenetrate.
-----------------------------------------
na : nail [boolean] ['query']
Creates a nail constraint. This command requires one rigid body.
-----------------------------------------
n : name [string] ['query', 'edit']
Names the rigid constraint.
-----------------------------------------
o : orientation [[float, float, float]] ['query', 'edit']
Set initial orientation of the constraint in world space. This command is only valid with hinge and barrier constraints Default value: 0.0 0.0 0.0
-----------------------------------------
pin : pinConstraint [boolean] ['query']
Creates a pin constraint. This command requires two rigid bodies.
-----------------------------------------
p : position [[float, float, float]] ['query', 'edit']
Set initial position of the constraint in world space. Default value: 0.0 0.0 0.0 for uni-constraints, midpoint of bodies for deul constraint.
-----------------------------------------
rl : restLength [float] ['query', 'edit']
Sets the rest length. Default value: 1.0
-----------------------------------------
s : spring [boolean] ['query']
Creates a spring constraint. This command requires one or two rigidies.
-----------------------------------------
st : stiffness [float]
Sets the springs stiffness constant. Default value: 5.0
"""
def drag(q=1,e=1,att="float",dx="float",dy="float",dz="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",ud=1,vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/drag.html
-----------------------------------------
drag is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. Drag exerts a friction, or braking
force proportional to the speed of a moving object. If direction is not
enabled, the drag acts opposite to the current velocity of the object. If
direction is enabled, it acts opposite to the component of the velocity in the
specified direction. The force is independent of the position of the affected
object.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
dx : directionX [float] ['query', 'edit']
X-component of direction.
-----------------------------------------
dy : directionY [float] ['query', 'edit']
Y-component of direction.
-----------------------------------------
dz : directionZ [float] ['query', 'edit']
Z-component of direction
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
ud : useDirection [boolean] ['query', 'edit']
Enable/disable direction. Drag will use -dx/-dy/-dz arguments if and only if this flag is set true.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def dynCache():
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynCache.html
-----------------------------------------
dynCache is undoable, NOT queryable, and NOT editable.
Cache the current state of all particle shapes at the current time.
-----------------------------------------
Return Value:
None
"""
def dynExport(all=1,atr="string",f="string",mxf="time",mnf="time",oup=1,os="int",p="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynExport.html
-----------------------------------------
dynExport is undoable, NOT queryable, and NOT editable.
Export particle data to disk files.
For cache export (-format cache), dynExport also sets three attributes of the
current dynGlobals node. It sets the useParticleRenderCache attribute to true,
and the min/maxFrameOfLastParticleRenderCache attributes to correspond to the
min and max frames.
Exported .pda or .pdb files are assigned a name of form object
name.frame.extension, where extension is "pda" or "pdb."
The naming convention for .pdc files is similar but does not use frame
numbers, it uses a more precise representation of the time instead.
By default, the pda and pdb formats export all per-particle attributes, and
all integer or float type attributes except those which are hidden or not
storable. (Exception: level of detail is not exported, by default) The pdc
format exports all attributes which the particle object needs for its state
cache.
To specify only selected attributes, use the -atr flag (which is multi-use).
In general, it is recommended not to use this flag with pdc type, since you
need all the attributes in order for the cache to be useful.
dynExport exports data for the current frame, or for a range of frames
specified with -mnf and -mxf. If you are not already at the start frame,
dynExport will run up the scene for you. VERY VERY IMPORTANT NOTE: If you use
dynExport in -prompt mode, it does NOT automatically force evaluation of your
objects. You must do this yourself from your script. The easiest way is to
request each particle object's "count" attribute each frame. You must request
the count attribute for each object you want to export, because their solvers
run independently of one another. In interactive mode, objects WILL get
evaluated automatically and you don't have to worry about any of this.
When exporting a particle object whose particles are created from collisions
involving particles in another particle object(s), you must make sure you
simultaneously export all the particle objects involved in the dependency
chain otherwise you will get an empty cache file.
For non-per-particle attributes, pda and pdb formats write the identical value
once for each particle. The following types of non-per-particle attributes can
be exported: float, double, doubleLinear, doubleAngle, byte, short, long,
enum. The first four are exported as "Real" (in PDB parlance), and the last
four as "Integer."
In the pda and pdb formats, "particleId" and "particleId0" are exported as
Integer, and are exported under the names "id" and "id0" respectively. All
other attributes are exported under their long names.
-----------------------------------------
Return Value:
string Path to the exported files
-----------------------------------------
Flags:
-----------------------------------------
all : allObjects [boolean] []
Ignore the selection list and export all particle objects. If you also specify an object name, the -all flag will be ignored.
-----------------------------------------
atr : attribute [string] []
Name of attribute to be exported. If any specified object does not have one of the specified attributes, dynExport will issue an error and not do the export.
-----------------------------------------
f : format [string] []
Desired format: "binary" ("pdb"), "ascii" ("pda"), or "cache" ("pdc"). The pdc format is for use by the Maya particle system to cache particle data. The pda and pdb format options are intended for pipelines involving other software (for example, sending the data to some program written in-house); Maya cannot read pda or pdb files. There is no formal description of the PDB format, but the ExploreMe/particles/readpdb directory contains the source and Makefile for a small, simple C program called "readpdb" which reads it. Note that you must compile and run readpdb on the platform which you exported the files on.
-----------------------------------------
mxf : maxFrame [time] []
Ending frame to be exported.
-----------------------------------------
mnf : minFrame [time] []
Starting frame to be exported. The export operation will play the scene through from min frame to max frame as it exports.
-----------------------------------------
oup : onlyUpdateParticles [boolean] []
Specify to only update the particles before exporting.
-----------------------------------------
os : overSampling [int] []
OverSampling to be used during export.
-----------------------------------------
p : path [string]
This option allows you to specify a subdirectory of the workspace "particles" directory where you want the exported files to be stored. By default, files are stored in the workspace particles directory, i.e., -path is relative to that directory. ( Please Read This: This is a change from previous versions of Maya in which the path was relative to the workspace root directory.) You can set the "particles" directory anywhere you want using the project window or workspace -fr command. (In this way, you can use an absolute path for export). The -path flag cannot handle strings which include "/" or "\", in other words, it lets you go down only one level in the directory hierarchy. If you specify a path which doesn't exist, the action will create it if possible; if it can't create the path it will warn you and fail. If you are using a project for which a particle data directory is not defined, dynExport will create a default one called "particles" and add it to your workspace.
"""
def dynExpression(q=1,e=1,c=1,n="string",r=1,rad=1,rbd=1,s="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynExpression.html
-----------------------------------------
dynExpression is undoable, queryable, and editable.
This command describes an expression that belongs to the specified particle
shape. The expression is a block of code of unlimited length with a C-like
syntax that can perform conversions, mathematical operations, and logical
decision making on any numeric attribute(s) or per-particle attribute(s) in
the scene. One expression can read and alter any number of these attributes.
Every particle shape in your scene has three expressions, one for the
runtimeBeforeDynamics, one for the runtimeAfterDynamics and one for creation
time. The create expression gets executed for every particle in the object
whose age is 0.0. The runtime expression gets executed for each particle with
an age greater then 0.0. Unlike expressions created with the expression
command, particle expressions always exist and are a part of the owning
particle object's shape. They default to empty strings, but they are always
there. Because of this, there is no need to use the '-e' flag. Every call to
the dynExpression command is considered an edit by default. Per-particle
attributes are those attributes of a particle shape that have a potentially
different value for each particle in the object. Examples of these include
position and velocity.
If this command is being sent by the command line or in a script, then the
user should be sure to embed escaped newlines (\n), tabs (\t) for clarity when
reading them in the expression editor. Also, quotes in an expression must be
escaped (\") so that they are not confused by the system as the end of your
string. When using the expression editor, these characters are escaped for you
unless they are already within quotes.
This type of expression is executed during the evaluation of the dynamics. If
an output of the expression is requested before that, then the dynamics will
be force to compute at that time. If dynamics is disabled, then these
expressions will have no effect.
-----------------------------------------
Return Value:
string The particle shape which this expression belongs to
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
c : creation [boolean] ['query', 'edit']
Tells the command that the string passed will be a creation expression for the particle shape. This means that this expression will be executed when a particle is emitted or at the beginning of the scene for existing particles.
-----------------------------------------
n : name [string] ['query', 'edit']
Name to use for this command
-----------------------------------------
r : runtime [boolean] ['query', 'edit']
Tells the command that the string passed will be a runtime expression for the particle shape. This expression will be executed at the beginning of runtime.
-----------------------------------------
rad : runtimeAfterDynamics [boolean] ['query', 'edit']
Tells the command that the string passed will be a runtime expression for the particle shape. This expression will be executed after dynamics whenever a particle's age is greater then zero (0).
-----------------------------------------
rbd : runtimeBeforeDynamics [boolean] ['query', 'edit']
Tells the command that the string passed will be a runtime expression for the particle shape. This expression will be executed before dynamics whenever a particle's age is greater then zero (0).
-----------------------------------------
s : string [string]
Set the expression string. This is queriable with the -q/query flag and the -rbd/runtimeBeforeDynamics, the -rab/runtimeAfterDynamics or the -c/creation flag.
"""
def dynGlobals(q=1,e=1,a=1,la=1,os="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynGlobals.html
-----------------------------------------
dynGlobals is undoable, queryable, and editable.
This node edits and queries the attributes of the active dynGlobals node in
the scene. There can be only one active node of this type. The active
dynGlobals node is the first one that was created, either with a "createNode"
command or by accessing/editing any of the attributes on the node through this
command.
-----------------------------------------
Return Value:
string For edit commands
int or string For query commands, depending on the flag queried.
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
a : active [boolean] ['query']
This flag returns the name of the active dynGlobals node in the the scene. Only one dynGlobals node is active. It is the first on created. Any additional dynGlobals nodes will be ignored.
-----------------------------------------
la : listAll [boolean] ['query']
This flag will list all of the dynGlobals nodes in the scene.
-----------------------------------------
os : overSampling [int]
This flag will set the current overSampling value for all of the particle in the scene.
"""
def dynPref(q=1,ac=1,ec=1,rf="int",rt=1,sq=1,sr=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynPref.html
-----------------------------------------
dynPref is undoable, queryable, and NOT editable.
This action modifies and queries the current state of "autoCreate rigid
bodies", "run up to current time", and "run up from" (previous time or start
time).
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ac : autoCreate [boolean] ['query']
If on, autoCreate rigid bodies.
-----------------------------------------
ec : echoCollision [boolean] ['query']
If on, will cause particle systems to echo to the Script Editor the command that they are running for each particle collision event. If off, only the output of the command will be echoed.
-----------------------------------------
rf : runupFrom [int] ['query']
If on, run up from previous time; if 2, run up from start time
-----------------------------------------
rt : runupToCurrentTime [boolean] ['query']
If on, run up the scene to current time
-----------------------------------------
sq : saveOnQuit [boolean] ['query']
If on, save the current values of preferences to userPrefs file.
-----------------------------------------
sr : saveRuntimeState [boolean]
If on, runtime state as well as initial state of all particle objects will be saved to file. If off, only initial state will be saved.
"""
def emit(at="string",fv="float",o="string",pos="[float, float, float]",vv="[float, float, float]"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/emit.html
-----------------------------------------
emit is undoable, NOT queryable, and NOT editable.
The emit action allows users to add particles to an existing particle object
without the use of an emitter. At the same time, it allows them to set any
per-particle attribute for the particles that are created with the action.
The particles created do not become a part of the initial state for the
particle object, and will disappear when the scene is rewound unless they are
saved into the initial state by the user explicitly. In addition, a particle
object will accept particles from an emit action ONLY at frames greater than
or equal to its start frame. For example, if you want to use the emit action
to create particles at frame -5, you must set startFrame for that particle
shape to -5 or less.
Unlike many commands or actions, the emit action uses the order of its flags
as important information as to how it works. The -object and -position flags
can appear anywhere in the argument list. The -attribute and the value flags
are interpreted based on their order. Any value flags after an -attribute flag
and before the next -attribute flag will set the values for the attribute
specified by the closest -attribute flag before them in the argument list. See
the Examples section below for more detail on how these flags work.
Currently, no creation expression is executed for the new particles unless
they are created from within a particle expression defined with the
dynExpression command or the Expression Editor. If you want any particular
values put into the particles at the time they are created, then those values
should be set using the -attribute, -vectorValue, and -floatValue flags.
-----------------------------------------
Return Value:
int[] Integer array containing the list of the particleId attribute values
for the created particles in the same order that the position flags were
passed.
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] []
Specifies the attribute on the particle object that any value flags following it and before the next -attribute flag will be associated with. The same attribute can be specified later in the command to pick up where the first one left off. The attributes used must be per-particle attributes. This will accept both long and short names for the attributes. Note the per- particle attribute must already exist on the particle object prior to being specified via this command flag.
-----------------------------------------
fv : floatValue [float] []
Sets the float value to be used for the "current" attribute of the "current" particle. By current attribute, it is meant the attribute specified by the most recent -attribute flag. By current particle, it is meant the particle in the list of -position flags that corresponds to the number of values that have been set for the "current" attribute. If the current attribute is a vector-per-particle attribute, then the float value specified will be used for all three components of the vector.
-----------------------------------------
o : object [string] []
This flag takes the name of a particleShape or the transform directly above it in the DAG as its parent. It specifies which object to add the particles to. This flag must be passed, as the selection list is ignored for this action.
-----------------------------------------
pos : position [[float, float, float]] []
Specifies the positions in the particle object's space (usually world space) where the particles are to be created. One particle is created for each occurence of this flag.
-----------------------------------------
vv : vectorValue [[float, float, float]]
Sets the vector value to be used for the "current" attribute of the "current" particle. By current attribute, it is meant the attribute specified by the most recent -attribute flag. By current particle, it is meant the particle in the list of -position flags that corresponds to the number of values that have been set for the "current" attribute. If the current attribute is a float-per-particle attribute, then the length of the vector described by this flag will be used. The length is described as SQR( xVal2 \+ yVal2 \+ zVal2 ).
"""
def emitter(q=1,e=1,alx="float",arx="float",afx="float",afc="float",cye="string",cyi="int",dx="linear",dy="linear",dz="linear",drs="float",mxd="linear",mnd="linear",n="string",nuv=1,nsp="float",pos="[linear, linear, linear]",rnd="float",r="float",sro=1,ssz=1,spd="float",srn="float",sp="float",tsp="float",tsr="linear",typ="string",vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/emitter.html
-----------------------------------------
emitter is undoable, queryable, and editable.
Creates, edits or queries an auxiliary dynamics object (for example, a field
or emitter). Creates an emitter object. If object names are provided or if
objects are selected, applies the emitter to the named/selected object(s)in
the scene. Particles will then be emitted from each. If no objects are named
or selected, or if the -pos option is specified, creates a positional emitter.
If an emitter was created, the command returns the name of the object owning
the emitter, and the name of emitter shape. If an emitter was queried, the
command returns the results of the query.
Keyframeable attributes of the emitter node: rate, directionX, directionY,
directionZ, minDistance, maxDistance, spread.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
alx : alongAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction along the central axis of the volume. See the diagrams in the documentation. Applies only to volume emitters.
-----------------------------------------
arx : aroundAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction around the central axis of the volume. See the diagrams in the documentation. Applies only to volume emitters.
-----------------------------------------
afx : awayFromAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction away from the central axis of the volume. See the diagrams in the documentation. Used only with the cylinder, cone, and torus volume emitters.
-----------------------------------------
afc : awayFromCenter [float] ['query', 'edit']
Initial velocity multiplier in the direction away from the center point of a cube or sphere volume emitter. Used only with the cube and sphere volume emitters.
-----------------------------------------
cye : cycleEmission [string] ['query', 'edit']
Possible values are "none" and "frame." Cycling emission restarts the random number stream after a specified interval. This can either be a number of frames or a number of emitted particles. In each case the number is specified by the cycleInterval attribute. Setting cycleEmission to "frame" and cycleInterval to 1 will then re-start the random stream every frame. Setting cycleInterval to values greater than 1 can be used to generate cycles for games work.
-----------------------------------------
cyi : cycleInterval [int] ['query', 'edit']
Specifies the number of frames or particles between restarts of the random number stream. See cycleEmission. Has no effect if cycleEmission is set to None.
-----------------------------------------
dx : directionX [linear] ['query', 'edit']
x-component of emission direction. Used for directional emitters, and for volume emitters with directionalSpeed.
-----------------------------------------
dy : directionY [linear] ['query', 'edit']
y-component of emission direction. Used for directional emitters, and for volume emitters with directionalSpeed.
-----------------------------------------
dz : directionZ [linear] ['query', 'edit']
z-component of emission direction. Used for directional emitters, and for volume emitters with directionalSpeed.
-----------------------------------------
drs : directionalSpeed [float] ['query', 'edit']
For volume emitters only, adds a component of speed in the direction specified by the directionX, Y, and Z attributes. Applies only to volume emitters. Does not apply to other types of emitters.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which emission ends.
-----------------------------------------
mnd : minDistance [linear] ['query', 'edit']
Minimum distance at which emission starts.
-----------------------------------------
n : name [string] ['query', 'edit']
Object name
-----------------------------------------
nuv : needParentUV [boolean] ['query', 'edit']
If aNeedParentUV is true, compute parentUV value from each triangle or each line segment, then send out to the target particle object. You also need to add parentU and parentV attributes to the particle object to store these values.
-----------------------------------------
nsp : normalSpeed [float] ['query', 'edit']
Normal speed multiple for point emission. For each emitted particle, multiplies the component of the velocity normal to the surface or curve by this amount. Surface and curve emitters only.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
world-space position
-----------------------------------------
rnd : randomDirection [float] ['query', 'edit']
Magnitude of a random component of the speed from volume emission.
-----------------------------------------
r : rate [float] ['query', 'edit']
Rate at which particles emitted (can be non-integer). For point emission this is rate per point per unit time. For surface emission it is rate per square unit of area per unit time.
-----------------------------------------
sro : scaleRateByObjectSize [boolean] ['query', 'edit']
Applies to curve and surface emitters, only. If true, number of particles is determined by object size (area or length) times rate value. If false, object size is ignored and the rate value is used without modification. The former is the way Maya behaved prior to version 3.0.
-----------------------------------------
ssz : scaleSpeedBySize [boolean] ['query', 'edit']
Indicates whether the scale of a volume emitter affects its velocity.
-----------------------------------------
spd : speed [float] ['query', 'edit']
Speed multiple. Multiplies the velocity of the emitted particles by this amount. Does not apply to volume emitters. For that emitter type, use directionalSpeed.
-----------------------------------------
srn : speedRandom [float] ['query', 'edit']
Identifies a range of random variation for the speed of each generated particle. If set to a non-zero value, speed becomes the mean value of the generated particles, whose speeds vary by a random amount up to plus or minus speedRandom/2. For example, speed 5 and speedRandom 2 will make the speeds vary between 4 and 6.
-----------------------------------------
sp : spread [float] ['query', 'edit']
Random spread (0-1), as a fraction of 90 degrees, along specified direction. Directional emitters only.
-----------------------------------------
tsp : tangentSpeed [float] ['query', 'edit']
Tangent speed multiple for point emission. For each emitted particle, multiplies the component of the velocity tangent to the surface or curve by this amount. Surface and curve emitters only.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
typ : type [string] ['query', 'edit']
Type of emitter. The choices are omni | dir | direction | surf | surface | curve | curv. The default is omni. The full definition of these types are: omnidirectional point emitter, directional point emitter, surface emitter, or curve emitter.
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the emitter. Volume offset translates the emission volume by the specified amount from the actual emitter location. This is in the emitter's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the emitter. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which particles are generated. Values are: "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the emitter. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def event(q=1,e=1,ct="uint",d=1,die=1,em="uint",ls=1,n="string",pr="script",r=1,re="string",s=1,spl="uint",sp="float",t="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/event.html
-----------------------------------------
event is undoable, queryable, and editable.
The event command assigns collision events to a particle object. Collision
events are stored in multi-attributes in the particle shape. The event command
returns the event name.
-----------------------------------------
Return Value:
string for creation; string array for list.
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ct : count [uint] ['query', 'edit']
Collision number (for each particle) to which this event applies. Zero (the default) indicates that it applies to all collisions.
-----------------------------------------
d : delete [boolean] []
Delete the specified event.
-----------------------------------------
die : dieAtCollision [boolean] ['query', 'edit']
Particle dies at the collision specified by "count." If no count value is given, die at first collision.
-----------------------------------------
em : emit [uint] ['query', 'edit']
Emit n additional particles into the assigned target object. The original (colliding) particle survives as well, and remains in its original object. The new particles have age zero and mass equal to the emitting particle. They use the velocity inheritance parameter of the target object.
-----------------------------------------
ls : list [boolean] []
List all events for the chosen shape, like this: event1Name event2Name ... If no shape identified, list all events for all shapes, like this: shape1Name event1Name shape2Name event2Name... Returns a string array.
-----------------------------------------
n : name [string] ['query', 'edit']
Assign a name to an event you are creating, or identify an event you wish to edit, query, or delete. See examples.
-----------------------------------------
pr : proc [script] ['query', 'edit']
Specify a MEL proc to be called each time the event occurs. This must be a global proc with arguments as follows: global proc procName( string obj, int id, string objHit ); Arguments passed in are the name of the particle object, the id of the particle which collided, and the name of the object collided with. You can use particle -id -q to get values of the particle's attributes.
-----------------------------------------
r : random [boolean] ['query', 'edit']
Used with -split and -emit flags. If -random is set true and -split or -emit is set to n, then a random number of particles uniformly distributed between 1 and n will be created at the event.
-----------------------------------------
re : rename [string] ['query']
Assign a new name to an event you are editing. See examples.
-----------------------------------------
s : select [boolean] []
This flag is obsolete. See the -name flag.
-----------------------------------------
spl : split [uint] ['query', 'edit']
Colliding particle splits into specified number of new particles. These new particles become part of the assigned target object. If no target has been assigned, they become part of the same object. The new particles inherit the current age of the particle that split. They use the velocity inheritance parameter of the target object. If you set both emit and split, the event will do both: first emit new particles, then split the original one. This is a change from earlier versions where emit and split were mutually exclusive.
-----------------------------------------
sp : spread [float] ['query', 'edit']
Particles created at collision will spread out a random amount from the rebound direction of the colliding particle. The spread is specified as a fraction (0-1) of 90 degrees. If spread is set at 0 (the default) all the new particles created may coincide.
-----------------------------------------
t : target [string]
Target object for emitting or split particles. New particles created through the -emit or -split flags join this object.
"""
def expression(q=1,e=1,ae="uint",an="uint",a="string",n="string",o="string",sf=1,sn=1,s="string",td=1,uc="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/expression.html
-----------------------------------------
expression is undoable, queryable, and editable.
This command describes an expression that belongs to the current scene. The
expression is a block of code of unlimited length with a C-like syntax that
can perform conversions, mathematical operations, and logical decision making
on any numeric attribute(s) in the scene. One expression can read and alter
any number of numeric attributes. Theoretically, every expression in a scene
can be combined into one long expression, but it is recommended that they are
separated for ease of use and editing, as well as efficiency.
If this command is being sent by the command line or in a script, then the
user should be sure to embed escaped newlines (\n), tabs (\t) for clarity when
reading them in the expression editor. Also, quotes in an expression must be
escaped (\") so that they are not confused by the system as the end of your
string. When using the expression editor, these characters are escaped for you
unless they are already within quotes.
Note, expressions that alter or use per-particle attributes of a particle
shape should use the '[dynExpression][751]' command.
[751]: dynExpression.html
-----------------------------------------
Return Value:
string The name of the expression
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ae : alwaysEvaluate [uint] ['query', 'edit']
If this is TRUE (the default), then the expression will be evaluated whenever time changes regardless of whether the other inputs have changed, and an output is requested. If it is FALSE, then the expression will only be evaluated if one or more of the inputs changes and an output is requested. Note, if 'time' or 'frame' are inputs, then the expression will act as if this was set to TRUE.
-----------------------------------------
an : animated [uint] ['query', 'edit']
Sets the animation mode on the expression node: 0 = Not Animated, 1 = Animated, 2 = Animated with No Callback.
-----------------------------------------
a : attribute [string] ['query', 'edit']
Sets the name of the attribute to use for the expression
-----------------------------------------
n : name [string] ['query', 'edit']
Sets the name of the dependency graph node to use for the expression
-----------------------------------------
o : object [string] ['query', 'edit']
Sets the "default" object for the expression. This allows the expression writer to not type the object name for frequently-used objects. See the examples below.
-----------------------------------------
sf : safe [boolean] ['query']
Returns true if no potential side effect can occurs running that expression. Safe expression will be optimized to evaluate only when needed even if flagged alwaysEvaluate.
-----------------------------------------
sn : shortNames [boolean] ['query', 'edit']
When used with the -q/query flag, tells the command to return the expression with attribute names as short as possible. The default is to return the FULL attribute name, regardless of how the user entered it into the expression, including the object names. With this flag set, attribute names are returned as their short versions, and any attribute that belongs to the default object, if there is one specified, will not display the object's name.
-----------------------------------------
s : string [string] ['query', 'edit']
Set the expression string
-----------------------------------------
td : timeDependent [boolean] ['query']
Returns true if expression is evaluated when time change. An expression can be time-dependent for the following reasons: \- The expression refers to 'time' or 'frame' keywords. \- The expression have side effects (unsafe). \- The expression node's "time" attribute is connected manually. If the expression is safe and not time dependent, then they will always evaluate on depend, even if alwaysEvaluate is on.
-----------------------------------------
uc : unitConversion [string]
Insert specified unit conversion nodes at creation: "all", "none," or "angularOnly." Default is "all." For angularOnly, will insert unit conversion nodes only for angular attributes (allowing degrees-to-radians conversion). This is for performance tuning. If queried, returns the option used when the expression was created or last edited.
"""
def expressionEditorListen(lf="string",la="string",le="string",ln="string",sla="string",sle="string",sln="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/expressionEditorListen.html
-----------------------------------------
expressionEditorListen is undoable, NOT queryable, and NOT editable.
Listens for messages for the Expression Editor, at its request, and
communicates them to it. This action is for internal use only and should not
be called by users. This action should be called only by the Expression
Editor.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
lf : listenFile [string] []
Listen for changes to the file argument.
-----------------------------------------
la : listenForAttr [string] []
Listen for changes to the attributes of the node argument.
-----------------------------------------
le : listenForExpression [string] []
Listen for changes to the named expression
-----------------------------------------
ln : listenForName [string] []
Listen for name changes for the node argument.
-----------------------------------------
sla : stopListenForAttr [string] []
Stop listening for changes to the attributes of the node argument.
-----------------------------------------
sle : stopListenForExpression [string] []
Stop listening for changes to the named expression
-----------------------------------------
sln : stopListenForName [string]
Stop listening for name changes for the node argument.
"""
def getParticleAttr(a=1,at="string",o="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/getParticleAttr.html
-----------------------------------------
getParticleAttr is undoable, NOT queryable, and NOT editable.
This action will return either an array of values, or the average value and
maximum offset, for a specied per-particle attribute of a particle object or
component. If a particle component is specified on the command line, values
are returned for that component only. If an object name is given instead,
values are returned for all particles in that object. If no object name is
passed, but a particle object or component is selected, values are returned
for the selection.
If you list components, they must all be from the same particle object; the
action ignores all objects after the first. Likewise if you list more than one
object, the actiion will return values only for the first one.
-----------------------------------------
Return Value:
float[] Command result
-----------------------------------------
Flags:
-----------------------------------------
a : array [boolean] []
Tells the action whether you want a full array of data. If set true, the action returns an array of floats containing the values for all the specified particles. If set false (the default), the action returns the average value and the maximum offset from the average over the component. If the attribute is a vector attribute, the action returns six values: Average X, Average Y, Average Z, Maximum offset in X, Y, and Z of component.
-----------------------------------------
at : attribute [string] []
Tells the action which attribute you want the value of. Must be a per- particle attribute.
-----------------------------------------
o : object [string]
This flag is obsolete. Instead of using it, please pass the name of the object and/or components you want on the command line. See the examples.
"""
def goal(q=1,g="string",i=1,utr=1,w="float"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/goal.html
-----------------------------------------
goal is undoable, queryable, and NOT editable.
Specifies the given objects as being goals for the given particle object. If
the goal objects are geometry, each particle in the particle object will each
try to follow or match its position to that of a certain vertex/CV/lattice
point of the goal. If the goal object is another particle object, each
particle will try to follow a paricle of the goal. In any other case, all the
particles will try to follow the current location of the goal object's
transform. You can get this latter behavior for a geometry or particle object
too by using -utr true.
The goal weight can be keyframed. It lives on the particle object to which the
goal was added and is a multi-attribute.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
g : goal [string] ['query']
This flag specifies string to be a goal of the particle object on the command line or the currently selected particle object. This flag can be used multiple times to specify multiple goals for a particle object. Query is for use by the attribute editor.
-----------------------------------------
i : index [boolean] ['query']
Returns array of multi-attribute indices for the goals. Intended for use by the Attribute Editor.
-----------------------------------------
utr : useTransformAsGoal [boolean] []
Use transform of specified object instead of the shape. Meaningful only for particle and geometry objects. Can only be passed once, applies to all objects passed with -g.
-----------------------------------------
w : weight [float]
This specifies the goal weight as a value from 0 to 1. A value of 0 means that the goal's position will have no effect on the particle object, while a weight of 1 will make the particle object try to follow the goal object exactly. This flag can only be passed once and sets the weight for every goal passed with the -g/-goal flag.
"""
def gravity(q=1,e=1,att="float",dx="float",dy="float",dz="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/gravity.html
-----------------------------------------
gravity is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A gravity field simulates the
Earth's gravitational force. It pulls objects in a fixed direction (generally
downward) entirely independent of their position or mass.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
The default for -dx -dy -dz is always the opposite of the current up
direction. For example, if the current up direction is (0,1,0) (a standard
Maya configuration), then the gravity default is -dx 0 -dy -1 -dz 0. The
default for -a is 9.8. 9.8 meters per second squared happens to be standard
Earth gravity, but in fact Maya interprets this value as centimeters per
second squared. If we were to use it as meters per second squared then with
default Maya units, your particles would vanish almost in the wink of an eye.
If you want a different value, set it in the gravity option box.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
dx : directionX [float] ['query', 'edit']
X-component of direction.
-----------------------------------------
dy : directionY [float] ['query', 'edit']
Y-component of direction.
-----------------------------------------
dz : directionZ [float] ['query', 'edit']
Z-component of direction
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def newton(q=1,e=1,att="float",m="float",mxd="linear",mnd="float",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/newton.html
-----------------------------------------
newton is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A Newton field pulls an object
towards the exerting object with force dependent on the exerting object's
mass, using Newton's universal law of gravitation.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
mnd : minDistance [float] ['query', 'edit']
Minimum distance at which field is exerted. Distance is in the denominator of the field force equation. Setting md to a small positive number avoids bizarre behavior when the distance gets extremely small.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def particle(q=1,e=1,at="string",ch=1,c="float",ct=1,dc=1,dal=1,fv="float",grs="linear",i="float",jbp="[linear, linear, linear]",jr="linear",ll="[linear, linear, linear]",n="string",nj="uint",order="int",id="int",ppd=1,ppv=1,p="[linear, linear, linear]",sn="string",ur="[linear, linear, linear]",vv="[float, float, float]"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/particle.html
-----------------------------------------
particle is undoable, queryable, and editable.
The particle command creates a new particle object from a list of world space
points. If a particle object is created, the command returns the names of the
new particle shape and its associated particle object dependency node. If an
object was queried, the results of the query are returned. Per particle
attributes can be queried using the particleId or the order of the particle in
the particle array. If an object was edited, nothing is returned.
-----------------------------------------
Return Value:
string The name of the particle object created
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the name of the attribute being queried or edited. In query mode, this flag needs a value.
-----------------------------------------
ch : cache [boolean] ['query', 'edit']
Turns caching on/off for the particle shape.
-----------------------------------------
c : conserve [float] ['query', 'edit']
Conservation of momentum control (between 0 and 1). Specifies the fraction of the particle shape's existing momentum which is conserved from frame to frame. A value of 1 (the default) corresponds to true Newtonian physics, in which momentum is conserved.
-----------------------------------------
ct : count [boolean] ['query']
Returns the number of particles in the object.
-----------------------------------------
dc : deleteCache [boolean] []
Deletes the particle shapes cache. This command is not undoable.
-----------------------------------------
dal : dynamicAttrList [boolean] ['query']
Returns a list of the dynamic attributes in the object.
-----------------------------------------
fv : floatValue [float] ['edit']
Used only in per particle attribute edit. Specifies that the edit is of a float attribute and must be followed by the new float value.
-----------------------------------------
grs : gridSpacing [linear] ['query']
Spacing between particles in the grid.
-----------------------------------------
i : inherit [float] ['query', 'edit']
Inherit this fraction (0-1) of emitting object's velocity.
-----------------------------------------
jbp : jitterBasePoint [[linear, linear, linear]] ['query']
Base point (center point) for jitters. The command will create one swatch of jitters for each base point. It will pair up other flags with base points in the order they are given in the command line. If not enough instances of the other flags are availble, the last one on the line with be used for all other instances of -jpb.
-----------------------------------------
jr : jitterRadius [linear] ['query']
Max radius from the center to place the particle instances.
-----------------------------------------
ll : lowerLeft [[linear, linear, linear]] ['query']
Lower left point of grid.
-----------------------------------------
n : name [string] ['query', 'edit']
name of particle object
-----------------------------------------
nj : numJitters [uint] ['query']
Number of jitters (instances) per particle.
-----------------------------------------
order : order [int] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the zero-based order (index) of the particle whose attribute is being queried or edited in the particle array. Querying the value of a per particle attribute requires the -attribute and -id or -order flags and their arguments to precede the -q flag. In query mode, this flag needs a value.
-----------------------------------------
id : particleId [int] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the id of the particle whose attribute is being queried or edited. Querying the value of a per particle attribute requires the -attribute and -id or -order flags and their arguments to precede the -q flag. In query mode, this flag needs a value.
-----------------------------------------
ppd : perParticleDouble [boolean] ['query']
Returns a list of the per-particle double attributes, excluding initial- state, cache, and information-only attributes.
-----------------------------------------
ppv : perParticleVector [boolean] ['query']
Returns a list of the per-particle vector attributes, excluding initial- state, cache, and information-only attributes.
-----------------------------------------
p : position [[linear, linear, linear]] []
World-space position of each particle.
-----------------------------------------
sn : shapeName [string] ['query', 'edit']
Specify the shape name used for geometry instancing. DO not confuse this with the -n flag which names the particle object.
-----------------------------------------
ur : upperRight [[linear, linear, linear]] ['query']
Upper right point of grid.
-----------------------------------------
vv : vectorValue [[float, float, float]]
Used only in per particle attribute edit. Specifies that the edit is of a vector attribute and must be followed by all three float values for the vector.
"""
def particleExists():
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/particleExists.html
-----------------------------------------
particleExists is undoable, NOT queryable, and NOT editable.
This command is used to query if a particle or soft object with the given name
exists. Either the transform or shape name can be used as well as the name of
the soft object.
-----------------------------------------
Return Value:
boolean True if there is a particle object or soft object by the given name,
false otherwise.
"""
def particleFill(cp=1,dw=1,mxx="float",mxy="float",mxz="float",mnx="float",mny="float",mnz="float",pd="float",rs="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/particleFill.html
-----------------------------------------
particleFill is NOT undoable, NOT queryable, and NOT editable.
This command generates an nParticle system that fills the selected object with
a grid of particles.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
cp : closePacking [boolean] []
If this is on then the particles are positioned as closely as possible in a hexagonal close packing arrangement. Otherwise particles are packed in a uniform grid lattice.
-----------------------------------------
dw : doubleWalled [boolean] []
This flag should be used if the thickness of the object to fill has been modeled( for example a mug ). Otherwise the particles will be created inside the wall. Note that doubleWalled will not handle some cases very well. For example a double walled donut shape may get the center region of the donut filled. In cases like this it may be better to make the internal wall a separate mesh then fill that without using doubleWalled.
-----------------------------------------
mxx : maxX [float] []
The fill max bounds of the particles in X relative to the X bounds of the object. A value of zero is totally empty and one is totally full. The default value is 1, or fully filled.
-----------------------------------------
mxy : maxY [float] []
The fill max bounds of the particles in Y relative to the Y bounds of the object. A value of zero is totally empty and one is totally full. The default value is 1, or fully filled.
-----------------------------------------
mxz : maxZ [float] []
The fill max bounds of the particles in Z relative to the Z bounds of the object. A value of zero is totally empty and one is totally full. The default value is 1, or fully filled.
-----------------------------------------
mnx : minX [float] []
The fill lower bounds of the particles in X relative to the X bounds of the object. A value of zero is totally full and one is totally empty. The default value is 0, or fully filled.
-----------------------------------------
mny : minY [float] []
The fill lower bounds of the particles in Y relative to the Y bounds of the object. A value of zero is totally full and one is totally empty. The default value is 0, or fully filled.
-----------------------------------------
mnz : minZ [float] []
The fill lower bounds of the particles in Z relative to the Z bounds of the object. A value of zero is totally full and one is totally empty. The default value is 0, or fully filled.
-----------------------------------------
pd : particleDensity [float] []
This controls the size of the particles. At a value of 1.0 the particle size will exactly match the grid spacing determined by the resolution parameter and the object bounds. Particles which overlap the surface will be rejected even if the center of the particle is inside.
-----------------------------------------
rs : resolution [int]
This determines the total number of particles generated. It represent the resolution along the largest axis of the object's bounding box. For a cube shape the total potential particles will be the cube of the resolution. For other shapes it will be less. The default value for this flag is 10, so 1000 particles could be generated for a cube shape.
"""
def particleInstancer(q=1,e=1,a=1,aa="string",ad="string",ap="string",aua="string",awu="string",am=1,c="string",sto="string",cs="float",csu="string",i="int",id="string",lod="string",n="string",obj="string",oi="string",age="string",p="string",rm=1,r="string",ro="string",rt="string",ru="string",sc="string",sh="string",vis="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/particleInstancer.html
-----------------------------------------
particleInstancer is undoable, queryable, and editable.
This command is used to create a particle instancer node and set the proper
attributes in the particle shape and in the instancer node. It will also
create the connections needed between the particle shape and the instancer
node.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
a : addObject [boolean] ['edit']
This flag indicates that objects specified by the -object flag will be added to the instancer node as instanced objects.
-----------------------------------------
aa : aimAxis [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the aim axis of the instanced objects.
-----------------------------------------
ad : aimDirection [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the aim direction of the instanced objects.
-----------------------------------------
ap : aimPosition [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the aim position of the instanced objects.
-----------------------------------------
aua : aimUpAxis [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the aim up axis of the instanced objects.
-----------------------------------------
awu : aimWorldUp [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the aim world up of the instanced objects.
-----------------------------------------
am : attributeMapping [boolean] ['query']
This flag queries the particle attribute mapping list.
-----------------------------------------
c : cycle [string] ['query', 'edit']
This flag sets or queries the cycle attribute for the instancer node. The options are "none", "sequential". The default is "none".
-----------------------------------------
sto : cycleStartObject [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the cycle start object of the instanced objects.
-----------------------------------------
cs : cycleStep [float] ['query', 'edit']
This flag sets or queries the cycle step attribute for the instancer node. This attribute indicates the size of the step in frames or seconds (see cycleStepUnits).
-----------------------------------------
csu : cycleStepUnits [string] ['query', 'edit']
This flag sets or queries the cycle step unit attribute for the instancer node. The options are "frames" or "seconds". The default is "frames".
-----------------------------------------
i : index [int] ['query']
This flag is used to query the name of the ith instanced object.
-----------------------------------------
id : instanceId [string] ['query']
This flag queries the particle attribute name to be used for the id of the instanced objects.
-----------------------------------------
lod : levelOfDetail [string] ['query', 'edit']
This flag sets or queries the level of detail of the instanced objects. The options are "geometry", "boundingBox" or "boundingBoxes". The default is "geometry".
-----------------------------------------
n : name [string] ['query']
This flag sets or queries the name of the instancer node.
-----------------------------------------
obj : object [string] ['query', 'edit']
This flag indicates which objects will be add/removed from the list of instanced objects. The flag is used in conjuction with the -addObject and -remove flags. If neither of these flags is specified on the command line then -addObject is assumed.
-----------------------------------------
oi : objectIndex [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the object index of the instanced objects.
-----------------------------------------
age : particleAge [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the age of the instanced objects.
-----------------------------------------
p : position [string] ['query', 'edit']
DEFAULT "worldPosition" This flag sets or queries the particle attribute name to be used for the positions of the instanced objects. By default the attribute is worldPosition.
-----------------------------------------
rm : removeObject [boolean] ['edit']
This flag indicates that objects specified by the -object flag will be removed from the instancer node as instanced objects.
-----------------------------------------
r : rotation [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the rotation of the instanced objects.
-----------------------------------------
ro : rotationOrder [string] ['query', 'edit']
This flag specifies the rotation order associated with the rotation flag. The options are XYZ, XZY, YXZ, YZX, ZXY, or ZYX. By default the attribute is XYZ.
-----------------------------------------
rt : rotationType [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the rotation type of the instanced objects.
-----------------------------------------
ru : rotationUnits [string] ['query', 'edit']
This flag specifies the rotation units associated with the rotation flag. The options are degrees or radians. By default the attribute is degrees.
-----------------------------------------
sc : scale [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the scale of the instanced objects.
-----------------------------------------
sh : shear [string] ['query', 'edit']
This flag sets or queries the particle attribute name to be used for the shear of the instanced objects.
-----------------------------------------
vis : visibility [string]
This flag sets or queries the particle attribute name to be used for the visibility of the instanced objects.
"""
def particleRenderInfo(q=1,al="int",ala=1,n="int",rtc=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/particleRenderInfo.html
-----------------------------------------
particleRenderInfo is undoable, queryable, and NOT editable.
This action provides information access to the particle render subclasses.
These are derived from TdynRenderBase. This action is used primarily by the
Attribute Editor to gather information about attributes used for rendering.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
al : attrList [int] ['query']
Return the list of attributes used by this render type.
-----------------------------------------
ala : attrListAll [boolean] ['query']
Return a complete list of all render attributes used by the particle object. This also includes the per particle attributes.
-----------------------------------------
n : name [int] ['query']
Return the name of the render subclass using the render type.
-----------------------------------------
rtc : renderTypeCount [boolean]
Return the count of registered render classes for particle.
"""
def radial(q=1,e=1,att="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",typ="float",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/radial.html
-----------------------------------------
radial is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A radial field pushes objects
directly towards or directly away from it, like a magnet.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
typ : type [float] ['query', 'edit']
Type of radial field (0 - 1). This controls the algorithm by which the field is attenuated. Type 1, provided for backward compatibility, specifies the same algorithm as Alias | Wavefront Dynamation. A value between 0 and 1 yields a linear blend.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def rigidBody(q=1,e=1,act=1,av=1,afa="string",b="float",c=1,com="[float, float, float]",cl=1,cc=1,cn=1,cp=1,dp="float",dc=1,df="float",f=1,ig=1,i="[float, float, float]",imp="[float, float, float]",iav="[float, float, float]",iv="[float, float, float]",l="int",lcm=1,m="float",n="string",o="[float, float, float]",pc=1,pas=1,p="[float, float, float]",rs="string",slv="string",si="[float, float, float]",sio="string",sf="float",tf="int",vel=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/rigidBody.html
-----------------------------------------
rigidBody is undoable, queryable, and editable.
This command creates a rigid body from a polygonal or nurbs surface.
-----------------------------------------
Return Value:
string New rigid body name.
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
act : active [boolean] ['query', 'edit']
Creates a rigid body that is active. An active rigid body accepts and causes collisions and is effected by dynamic fields. This is the default.
-----------------------------------------
av : angularVelocity [boolean] ['query']
Current angular velocity of rigid body.
-----------------------------------------
afa : applyForceAt [string] ['query', 'edit']
Determines how forces are applied to the rigid body. The choices are centerOfMass | boundingBox | verticesOrCVs. Default: boundingBox
-----------------------------------------
b : bounciness [float] ['query', 'edit']
Sets the restitution (or bounciness) of the rigid body. Range: 0.0 - 2.0 Default: 0.6
-----------------------------------------
c : cache [boolean] ['query', 'edit']
Turns caching on (1) or off (0) for the rigid body. Default: off
-----------------------------------------
com : centerOfMass [[float, float, float]] ['query', 'edit']
Sets the center of mass (x,y,z) of the rigid body. Default: actual center of mass.
-----------------------------------------
cl : collisions [boolean] ['query', 'edit']
Truns collisions on/off for the rigid body. If the collisions are turned of the rigid body will not collide with any other rigid body. Default: on.
-----------------------------------------
cc : contactCount [boolean] ['query']
returns the current contact count for the rigid body.
-----------------------------------------
cn : contactName [boolean] ['query']
returns all the rigid body names which are in contact with this shape. One name for each contact will be returned.
-----------------------------------------
cp : contactPosition [boolean] ['query']
returns all the contact position. One position for each contact will be returned.
-----------------------------------------
dp : damping [float] ['query', 'edit']
Sets the damping value of the rigid body. Range: -2.0 - 2.0 Default: 0.0
-----------------------------------------
dc : deleteCache [boolean] ['edit']
Deletes the cache (if one exists) of the rigid body.
-----------------------------------------
df : dynamicFriction [float] ['query', 'edit']
Sets the dynamic friction for the rigid body. Range: 0.0 - 1.0 Default: 0.2
-----------------------------------------
f : force [boolean] ['query']
Current force on the rigid body.
-----------------------------------------
ig : ignore [boolean] ['query', 'edit']
Causes the rigid body to be ignored in the rigid solver. Default: off
-----------------------------------------
i : impulse [[float, float, float]] ['edit']
Applies an impulse (instantaneous) force on a rigid body. Default: 0.0 0.0 0.0
-----------------------------------------
imp : impulsePosition [[float, float, float]] ['edit']
The position at which the impulse is applied. Default: the bodies center of mass.
-----------------------------------------
iav : initialAngularVelocity [[float, float, float]] ['query', 'edit']
Sets the initial angular velocity of the rigid body. Default: 0.0 0.0 0.0
-----------------------------------------
iv : initialVelocity [[float, float, float]] ['query', 'edit']
Sets the initial velocity of the rigid body. Default: 0.0 0.0 0.0
-----------------------------------------
l : layer [int] ['query', 'edit']
Sets the collision layer of the rigid body. Only rigid bodies in the same collision layer can collide with each other. Range: >= 0 Default: 0.
-----------------------------------------
lcm : lockCenterOfMass [boolean] ['query', 'edit']
Locks the center of mass for the rigid body. Default: off
-----------------------------------------
m : mass [float] ['query', 'edit']
Sets the mass of the rigid body. Range: > 0 Default: 1.0
-----------------------------------------
n : name [string] ['query', 'edit']
Assigns the rigid body the given name.
-----------------------------------------
o : orientation [[float, float, float]] ['query', 'edit']
Sets the initial orientation (x,y,z) of the rigid body. Default: current orientation.
-----------------------------------------
pc : particleCollision [boolean] ['query', 'edit']
Turns the ability for a rigid body to collide with particles on and off. The particles will exert a force on the rigid body. Default: off
-----------------------------------------
pas : passive [boolean] ['query', 'edit']
Creates a rigid body that is passive. A passive rigid body does not react to collisions but active rigid bodies can collide with it. Dynamic Fields will not effect a passive rigid body. Only passive rigid bodies can be keyframed.
-----------------------------------------
p : position [[float, float, float]] ['query', 'edit']
Sets the initial position (x,y,z) of the rigid body. Default: current position.
-----------------------------------------
rs : removeShape [string] ['query', 'edit']
Remove the named shape.
-----------------------------------------
slv : solver [string] ['query', 'edit']
The name of the solver which this rigid node is to resided. If the solver does not exists then the rigid body will not be created. If the edit flag is thrown add the solver exists, the rigid body will be moved to that solver.
-----------------------------------------
si : spinImpulse [[float, float, float]] ['edit']
Applies an spin impulse (instantaneous rotational) force on a rigid body. Default: 0.0 0.0 0.0
-----------------------------------------
sio : standInObject [string] ['query', 'edit']
Causes the simulator to use a stand in object for the simulation. The choices are none | cube | sphere. The default is none. Default: none
-----------------------------------------
sf : staticFriction [float] ['query', 'edit']
Sets the static friction for the rigid body. Range: 0.0 - 1.0 Default: 0.2
-----------------------------------------
tf : tesselationFactor [int] ['query']
Sets the tesselation factor for a rigid body surface. Range: >= 10 Default: 200.
-----------------------------------------
vel : velocity [boolean]
Current velocity of rigid body.
"""
def rigidSolver(q=1,e=1,at=1,b=1,cd=1,c=1,ct="float",ctd=1,cr=1,cu=1,deleteCache=1,dcm=1,dc=1,dv=1,d=1,f=1,i=1,ic=1,n="string",rb=1,rbc=1,sc=1,si=1,sm="int",stt="float",st=1,sta=1,s="float",vs="float"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/rigidSolver.html
-----------------------------------------
rigidSolver is undoable, queryable, and editable.
This command sets the attributes for the rigid solver
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
at : autoTolerances [boolean] ['query', 'edit']
Turns the auto tolerance calculation on and off. The auto tolerances calculation will override the default or user defined values of the step size and collision tolerance value that is calculated based on the objects in the scene. Default: 0 (off)
-----------------------------------------
b : bounciness [boolean] ['query', 'edit']
Turns bounciness on and off for the an the objects in the simulation. Default value: on
-----------------------------------------
cd : cacheData [boolean] ['query', 'edit']
Turns the cache on fall all rigid bodies in the system. Default value: off
-----------------------------------------
c : collide [boolean] ['query', 'edit']
Disallows the interpenetration of the two rigid bodies listed. Default: Collide is on for all bodies.
-----------------------------------------
ct : collisionTolerance [float] ['query', 'edit']
Sets the collision tolerance. This is the error at which two objects are considered to have collided. Range: 0.0005 - 1.000 Default: 0.02
-----------------------------------------
ctd : contactData [boolean] ['query', 'edit']
Turns the contact data information on/off for all rigid bodies. Default value: off
-----------------------------------------
cr : create [boolean] []
Creates a new rigid solver.
-----------------------------------------
cu : current [boolean] []
Sets rigid solver as the current solver.
-----------------------------------------
deleteCache : deleteCache [boolean] ['query', 'edit']
Deletes the cache for all rigid bodies in the system.
-----------------------------------------
dcm : displayCenterOfMass [boolean] ['query', 'edit']
Displays the center of mass icon. Default value: on
-----------------------------------------
dc : displayConstraint [boolean] ['query', 'edit']
Displays the constraint vectors. Default value: on
-----------------------------------------
dv : displayVelocity [boolean] ['query', 'edit']
Displays the velocity vectors. Default value: off
-----------------------------------------
d : dynamics [boolean] ['query', 'edit']
Turns dynamics on and off for the an the objects in the simulation. Default value: on
-----------------------------------------
f : friction [boolean] ['query', 'edit']
Turns friction on and off for the an the objects in the simulation. Default value: on
-----------------------------------------
i : interpenetrate [boolean] ['query', 'edit']
Allows the two rigid bodies listed to interpenetrate. Default: interpenetration is off for all bodies.
-----------------------------------------
ic : interpenetrationCheck [boolean] ['edit']
Checks for interpenetrating rigid bodies in the scene.
-----------------------------------------
n : name [string] ['query', 'edit']
Name of the new object
-----------------------------------------
rb : rigidBodies [boolean] ['query']
Returns a list of rigid bodies in the solver.
-----------------------------------------
rbc : rigidBodyCount [boolean] ['query']
Returns the number of rigid bodies in the solver.
-----------------------------------------
sc : showCollision [boolean] ['query', 'edit']
Displays the colliding objects in a different color.
-----------------------------------------
si : showInterpenetration [boolean] ['query', 'edit']
Displays the interpenetrating objects in a different color.
-----------------------------------------
sm : solverMethod [int] ['query', 'edit']
Sets the solver method. The choices are 0 | 1 | 2. 0 = Euler (fastest/least acurate), 1 = Runge-Kutta ( slower/more acurate), 2 = adaptive Runge-Kutta (slowest/most acurate). The default is 2 (adaptive Runge-Kutta)
-----------------------------------------
stt : startTime [float] ['query', 'edit']
Sets the start time for the solver.
-----------------------------------------
st : state [boolean] ['query', 'edit']
Turns the rigid solver on or off.
-----------------------------------------
sta : statistics [boolean] ['query', 'edit']
Turns the statistic information on/off for all rigid bodies. Default value: off
-----------------------------------------
s : stepSize [float] ['query', 'edit']
Sets the solvers step size. This is the maximum size of a single step the solver will take at one time. Range: 0.0004 - 0.100 Default: 0.0333
-----------------------------------------
vs : velocityVectorScale [float]
scales the velocity vector display. Default value: 1.0
"""
def runup(cch=1,fpf=1,fsf=1,mxf="time",st=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/runup.html
-----------------------------------------
runup is undoable, NOT queryable, and NOT editable.
runup plays the scene through a frame of frames, forcing dynamic objects to
evaluate as it does so. If no max frame is specified, runup runs up to the
current time.
-----------------------------------------
Return Value:
string Command result
-----------------------------------------
Flags:
-----------------------------------------
cch : cache [boolean] []
Cache the state after the runup.
-----------------------------------------
fpf : fromPreviousFrame [boolean] []
Run up the animation from the previously evaluated frame. If no flag is supplied this is the default.
-----------------------------------------
fsf : fromStartFrame [boolean] []
Run up the animation from the start frame. If no flag is supplied -fromPreviousFrame is the default.
-----------------------------------------
mxf : maxFrame [time] []
Ending time for runup, in current user time units. The runup will always start at the minimum start frame for all dynamic objects.
-----------------------------------------
st : state [boolean]
Turns runup and cache on/off.
"""
def saveInitialState(atr="string",all=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/saveInitialState.html
-----------------------------------------
saveInitialState is undoable, NOT queryable, and NOT editable.
saveInitialState saves the current state of dynamics objects as the initial
state. A dynamic object is a particle shape, rigid body, rigid constraint or
rigid solver. If no objects are specified, it saves the initial state for any
selected objects. It returns the names of the objects for which initial state
was saved.
-----------------------------------------
Return Value:
string Command result
-----------------------------------------
Flags:
-----------------------------------------
atr : attribute [string] []
Save the initial state of the specified attribute only. This is a multi- use flag.
-----------------------------------------
all : saveall [boolean]
Save the initial state for all dynamics objects in the scene.
"""
def setDynamic(awr=1,dwr=1,all=1,off=1,on=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/setDynamic.html
-----------------------------------------
setDynamic is undoable, NOT queryable, and NOT editable.
setDynamic sets the isDynamic attribute of particle objects on or off. If no
objects are specified, it sets the attribute for any selected objects. If -all
is thrown, it sets the attribute for all particle objects in the scene. By
default it sets the attribute true (on); if the -off flag is thrown, it sets
the attribute false (off).
WARNING: setDynamic is obsolescent. This is the last version of Maya in which
it will be supported.
-----------------------------------------
Return Value:
string array
-----------------------------------------
Flags:
-----------------------------------------
awr : allOnWhenRun [boolean] []
Obsolete, no longer suppported or necessary.
-----------------------------------------
dwr : disableAllOnWhenRun [boolean] []
Obsolete, no longer suppported or necessary.
-----------------------------------------
all : setAll [boolean] []
Set for all objects.
-----------------------------------------
off : setOff [boolean] []
Sets isDynamic false.
-----------------------------------------
on : setOn [boolean]
Sets isDynamic true. This flag is set by default.
"""
def setParticleAttr(at="string",fv="float",o="string",rf="float",rv="[float, float, float]",r=1,vv="[float, float, float]"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/setParticleAttr.html
-----------------------------------------
setParticleAttr is undoable, NOT queryable, and NOT editable.
This action will set the value of the chosen attribute for every particle or
selected component in the selected or passed particle object. Components
should not be passed to the command line. For setting the values of
components, the components must be selected and only the particle object's
names should be passed to this action. If the attribute is a vector attribute
and the -vv flag is passed, then the three floats passed will be used to set
the values. If the attribute is a vector and the -fv flag is pass and the -vv
flag is not passed, then the float will be repeated for each of the X, Y, and
Z values of the attribute. Similarly, if the attribute is a float attribute
and a vector value is passed, then the length of the vector passed will be
used for the value. Note: The attribute passed must be a Per-Particle
attribute.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] []
Tells the action which attribute you want to set
-----------------------------------------
fv : floatValue [float] []
Tells what you want the value to be set to of a float attribute
-----------------------------------------
o : object [string] []
If this flag is passed and the STRING is the name of a particle object's transform or shape, then ONLY that object will be edited, ignoring the selection list or command line, and ALL of its particles' values will be changed for the specified attribute.
-----------------------------------------
rf : randomFloat [float] []
Tells the command to add a random value from -FLOAT to +FLOAT to the results of each particle. The default is 0.0.
-----------------------------------------
rv : randomVector [[float, float, float]] []
Tells the command to add a random value from <<-x,-y,-z>> to <<x,y,z>> to the results of each particle. The default 0 0 0.
-----------------------------------------
r : relative [boolean] []
If this is set to TRUE (the default is FALSE), then the float or vector value will be added to the current value for each particle.
-----------------------------------------
vv : vectorValue [[float, float, float]]
Tells what you want the value to be set to of a vector attribute
"""
def soft(q=1,c=1,d=1,dh=1,g="float",h=1,n="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/soft.html
-----------------------------------------
soft is undoable, queryable, and NOT editable.
Makes a soft body from the object(s) passed on the command line or in the
selection list. The geometry can be a NURBS, polygonal, lattice object. The
resulting soft body is made up of a hierarchy with a particle shape and a
geometry shape, thus:
T
/ \
T G
/
P
Dynamics are applied to the particle shape and the resulting particle
positions then drive the locations of the geometry's CVs, vertices, or lattice
points.
With the convert option, the particle shape and its transform are simply
inserted below the original shape's hierarchy. With the duplicate option, the
original geometry's transform and shape are duplicated underneath its parent,
and the particle shape is placed under the duplicate. Note that any animation
on the hierarchy will affect the particle shape as well. If you do not want
then, then reparent the structure outside the hierarchy.
When duplicating, the soft portion (the duplicate) is given the name "copyOf"
\+ "original object name". The particle portion is always given the name
"original object name" \+ "Particles."
None of the flags of the soft command can be queried. The soft -q command is
used only to identify when an object is a soft body, or when two objects are
part of the same soft body. See the examples.
-----------------------------------------
Return Value:
string array
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
c : convert [boolean] []
This tells the command that you want the original object to be the actual deformed object. The particle shape portion of the soft body will be inserted in the same hierarchy as the original, under the same parent (with one additional intervening transform which is initially the identity). If no flags are passed, then this is assumed. The combination -c -h 1 is not valid; if you have this in your scripts, remove the -h 1.
-----------------------------------------
d : duplicate [boolean] []
This tells the command that you want to make a copy of the original object and use the copy as the deforming geometry. Input connections to the original object are duplicated. You would do this if you wanted to keep the original object in your scene and also have a copy of it that was a soft body. This flag and -dh are mutually exclusive.
-----------------------------------------
dh : duplicateHistory [boolean] []
This is the same as -d, except that upstream history, is duplicated as well, instead of just input connections. This flag and -d are mutually exclusive.
-----------------------------------------
g : goal [float] []
This is the same as -d, but in addition it tells the command that you want the resulting soft body to try to follow the original geometry, using the set goal weight as the value that controls how strongly it is to follow it. A value of 1.0 will try to follow exactly, and a value of 0.0 will not follow at all. The default value is 0.5. This value must be from 0.0 to 1.0. You could use -d with -g, but it is redundant. If you want history to be duplicated, you can use -dh and -g together.
-----------------------------------------
h : hideOriginal [boolean] []
This flag is used only when duplicating (-d, -g, or -dh). If set to true, whichever of the two objects is NOT the soft object will be hidden. In other words, with -d -h true, the original object will be hidden; with -d -c -h 1 the duplicate object will be hidden. You would typically do this if you want to use the non-dynamic object as a goal for the soft one (see -g) but you do not want it visible in the scene. The flags -h 1 and -c are mutually exclusive.
-----------------------------------------
n : name [string]
This flag is obsolete. If you wish to give your new soft object a name, use the rename command (or from the UI, use the outliner).
"""
def spring(q=1,e=1,add=1,all=1,ct=1,d="float",dPS="float",efw="float",exc=1,l="float",mxd="float",mnd="float",mm=1,n="string",nd=1,rl="float",rPS="float",sfw="float",s="float",sPS="float",udp=1,urp=1,usp=1,wl="uint",wf=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/spring.html
-----------------------------------------
spring is undoable, queryable, and editable.
The spring command can do any of the following:
* create a new spring object (shape plus transform). The shape contains springs between the points (particles, cvs, etc.) of the objects selected or listed on the command line.
* create new springs and add them to an existing spring object
* edit or query certain attributes of an existing spring object
One "spring object" may have hundreds or even thousands of individual springs.
Certain attributes of the spring object specify exactly where the springs are
attached to which other objects.
Springs may be attached to the following: particles, vertices of soft bodies,
CVs or edit points of curves or surfaces, vertices of polygonal objects, and
points of lattices. In the case where one endpoint of a spring is non-dynamic
(a CV, edit point, etc.), the spring does not affect its motion, but the
motion of the point affects the spring. A spring will be created only if at
least one of the endpoints is dynamic: for example, a spring will never be
created between two CVs. A single spring object can hold springs which are
incident to any number of other objects.
The spring has creation-only flags and editable flags. Creation-only flags
(minDistance, maxDistance, add, exclusive, all, wireframe, walklength,
checkExisting) can be used only when creating new springs (including adding
springs to existing spring object). Editable flags modify attributes of an
existing spring object.
If a spring object is created, this command returns the names of the shape and
transform. If a spring object is queried, the command returns the results of
the query.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
add : addSprings [boolean] []
If specified, springs will be added to the existing selected set of springs. (Default is to create a new spring object.)
-----------------------------------------
all : allPoints [boolean] ['edit']
If True, sets the mode of spring application to All. This will add springs between all points selected. (Default is False.)
-----------------------------------------
ct : count [boolean] ['query']
Return the number of springs in the shape. Query-only. We maintain this flag only for compatibility with earlier versions of Maya. To get the count of springs, it is much faster and simpler to use the spring shape's count attribute: getAttr <shapeName>.count.
-----------------------------------------
d : damping [float] ['query', 'edit']
Damping factor for the springs created in the spring object. (Default = 0.2 )
-----------------------------------------
dPS : dampingPS [float] ['query', 'edit']
Damping factor for the springs created in the spring object. This will initialize all the entries in dampingPS to the specified value. In both the flag and the attribute name, "PS" stands for "per-spring." (Default = 0.2 )
-----------------------------------------
efw : endForceWeight [float] ['query', 'edit']
Amount of the force of the spring that gets applied to the point to which the spring ends. Valid range is from 0.0 to 1.0. (Default = 1.0 )
-----------------------------------------
exc : exclusive [boolean] []
If true, tells the command to create springs only between pairs of points which are not in the same object. (Default is False.)
-----------------------------------------
l : length [float] ['query', 'edit']
Vestigial form of "restLength." Please use "restLength" instead.
-----------------------------------------
mxd : maxDistance [float] ['edit']
Maximum distance between two points that a spring would be considered.
-----------------------------------------
mnd : minDistance [float] []
Minimum distance between two points that a spring would be considered. (Default = 0.0. See Defaults for more information on this flag's default.)
-----------------------------------------
mm : minMax [boolean] []
If True, sets the mode of the spring application to Min/Max. This will add springs between all points from the specified point groups that are between the minimum and maximum distance values set with min and max. (Default is False.) Note: This gets automatically set if either the min or max flags are used.
-----------------------------------------
n : name [string] ['query']
Name of spring object.
-----------------------------------------
nd : noDuplicate [boolean] []
Check for existing springs and don't add a new spring between two points already connected by a spring in the same object. Only the object the command is working on is checked. This flag is relevant only when using -add. (Default = false)
-----------------------------------------
rl : restLength [float] ['query', 'edit']
Per-object rest length for the new springs. Springs can use either their per-object or per-spring rest length. See the -lPS and -ulp flags.
-----------------------------------------
rPS : restLengthPS [float] ['query', 'edit']
Per-spring rest length for the new springs. This will initialize all the entries in restLengthPS to the specified value. If this flag is not thrown, each rest length will be initialized to the distance between the two points at the time the spring is created (i.e., the initial length of the spring). When playing back, springs can use either their per-spring or per-object rest length. See the -rl and -urp flags. In both the flag and the attribute name, "PS" stands for "per-spring."
-----------------------------------------
sfw : startForceWeight [float] ['query', 'edit']
Amount of the force of the spring that gets applied to the point from which the spring starts. Valid range is from 0.0 to 1.0. (Default = 1.0 )
-----------------------------------------
s : stiffness [float] ['query', 'edit']
Stiffness of the springs created in the spring object. (Default = 1.0 ) -damp float Vestigial form of "damping." Please use "damping" instead.
-----------------------------------------
sPS : stiffnessPS [float] ['query', 'edit']
Stiffness of the springs created in the spring object. This will initialize all the entries in stiffnessPS to the specified value. In both the flag and the attribute name, "PS" stands for "per-spring." (Default = 1.0 )
-----------------------------------------
udp : useDampingPS [boolean] ['query', 'edit']
Specifies whether to use dampingPS (per spring damping). If set to false, the per object damping attribute value will be used. This flag simply sets the useDampingPS attribute of the spring shape. In both the flag and the attribute name, "PS" stands for "per-spring." (Default = false )
-----------------------------------------
urp : useRestLengthPS [boolean] ['query', 'edit']
Specifies whether to use restLengthPS (per spring restLength). If set to false, the per object restLength attribute value will be used. This flag simply sets the useRestLengthPS attribute of the spring shape. In both the flag and the attribute name, "PS" stands for "per-spring." (Default = false )
-----------------------------------------
usp : useStiffnessPS [boolean] ['query', 'edit']
Specifies whether to use stiffnessPS (per spring stiffness). If set to false, the per object stiffness attribute value will be used. This flag simply sets the useStiffnessPS attribute of the spring shape. In both the flag and the attribute name, "PS" stands for "per-spring." (Default = false )
-----------------------------------------
wl : walkLength [uint] []
This flag is valid only when doing wireframe creation. It will create springs between pairs of points connected by the specified number of edges. For example, if walk length is 2, each pair of points separated by no more than 2 edges will get a spring. Walk length measures the distance between pairs of vertices just like the number of blocks measures the distance between two intersections in a city.
-----------------------------------------
wf : wireframe [boolean]
If True, sets the mode of the spring application to Wireframe. This is valid only for springs created on a soft body. It will add springs along all edges connecting the adjacent points (vertices or CV's) of curves and surfaces. (Default is False.)
"""
def turbulence(q=1,e=1,att="float",f="float",m="float",mxd="linear",n="string",nsl="int",nsr="float",pv=1,p="float",px="float",py="float",pz="float",pos="[linear, linear, linear]",tsr="linear",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/turbulence.html
-----------------------------------------
turbulence is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A turbulence field causes
irregularities (also called 'noise' or 'jitter') in the motion of affected
objects.
Use connectDynamic to cause the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
f : frequency [float] ['query', 'edit']
Frequency of turbulence field. This determines how often motion is disrupted.
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
nsl : noiseLevel [int] ['query', 'edit']
If the noiseLevel parameter is greater than zero, the field will do multiple lookups in the table. Each additional lookup is weighted using noiseRatio (which see). The noiseLevel is the number of additional lookups, so if noiseLevel is 0, there is just one lookup. A value of 0 (the default) corresponds to the way the field behaved prior to Maya 3.0.
-----------------------------------------
nsr : noiseRatio [float] ['query', 'edit']
If noiseLevel is greater than zero, then noiseRatio is the relative magnitude for each consecutive noise evaluation. These are cumulative: for example, if noiseRatio is 0.5, then the first evaluation is weighted 0.5, the second 0.25, and so on. Has no effect if noiseLevel is zero.
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
p : phase [float] ['query', 'edit']
Phase shift of turbulence field. This influences the direction of the disruption. This flag is obsolete and is retained only for backward compatibility. It is replaced by -phaseX, -phaseY, and -phaseZ. Setting -phase is identical to setting -phaseZ (the phase shift was always in the Z dimension).
-----------------------------------------
px : phaseX [float] ['query', 'edit']
X component of phase shift of turbulence field. This influences the direction of the disruption.
-----------------------------------------
py : phaseY [float] ['query', 'edit']
Y component of phase shift of turbulence field. This influences the direction of the disruption.
-----------------------------------------
pz : phaseZ [float] ['query', 'edit']
Z component of phase shift of turbulence field. This influences the direction of the disruption.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def uniform(q=1,e=1,att="float",dx="float",dy="float",dz="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/uniform.html
-----------------------------------------
uniform is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A uniform field pushes objects in a
fixed direction. The field strength, but not the field direction, depends on
the distance from the object to the field location.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
dx : directionX [float] ['query', 'edit']
X-component of direction.
-----------------------------------------
dy : directionY [float] ['query', 'edit']
Y-component of direction.
-----------------------------------------
dz : directionZ [float] ['query', 'edit']
Z-component of direction
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def volumeAxis(q=1,e=1,alx="float",arx="float",att="float",afx="float",afc="float",dtr="float",dx="float",dy="float",dz="float",drs="float",ia=1,m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",trb="float",tfx="float",tfy="float",tfz="float",tox="float",toy="float",toz="float",trs="float",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/volumeAxis.html
-----------------------------------------
volumeAxis is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A volume axis field can push
particles in four directions, defined with respect to a volume: along the
axis, away from the axis or center, around the axis, and in a user-specified
direction. These are analogous to the emission speed controls of volume
emitters. The volume axis field also contains a wind turbulence model
(different from the turbulence field) that simulates an evolving flow of
liquid or gas. The turbulence has a build in animation that is driven by a
connection to a time node.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
alx : alongAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction along the central axis of the volume. See the diagrams in the documentation.
-----------------------------------------
arx : aroundAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction around the central axis of the volume. See the diagrams in the documentation.
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
afx : awayFromAxis [float] ['query', 'edit']
Initial velocity multiplier in the direction away from the central axis of the volume. See the diagrams in the documentation. Used only with the cylinder, cone, and torus volumes.
-----------------------------------------
afc : awayFromCenter [float] ['query', 'edit']
Initial velocity multiplier in the direction away from the center point of a cube or sphere volume. Used only with the cube and sphere volumes.
-----------------------------------------
dtr : detailTurbulence [float] ['query', 'edit']
The relative intensity of a second higher frequency turbulence. This can be used to create fine features in large scale flows. Both the speed and the frequency on this second turbulence are higher than the primary turbulence. When the detailTurbulence is non-zero the simulation may run a bit slower, due to the computation of a second turbulence.
-----------------------------------------
dx : directionX [float] ['query', 'edit']
x-component of force direction. Used with directional speed.
-----------------------------------------
dy : directionY [float] ['query', 'edit']
y-component of force direction. Used with directional speed.
-----------------------------------------
dz : directionZ [float] ['query', 'edit']
z-component of force direction. Used with directional speed.
-----------------------------------------
drs : directionalSpeed [float] ['query', 'edit']
Adds a component of speed in the direction specified by the directionX, Y, and Z attributes.
-----------------------------------------
ia : invertAttenuation [boolean] ['query', 'edit']
If this attribute is FALSE, the default, then the attenuation makes the field's effect decrease as the affected point is further from the volume's axis and closer to its edge. If the is set to TRUE, then the effect of the field increases in this case, making the full effect of the field felt at the volume's edge.
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
trb : turbulence [float] ['query', 'edit']
Adds a force simulating a turbulent wind that evolves over time.
-----------------------------------------
tfx : turbulenceFrequencyX [float] ['query', 'edit']
The repeats of the turbulence function in X.
-----------------------------------------
tfy : turbulenceFrequencyY [float] ['query', 'edit']
The repeats of the turbulence function in Y.
-----------------------------------------
tfz : turbulenceFrequencyZ [float] ['query', 'edit']
The repeats of the turbulence function in Z.
-----------------------------------------
tox : turbulenceOffsetX [float] ['query', 'edit']
The translation of the turbulence function in X.
-----------------------------------------
toy : turbulenceOffsetY [float] ['query', 'edit']
The translation of the turbulence function in Y.
-----------------------------------------
toz : turbulenceOffsetZ [float] ['query', 'edit']
The translation of the turbulence function in Z.
-----------------------------------------
trs : turbulenceSpeed [float] ['query', 'edit']
The rate of change of the turbulence over time. The turbulence loops seamlessly every 1.0/turbulenceSpeed seconds. To animate this rate attach a new time node to the time input on the volumeAxisNode then animate the time value on the time node.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def vortex(q=1,e=1,att="float",ax="float",ay="float",az="float",m="float",mxd="linear",n="string",pv=1,pos="[linear, linear, linear]",tsr="linear",vex=1,vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/vortex.html
-----------------------------------------
vortex is undoable, queryable, and editable.
For each listed object, the command creates a new field. The field has a shape
which lives in the DAG and it has an associated dependency node. The field is
added to the list of fields owned by the object. Use connectDynamic to cause
the field to affect a dynamic object. Note that if more than one object is
listed, a separate field is created for each object.
If fields are created, this command returns the names of each owning shape and
of the field shapes themselves. If a field was queried, the results of the
query are returned. If a field was edited, the field name is returned.
If no object names are provided but the active selection list is non-empty,
the command creates a field for every object in the list. If the list is
empty, the command defaults to -pos 0 0 0. A vortex field pulls objects in a
circular direction, like a whirlpool or tornado. Objects affected by the
vortex field tend to rotate around the axis specified by -ax, -ay, and -az.
The transform is the associated dependency node. Use connectDynamic to cause
the field to affect a dynamic object.
If fields are created, this command returns the names of each of the fields.
If a field was queried, the results of the query are returned. If a field was
edited, the field name is returned.
If object names are provided or the active selection list is non-empty, the
command creates a field for every object in the list and calls addDynamic to
add it to the object. If the list is empty, the command defaults to -pos 0 0
0.
Setting the -pos flag with objects named on the command line is an error.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
att : attenuation [float] ['query', 'edit']
Attentuation rate of field
-----------------------------------------
ax : axisX [float] ['query', 'edit']
X-component of vortex axis
-----------------------------------------
ay : axisY [float] ['query', 'edit']
Y-component of vortex axis
-----------------------------------------
az : axisZ [float] ['query', 'edit']
Z-component of vortex axis
-----------------------------------------
m : magnitude [float] ['query', 'edit']
Strength of field.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which field is exerted. -1 indicates that the field has no maximum distance.
-----------------------------------------
n : name [string] ['query', 'edit']
name of field
-----------------------------------------
pv : perVertex [boolean] ['query', 'edit']
Per-vertex application. If this flag is set true, then each individual point (CV, particle, vertex,etc.) of the chosen object exerts an identical copy of the force field. If this flag is set to false, then the froce is exerted only from the geometric center of the set of points.
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
Position in space (x,y,z) where you want to place a gravity field. The gravity then emanates from this position in space rather than from an object. Note that you can both use -pos (creating a field at a position) and also provide object names.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
vex : volumeExclusion [boolean] ['query', 'edit']
Volume exclusion of the field. If true, points outside the volume (defined by the volume shape attribute) are affected, If false, points inside the volume are affected. Has no effect if volumeShape is set to "none."
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the field. Volume offset translates the field's volume by the specified amount from the actual field location. This is in the field's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the field. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which the field has effect. Values are: "none," "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the field. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def nBase(q=1,e=1,cct="string",cs=1,ss=1,ttv="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/nBase.html
-----------------------------------------
nBase is undoable, queryable, and editable.
Edits one or more nBase objects. Note that nBase objects include nCloth,
nRigid and nParticle objects, but the options on this command do not currently
apply to nParticle objects.
-----------------------------------------
Return Value:
boolean Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
cct : clearCachedTextureMap [string] ['edit']
Clear the cached texture map for the specified attribute from the nBase.
-----------------------------------------
cs : clearStart [boolean] ['edit']
Indicates that start state should be cleared
-----------------------------------------
ss : stuffStart [boolean] ['edit']
Indicates that current state should be stuffed into the start state
-----------------------------------------
ttv : textureToVertex [string]
Transfer the texture map data for the specified attribute into the related per-vertex attribute.
"""
def nParticle(q=1,e=1,at="string",ch=1,c="float",ct=1,dc=1,dal=1,fv="float",grs="linear",i="float",jbp="[linear, linear, linear]",jr="linear",ll="[linear, linear, linear]",n="string",nj="uint",order="int",id="int",ppd=1,ppv=1,p="[linear, linear, linear]",sn="string",ur="[linear, linear, linear]",vv="[float, float, float]"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/nParticle.html
-----------------------------------------
nParticle is undoable, queryable, and editable.
The nParticle command creates a new nParticle object from a list of world
space points. If an nParticle object is created, the command returns the names
of the new particle shape and its associated particle object dependency node.
If an object was queried, the results of the query are returned. Per particle
attributes can be queried using the particleId or the order of the particle in
the particle array. If an object was edited, nothing is returned.
-----------------------------------------
Return Value:
string The name of the nParticle object created
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the name of the attribute being queried or edited. In query mode, this flag needs a value.
-----------------------------------------
ch : cache [boolean] ['query', 'edit']
Turns caching on/off for the particle shape.
-----------------------------------------
c : conserve [float] ['query', 'edit']
Conservation of momentum control (between 0 and 1). Specifies the fraction of the particle shape's existing momentum which is conserved from frame to frame. A value of 1 (the default) corresponds to true Newtonian physics, in which momentum is conserved.
-----------------------------------------
ct : count [boolean] ['query']
Returns the number of particles in the object.
-----------------------------------------
dc : deleteCache [boolean] []
Deletes the particle shapes cache. This command is not undoable.
-----------------------------------------
dal : dynamicAttrList [boolean] ['query']
Returns a list of the dynamic attributes in the object.
-----------------------------------------
fv : floatValue [float] ['edit']
Used only in per particle attribute edit. Specifies that the edit is of a float attribute and must be followed by the new float value.
-----------------------------------------
grs : gridSpacing [linear] ['query']
Spacing between particles in the grid.
-----------------------------------------
i : inherit [float] ['query', 'edit']
Inherit this fraction (0-1) of emitting object's velocity.
-----------------------------------------
jbp : jitterBasePoint [[linear, linear, linear]] ['query']
Base point (center point) for jitters. The command will create one swatch of jitters for each base point. It will pair up other flags with base points in the order they are given in the command line. If not enough instances of the other flags are availble, the last one on the line with be used for all other instances of -jpb.
-----------------------------------------
jr : jitterRadius [linear] ['query']
Max radius from the center to place the particle instances.
-----------------------------------------
ll : lowerLeft [[linear, linear, linear]] ['query']
Lower left point of grid.
-----------------------------------------
n : name [string] ['query', 'edit']
name of particle object
-----------------------------------------
nj : numJitters [uint] ['query']
Number of jitters (instances) per particle.
-----------------------------------------
order : order [int] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the zero-based order (index) of the particle whose attribute is being queried or edited in the particle array. Querying the value of a per particle attribute requires the -attribute and -id or -order flags and their arguments to precede the -q flag. In query mode, this flag needs a value.
-----------------------------------------
id : particleId [int] ['query', 'edit']
Used in per particle attribute query and edit. Specifies the id of the particle whose attribute is being queried or edited. Querying the value of a per particle attribute requires the -attribute and -id or -order flags and their arguments to precede the -q flag. In query mode, this flag needs a value.
-----------------------------------------
ppd : perParticleDouble [boolean] ['query']
Returns a list of the per-particle double attributes, excluding initial- state, cache, and information-only attributes.
-----------------------------------------
ppv : perParticleVector [boolean] ['query']
Returns a list of the per-particle vector attributes, excluding initial- state, cache, and information-only attributes.
-----------------------------------------
p : position [[linear, linear, linear]] []
World-space position of each particle.
-----------------------------------------
sn : shapeName [string] ['query', 'edit']
Specify the shape name used for geometry instancing. DO not confuse this with the -n flag which names the particle object.
-----------------------------------------
ur : upperRight [[linear, linear, linear]] ['query']
Upper right point of grid.
-----------------------------------------
vv : vectorValue [[float, float, float]]
Used only in per particle attribute edit. Specifies that the edit is of a vector attribute and must be followed by all three float values for the vector.
"""
def nSoft(q=1,c=1,d=1,dh=1,g="float",h=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/nSoft.html
-----------------------------------------
nSoft is undoable, queryable, and NOT editable.
Makes a nSoft body from the object(s) passed on the command line or in the
selection list. The geometry can be a NURBS, polygonal, lattice object. The
resulting nSoft body is made up of a hierarchy with a particle shape and a
geometry shape, thus:
T
/ \
T G
/
P
Dynamics are applied to the particle shape and the resulting particle
positions then drive the locations of the geometry's CVs, vertices, or lattice
points.
With the convert option, the particle shape and its transform are simply
inserted below the original shape's hierarchy. With the duplicate option, the
original geometry's transform and shape are duplicated underneath its parent,
and the particle shape is placed under the duplicate. Note that any animation
on the hierarchy will affect the particle shape as well. If you do not want
them, then reparent the structure outside the hierarchy.
When duplicating, the nSoft portion (the duplicate) is given the name "copyOf"
\+ "original object name". The particle portion is always given the name
"original object name" \+ "Particles."
None of the flags of the nSoft command can be queried. The nSoft -q command is
used only to identify when an object is a nSoft body, or when two objects are
part of the same nSoft body. See the examples.
-----------------------------------------
Return Value:
string array
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
c : convert [boolean] []
This tells the command that you want the original object to be the actual deformed object. The particle shape portion of the nSoft body will be inserted in the same hierarchy as the original, under the same parent (with one additional intervening transform which is initially the identity). If no flags are passed, then this is assumed. The combination -c -h 1 is not valid; if you have this in your scripts, remove the -h 1.
-----------------------------------------
d : duplicate [boolean] []
This tells the command that you want to make a copy of the original object and use the copy as the deforming geometry. Input connections to the original object are duplicated. You would do this if you wanted to keep the original object in your scene and also have a copy of it that was a nSoft body. This flag and -dh are mutually exclusive.
-----------------------------------------
dh : duplicateHistory [boolean] []
This is the same as -d, except that upstream history, is duplicated as well, instead of just input connections. This flag and -d are mutually exclusive.
-----------------------------------------
g : goal [float] []
This is the same as -d, but in addition it tells the command that you want the resulting nSoft body to try to follow the original geometry, using the set goal weight as the value that controls how strongly it is to follow it. A value of 1.0 will try to follow exactly, and a value of 0.0 will not follow at all. The default value is 0.5. This value must be from 0.0 to 1.0. You could use -d with -g, but it is redundant. If you want history to be duplicated, you can use -dh and -g together.
-----------------------------------------
h : hideOriginal [boolean]
This flag is used only when duplicating (-d, -g, or -dh). If set to true, whichever of the two objects is NOT the nSoft object will be hidden. In other words, with -d -h true, the original object will be hidden; with -d -c -h 1 the duplicate object will be hidden. You would typically do this if you want to use the non-dynamic object as a goal for the nSoft one (see -g) but you do not want it visible in the scene. The flags -h 1 and -c are mutually exclusive.
"""
def dynPaintEditor(q=1,e=1,ao=1,autoSave=1,cam="string",cm=1,cu=1,cc="[string, string, string, string]",cl="[float, float, float]",ctl=1,ccs=1,dt="string",dsa="string",dfg=1,di="int",dsl="string",dst="string",dtx=1,dtg="string",dbf=1,da=1,drc=1,ex=1,fu="int",fil="string",f="string",fmc="string",hlc="string",ig=1,li="string",lck=1,mlc="string",mn="string",nim=1,ni="[int, int, float, float, float]",pa="float",pnl="string",p="string",rl=1,ref=1,rmd="int",ra=1,ri=1,rig="[float, float]",sa=1,sbm="string",si=1,sb="float",sg="float",sr="float",slc="string",sbf=1,snp=1,sts=1,swp="int",ts="int",up=1,uc=1,ulk=1,upd=1,ut="string",wr="[boolean, boolean]",wi="string",zm="float"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/dynPaintEditor.html
-----------------------------------------
dynPaintEditor is undoable, queryable, and editable.
Create a editor window that can be painted into
-----------------------------------------
Return Value:
string Editor name
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ao : activeOnly [boolean] ['query', 'edit']
For Scene mode, this determines if only the active strokes will be refreshed.
-----------------------------------------
autoSave : autoSave [boolean] ['query', 'edit']
For Canvas mode, this determines if the buffer will be saved to a disk file after every stroke. Good for painting textures and viewing the results in shaded display in the model view.
-----------------------------------------
cam : camera [string] ['query', 'edit']
Sets the name of the camera which the Paint Effects panel looks through.
-----------------------------------------
cm : canvasMode [boolean] ['query', 'edit']
Sets the Paint Effects panel into Canvas mode if true.
-----------------------------------------
cu : canvasUndo [boolean] ['edit']
Does a fast undo in Canvas mode. This is a special undo because we are not using any history when we paint in Canvas mode so we provide a single level undo for the Canvas.
-----------------------------------------
cc : changeCommand [[string, string, string, string]] ['query', 'edit']
Parameters: * First string: command * Second string: editorName * Third string: editorCmd * Fourth string: updateFunc Call the command when something changes in the editor The command should have this prototype : command(string $editor, string $editorCmd, string $updateFunc, int $reason) The possible reasons could be : * 0: no particular reason * 1: scale color * 2: buffer (single/double) * 3: axis * 4: image displayed * 5: image saved in memory
-----------------------------------------
cl : clear [[float, float, float]] ['edit']
Clears the buffer (if in Canvas mode) to the floating point values (R,G,B).
-----------------------------------------
ctl : control [boolean] ['query']
Query only. Returns the top level control for this editor. Usually used for getting a parent to attach popup menus. Caution: It is possible for an editor to exist without a control. The query will return "NONE" if no control is present.
-----------------------------------------
ccs : currentCanvasSize [boolean] ['query']
In Query mode, this returns the (X,Y) resolution of the current canvas.
-----------------------------------------
dt : defineTemplate [string] []
Puts the command in a mode where any other flags and arguments are parsed and added to the command template specified in the argument. They will be used as default arguments in any subsequent invocations of the command when templateName is set as the current template.
-----------------------------------------
dsa : displayAppearance [string] ['query', 'edit']
Sets the display appearance of the model panel. Possible values are "wireframe", "points", "boundingBox", "smoothShaded", "flatShaded". This flag may be used with the -interactive and -default flags. Note that only "wireframe", "points", and "boundingBox" are valid for the interactive mode.
-----------------------------------------
dfg : displayFog [boolean] ['query', 'edit']
For Scene mode, this determines if fog will be displayed in the Paint Effects panel when refreshing the scene. If fog is on, but this is off, fog will only be drawn on the strokes, not the rest of the scene.
-----------------------------------------
di : displayImage [int] ['query', 'edit']
Set a particular image in the Editor Image Stack as the current Editor Image. Images are added to the Editor Image Stack using the "si/saveImage" flag.
-----------------------------------------
dsl : displayLights [string] ['query', 'edit']
Sets the lighting for shaded mode. Possible values are "selected", "active", "all", "default".
-----------------------------------------
dst : displayStyle [string] ['query', 'edit']
Set the mode to display the image. Valid values are: * "color" to display the basic RGB image * "mask" to display the mask channel * "lum" to display the luminance of the image
-----------------------------------------
dtx : displayTextures [boolean] ['query', 'edit']
Turns on or off display of textures in shaded mode
-----------------------------------------
dtg : docTag [string] ['query', 'edit']
Attaches a tag to the editor.
-----------------------------------------
dbf : doubleBuffer [boolean] ['query', 'edit']
Set the display in double buffer mode
-----------------------------------------
da : drawAxis [boolean] ['query', 'edit']
Set or query whether the axis will be drawn.
-----------------------------------------
drc : drawContext [boolean] ['query']
Returns the name of the context.
-----------------------------------------
ex : exists [boolean] []
Returns whether the specified object exists or not. Other flags are ignored.
-----------------------------------------
fu : fastUpdate [int] []
Obsolete - do not use
-----------------------------------------
fil : fileName [string] ['query', 'edit']
This sets the file to which the canvas will be saved.
-----------------------------------------
f : filter [string] ['query', 'edit']
Specifies the name of an itemFilter object to be used with this editor. This filters the information coming onto the main list of the editor.
-----------------------------------------
fmc : forceMainConnection [string] ['query', 'edit']
Specifies the name of a selectionConnection object that the editor will use as its source of content. The editor will only display items contained in the selectionConnection object. This is a variant of the -mainListConnection flag in that it will force a change even when the connection is locked. This flag is used to reduce the overhead when using the -unlockMainConnection , -mainListConnection, -lockMainConnection flags in immediate succession.
-----------------------------------------
hlc : highlightConnection [string] ['query', 'edit']
Specifies the name of a selectionConnection object that the editor will synchronize with its highlight list. Not all editors have a highlight list. For those that do, it is a secondary selection list.
-----------------------------------------
ig : iconGrab [boolean] ['edit']
This puts the Paint Effects panel into Grab Icon mode where the user is expected to drag out a section of the screen to be made into an icon.
-----------------------------------------
li : loadImage [string] ['edit']
load an image from disk and set it as the current Editor Image
-----------------------------------------
lck : lockMainConnection [boolean] ['edit']
Locks the current list of objects within the mainConnection, so that only those objects are displayed within the editor. Further changes to the original mainConnection are ignored.
-----------------------------------------
mlc : mainListConnection [string] ['query', 'edit']
Specifies the name of a selectionConnection object that the editor will use as its source of content. The editor will only display items contained in the selectionConnection object.
-----------------------------------------
mn : menu [string] []
Sets the name of the script used to build a menu in the editor. The script takes the editor name as an argument.
-----------------------------------------
nim : nbImages [boolean] ['query']
returns the number of images
-----------------------------------------
ni : newImage [[int, int, float, float, float]] ['query', 'edit']
Starts a new image in edit mode, setting the resolution to the integer values (X,Y) and clearing the buffer to the floating point values (R,G,B). In Query mode, this returns the (X,Y) resolution of the current Image.
-----------------------------------------
pa : paintAll [float] ['edit']
Redraws the buffer in current refresh mode.
-----------------------------------------
pnl : panel [string] ['query']
Specifies the panel for this editor. By default if an editor is created in the create callback of a scripted panel it will belong to that panel. If an editor does not belong to a panel it will be deleted when the window that it is in is deleted.
-----------------------------------------
p : parent [string] ['query', 'edit']
Specifies the parent layout for this editor. This flag will only have an effect if the editor is currently un-parented.
-----------------------------------------
rl : redrawLast [boolean] ['edit']
Redraws the last stroke again. Useful when it's brush has just changed. This feature does a fast undo and redraws the stroke again.
-----------------------------------------
ref : refresh [boolean] ['edit']
requests a refresh of the current Editor Image.
-----------------------------------------
rmd : refreshMode [int] ['query', 'edit']
Sets the refresh mode to the specified value. 0 - Do not draw strokes on refresh, 1 - Redraw strokes in wireframe mode, 2 - Redraw strokes in final rendered mode.
-----------------------------------------
ra : removeAllImages [boolean] ['edit']
remove all the Editor Images from the Editor Image Stack
-----------------------------------------
ri : removeImage [boolean] ['edit']
remove the current Editor Image from the Editor Image Stack
-----------------------------------------
rig : rollImage [[float, float]] ['edit']
In Canvas mode, this rolls the image by the floating point values (X,Y). X and Y are between 0 (no roll) and 1 (full roll). A value of .5 rolls the image 50% (ie. the border moves to the center of the screen.
-----------------------------------------
sa : saveAlpha [boolean] ['query', 'edit']
For Canvas mode, this determines if the alpha will be saved when storing the canvas to a disk file.
-----------------------------------------
sbm : saveBumpmap [string] ['query', 'edit']
Saves the current buffer as a bump map to the specified file.
-----------------------------------------
si : saveImage [boolean] ['edit']
save the current Editor Image to memory. Saved Editor Images are stored in an Editor Image Stack. The most recently saved image is stored in position 0, the second most recently saved image in position 1, and so on... To set the current Editor Image to a previously saved image use the "di/displayImage" flag.
-----------------------------------------
sb : scaleBlue [float] ['query', 'edit']
Define the scaling factor for the blue component in the View. The default value is 1 and can be between -1000 to +1000
-----------------------------------------
sg : scaleGreen [float] ['query', 'edit']
Define the scaling factor for the green component in the View. The default value is 1 and can be between -1000 to +1000
-----------------------------------------
sr : scaleRed [float] ['query', 'edit']
Define the scaling factor for the red component in the View. The default value is 1 and can be between -1000 to +1000
-----------------------------------------
slc : selectionConnection [string] ['query', 'edit']
Specifies the name of a selectionConnection object that the editor will synchronize with its own selection list. As the user selects things in this editor, they will be selected in the selectionConnection object. If the object undergoes changes, the editor updates to show the changes.
-----------------------------------------
sbf : singleBuffer [boolean] ['query', 'edit']
Set the display in single buffer mode
-----------------------------------------
snp : snapShot [boolean] ['edit']
Takes a snapshot of the current camera view.
-----------------------------------------
sts : stateString [boolean] ['query']
Query only flag. Returns the MEL command that will create an editor to match the current editor state. The returned command string uses the string variable $editorName in place of a specific name.
-----------------------------------------
swp : swap [int] []
Obsolete - do not use
-----------------------------------------
ts : tileSize [int] ['edit']
Sets the size of the tile for the hardware texture redraw of the display buffer.
-----------------------------------------
up : unParent [boolean] ['edit']
Specifies that the editor should be removed from its layout. This cannot be used in query mode.
-----------------------------------------
uc : undoCache [boolean] ['edit']
By default the last image is cached for undo. If this is set false, then undoing will be disabled in canvas mode and undo in scene mode will force a full refresh. Less memory will be used if this is set false before the first clear or refresh of the current scene.
-----------------------------------------
ulk : unlockMainConnection [boolean] ['edit']
Unlocks the mainConnection, effectively restoring the original mainConnection (if it is still available), and dynamic updates.
-----------------------------------------
upd : updateMainConnection [boolean] ['edit']
Causes a locked mainConnection to be updated from the orginal mainConnection, but preserves the lock state.
-----------------------------------------
ut : useTemplate [string] []
Forces the command to use a command template other than the current one.
-----------------------------------------
wr : wrap [[boolean, boolean]] ['query', 'edit']
For Canvas mode, should the buffer wrap in U, and V (respectively) when painting.
-----------------------------------------
wi : writeImage [string] ['edit']
write the current Editor Image to disk
-----------------------------------------
zm : zoom [float]
Zooms the Canvas image by the specified value.
"""
def getDefaultBrush():
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/getDefaultBrush.html
-----------------------------------------
getDefaultBrush is undoable, NOT queryable, and NOT editable.
The command returns the name of the default Paint Effects brush.
-----------------------------------------
Return Value:
string Name of the default brush node
"""
def paintEffectsDisplay(q=1,me=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/paintEffectsDisplay.html
-----------------------------------------
paintEffectsDisplay is NOT undoable, queryable, and NOT editable.
Command to set the global display methods for paint effects items
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
me : meshDrawEnable [boolean]
Set whether mesh draw is enabled on objects
"""
def pfxstrokes(fn="string",pc=1,sl=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/pfxstrokes.html
-----------------------------------------
pfxstrokes is NOT undoable, NOT queryable, and NOT editable.
This command will loop through all the Paint Effects strokes, including
pfxHair nodes, and write the current state of all the tubes to a file. For
normal stroke nodes tubes must be ON in the brush or there will be no output.
For pfxHair nodes there will always be output, but the format is different
than for stroke nodes(however one can assign a brush with tubes = ON to a
pfxHair node, in which case it will output the same format as strokes). The
general file format is ASCII, using commas to separate numerical values and
newlines between blocks of data. The format used for pfxHair nodes presents
the hair curves points in order from root to tip of the hair. The hairs follow
sequentially in the following fashion: NumCvs pointX,pointY,pointZ,
normalX,normalY,normalZ, width, colorR,colorG,colorB, paramU
pointX,pointY,pointZ, normalX,normalY,normalZ, width, colorR,colorG,colorB,
paramU etc... NumCvs pointX,pointY,pointZ, normalX,normalY,normalZ, width,
colorR,colorG,colorB, paramU etc.. The format used to output files for brushes
with tubes=ON is more complex. The tubes can branch and the order the segments
are written is the same order they are drawn in. Slowly drawing a tall grass
brush in the paint effects panel can help to illustrate the order the segments
will appear in the file. New tubes can start "growing" before others are
finished. There is no line for "NumCvs". Instead all data for each segment
appears on each line. The data on each line is the same as passed into the
paint effects runtime function. See the argument list of paintRuntimeFunc.mel
for the order and a description of these parameters. The parameters match up
exactly in the order they appear on a line of the output file with the order
of arguments to this function. If one wishes to parse the output file and
connect the segments together into curves the branchId, parentId and
siblingCnt parameters can help when sorting which segment connects to which
line. Using the -postCallback option will write out the tubes data after it
has been proessed by the runTime callback.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
fn : filename [string] []
The output file.
-----------------------------------------
pc : postCallback [boolean] []
Output information to the file after the Runtime Callback MEL function has been invoked. The default is to output the information prior to the callback.
-----------------------------------------
sl : selected [boolean]
Only loop through the selected strokes.
"""
def stroke(n="string",pr=1,s="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/stroke.html
-----------------------------------------
stroke is undoable, NOT queryable, and NOT editable.
The stroke command creates a new Paint Effects stroke node.
-----------------------------------------
Return Value:
string (The path to the new stroke or the replaced stroke)
-----------------------------------------
Flags:
-----------------------------------------
n : name [string] []
Sets the name of the stroke to the input string
-----------------------------------------
pr : pressure [boolean] []
On creation, allows the copying of the pressure mapping settings from the Paint Effects Tool. Default is false.
-----------------------------------------
s : seed [int]
Sets the random seed for this stroke.
"""
def colorAtPoint(u="float",v="float",xu="float",xv="float",mu="float",mv="float",o="string",su="uint",sv="uint"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/colorAtPoint.html
-----------------------------------------
colorAtPoint is NOT undoable, NOT queryable, and NOT editable.
The colorAtPoint command is used to query textures or ocean shaders at passed
in uv coordinates. (For ocean shaders uv is x and z in worldspace ). The
return value is a floating point array whose size is determined by either the
number of input uv arguments passed in and the the queried value. One can
query alpha only, rgb only, or rgba values. The returned array is only single
indexed, so if rgb is specified then the index for red values would be index *
3. Blue is index * 3 + 1, and green is index * 3 + 2. For rgba use a multiple
of 4 instead of 3. For alpha only one can simply use the index. There are two
basic argument formats that may be used: colorAtPoint -u 0 -v 0 -u .2 -v .1
etc.. for all points or colorAtPoint -mu 0 -mv 0 -xu 1 -xv 1 -su 10 -sv 10 //
samples 100 points If one is sampling several points and they are all in a
regular grid formation it is more efficient to call this routine with the
latter method, which uses a min/max uv and number of samples, rather than a
long argument list of uv coords.
* return values (-o A or RGB or RGBA )
* individual UV coordinates to sample (-u float -v float )
* (numbers of calls to -u and -v must match)
* uniform grid of points to sample (-su int -sv int)
* (may not use this in combination with -u or -v)
* bounds for sample grid (-mu float -mv float -xu float -xv float)
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
u : coordU [float] []
Input u coordinate to sample texture at.
-----------------------------------------
v : coordV [float] []
Input v coordinate to sample texture at.
-----------------------------------------
xu : maxU [float] []
DEFAULT 1.0 Maximum u bounds to sample.
-----------------------------------------
xv : maxV [float] []
DEFAULT 1.0 Maximum v bounds to sample.
-----------------------------------------
mu : minU [float] []
DEFAULT 0.0 Minimum u bounds to sample.
-----------------------------------------
mv : minV [float] []
DEFAULT 0.0 Minimum v bounds to sample.
-----------------------------------------
o : output [string] []
Type of data to output: A = alpha only RGB = color only RGBA = color and alpha
-----------------------------------------
su : samplesU [uint] []
DEFAULT 1 The number of points to sample in the U dimension.
-----------------------------------------
sv : samplesV [uint]
DEFAULT 1 The number of points to sample in the V dimension.
"""
def fluidCacheInfo(q=1,e=1,at="string",t="time",ef=1,hc=1,hd=1,ic=1,pb=1,re=1,sf=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/fluidCacheInfo.html
-----------------------------------------
fluidCacheInfo is undoable, queryable, and editable.
A command to get information about the fluids cache. Get the startFrame and
resolution for InitialConditions. Get the endFrame as well for a playback
cache. Note that for the playback cache, it will look at the current time (or
last frame if the current time is past end of cache)
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] ['query', 'edit']
Modifier to the "hasData" flag, used to query whether a cache has data (at the current time) for a specific fluid attribute. Valid attribute values are "density", "velocity", "temperature", "fuel", "color", "coordinates" (for texture coordinates), "falloff".
-----------------------------------------
t : cacheTime [time] ['query', 'edit']
Only valid with the -hasData flag. The time the -hasData flag uses when it queries the cache to see if there is data.
-----------------------------------------
ef : endFrame [boolean] ['query', 'edit']
Returns end time of cache as float.
-----------------------------------------
hc : hasCache [boolean] ['query', 'edit']
Returns true if fluid has specified cache, false if not.
-----------------------------------------
hd : hasData [boolean] ['query', 'edit']
Queries whether a given cache has data in it at the time specified by the -time flag. (If not -time flag is present, -hasData assumes the current time.) When used with the "attribute" flag, indicates if data for the specified attribute exists in the cache. When used without the "attribute" flag, "hasData" indicates whether there is data in the cache for any of the valid fluid attributes.
-----------------------------------------
ic : initialConditions [boolean] ['query', 'edit']
Specifies the cache to be queried is the "Initial Conditions" cache.
-----------------------------------------
pb : playback [boolean] ['query', 'edit']
Specifies the cache to be queried is the "Playback" cache.
-----------------------------------------
re : resolution [boolean] ['query', 'edit']
Returns cache resolution as float[].
-----------------------------------------
sf : startFrame [boolean]
Returns start time for cache as float.
"""
def fluidEmitter(q=1,e=1,cye="string",cyi="int",der="float",fdr="float",fer="float",her="float",mxd="linear",mnd="linear",n="string",pos="[linear, linear, linear]",r="float",tsr="linear",typ="string",vof="[linear, linear, linear]",vsh="string",vsw="angle"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/fluidEmitter.html
-----------------------------------------
fluidEmitter is undoable, queryable, and editable.
Creates, edits or queries an auxiliary dynamics object (for example, a field
or emitter). Creates an emitter object. If object names are provided or if
objects are selected, applies the emitter to the named/selected object(s)in
the scene. Fluid will then be emitted from each. If no objects are named or
selected, or if the -pos option is specified, creates a positional emitter.
If an emitter was created, the command returns the name of the object owning
the emitter, and the name of emitter shape. If an emitter was queried, the
command returns the results of the query.
-----------------------------------------
Return Value:
string Command result
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
cye : cycleEmission [string] ['query', 'edit']
Possible values are "none" and "frame." Cycling emission restarts the random number stream after a specified interval. This can either be a number of frames or a number of emitted particles. In each case the number is specified by the cycleInterval attribute. Setting cycleEmission to "frame" and cycleInterval to 1 will then re-start the random stream every frame. Setting cycleInterval to values greater than 1 can be used to generate cycles for games work.
-----------------------------------------
cyi : cycleInterval [int] ['query', 'edit']
Specifies the number of frames or particles between restarts of the random number stream. See cycleEmission. Has no effect if cycleEmission is set to None.
-----------------------------------------
der : densityEmissionRate [float] ['query', 'edit']
Rate at which density is emitted.
-----------------------------------------
fdr : fluidDropoff [float] ['query', 'edit']
Fluid Emission Dropoff in volume
-----------------------------------------
fer : fuelEmissionRate [float] ['query', 'edit']
Rate at which is emitted.
-----------------------------------------
her : heatEmissionRate [float] ['query', 'edit']
Rate at which density is emitted.
-----------------------------------------
mxd : maxDistance [linear] ['query', 'edit']
Maximum distance at which emission ends.
-----------------------------------------
mnd : minDistance [linear] ['query', 'edit']
Minimum distance at which emission starts.
-----------------------------------------
n : name [string] ['query', 'edit']
Object name
-----------------------------------------
pos : position [[linear, linear, linear]] ['query', 'edit']
world-space position
-----------------------------------------
r : rate [float] ['query', 'edit']
Rate at which particles emitted (can be non-integer). For point emission this is rate per point per unit time. For surface emission it is rate per square unit of area per unit time.
-----------------------------------------
tsr : torusSectionRadius [linear] ['query', 'edit']
Section radius for a torus volume. Applies only to torus. Similar to the section radius in the torus modelling primitive.
-----------------------------------------
typ : type [string] ['query', 'edit']
Type of emitter. The choices are omni | dir | direction | surf | surface | curve | curv. The default is omni. The full definition of these types are: omnidirectional point emitter, directional point emitter, surface emitter, or curve emitter.
-----------------------------------------
vof : volumeOffset [[linear, linear, linear]] ['query', 'edit']
Volume offset of the emitter. Volume offset translates the emission volume by the specified amount from the actual emitter location. This is in the emitter's local space.
-----------------------------------------
vsh : volumeShape [string] ['query', 'edit']
Volume shape of the emitter. Sets/edits/queries the field's volume shape attribute. If set to any value other than "none", determines a 3-D volume within which particles are generated. Values are: "cube," "sphere," "cylinder," "cone," "torus."
-----------------------------------------
vsw : volumeSweep [angle]
Volume sweep of the emitter. Applies only to sphere, cone, cylinder, and torus. Similar effect to the sweep attribute in modelling.
"""
def fluidVoxelInfo(cb=1,ib="[int, int, int]",os=1,r="float",v="[float, float, float]",vc=1,xi="int",yi="int",zi="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/fluidVoxelInfo.html
-----------------------------------------
fluidVoxelInfo is NOT undoable, NOT queryable, and NOT editable.
Provides basic information about the mapping of a fluid voxel grid into world-
or object space of the fluid. Use this command to determine the center point
of a voxel, or to find the voxel containing a given point, among other things.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
cb : checkBounds [boolean] []
If this flag is on, and the voxel index of a point that is out of bounds is requested, then we return nothing.
-----------------------------------------
ib : inBounds [[int, int, int]] []
Are the three ints representing the x, y, z indices of a voxel within the bounds of the fluid's voxel grid? True if yes, false if not. (For 2D fluids, pass in z=0 for the third argument. See examples.)
-----------------------------------------
os : objectSpace [boolean] []
Whether the queried value should be returned in object space (TRUE), or world space (FALSE, the default).
-----------------------------------------
r : radius [float] []
Modifier for the -voxel flag. Returns a list of index triples identifying voxels that fall within the given radius of the point specified by the -voxel flag.
-----------------------------------------
v : voxel [[float, float, float]] []
Returns array of three ints representing the x, y, z indices of the voxel within which the given point position is contained. If the checkBounds flag is on, and the point is out of bounds, we return nothing. Otherwise, even if the point is out of bounds, index values are returned. When combined with the -radius flag, returns an array of index triples representing a list of voxels within a given radius of the given point position.
-----------------------------------------
vc : voxelCenter [boolean] []
The center position of the specified voxels. Returns an array of floats (three for each of the indices in the query). (Valid only with the -xIndex, -yIndex, and -zIndex flags.)
-----------------------------------------
xi : xIndex [int] []
Only return values for cells with this X index
-----------------------------------------
yi : yIndex [int] []
Only return values for cells with this Y index
-----------------------------------------
zi : zIndex [int]
Only return values for cells with this Z index
"""
def getFluidAttr(at="string",lf=1,xi="int",x=1,yi="int",y=1,zi="int",z=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/getFluidAttr.html
-----------------------------------------
getFluidAttr is NOT undoable, NOT queryable, and NOT editable.
Returns values of built-in fluid attributes such as density, velocity, etc.,
for individual grid cells or for all cells in the grid.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
at : attribute [string] []
Specifies the fluid attribute for which to display values. Valid attributes are "force", "velocity", "density", "falloff", "fuel", "color", and "temperature". (Note that getting force values is an alternate way of getting velocity values at one time step.)
-----------------------------------------
lf : lowerFace [boolean] []
Only valid with "-at velocity". Since velocity values are stored on the edges of each voxel and not at the center, using voxel based indices to set velocity necessarily affects neighboring voxels. Use this flag to only set velocity components on the lower left three faces of a voxel, rather than all six.
-----------------------------------------
xi : xIndex [int] []
Only return values for cells with this X index
-----------------------------------------
x : xvalue [boolean] []
Only get the first component of the vector-valued attribute specified by the "-at/attribute" flag.
-----------------------------------------
yi : yIndex [int] []
Only return values for cells with this Y index
-----------------------------------------
y : yvalue [boolean] []
Only get the second component of the vector-valued attribute specified by the "-at/attribute" flag.
-----------------------------------------
zi : zIndex [int] []
Only return values for cells with this Z index
-----------------------------------------
z : zvalue [boolean]
Only get the third component of the vector-valued attribute specified by the "-at/attribute" flag.
"""
def loadFluid(q=1,e=1,ct=1,f="float",ic=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/loadFluid.html
-----------------------------------------
loadFluid is undoable, queryable, and editable.
A command to set builtin fluid attributes such as Density, Velocity, etc for
all cells in the grid from the initial state cache
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ct : currentTime [boolean] ['query', 'edit']
This flag is now obsolete. Move the cache clip in the Trax editor to view different frames of the playback cache.
-----------------------------------------
f : frame [float] ['query', 'edit']
This flag is now obsolete. Move the cache clip in the Trax editor to view different frames of the playback cache.
-----------------------------------------
ic : initialConditions [boolean]
load initial conditions cache
"""
def resampleFluid(q=1,e=1,rd="int",rh="int",rw="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/resampleFluid.html
-----------------------------------------
resampleFluid is undoable, queryable, and editable.
A command to extend the fluid grid, keeping the voxels the same size, and
keeping the existing contents of the fluid in the same place. Note that the
fluid transform is also modified to make this possible.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
rd : resampleDepth [int] ['query', 'edit']
Change depth resolution to this value
-----------------------------------------
rh : resampleHeight [int] ['query', 'edit']
Change height resolution to this value
-----------------------------------------
rw : resampleWidth [int]
Change width resolution to this value
"""
def saveFluid(q=1,e=1,ct="int",et="int",st="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/saveFluid.html
-----------------------------------------
saveFluid is undoable, queryable, and editable.
A command to save the current state of the fluid to the initial state cache.
The grids to be saved are determined by the cache attributes: cacheDensity,
cacheVelocity, etc. These attributes are normally set from the options on Set
Initial State. The cache must be set up before invoking this command.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
-----------------------------------------
Flags:
-----------------------------------------
ct : currentTime [int] ['query', 'edit']
cache state of fluid at current time
-----------------------------------------
et : endTime [int] ['query', 'edit']
end Time for cacheing
-----------------------------------------
st : startTime [int]
start Time for cacheing
"""
def setFluidAttr(ad=1,at="string",cl=1,fr="float",fv="float",lf=1,re=1,vr="[float, float, float]",vv="[float, float, float]",xi="int",x=1,yi="int",y=1,zi="int",z=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/setFluidAttr.html
-----------------------------------------
setFluidAttr is NOT undoable, NOT queryable, and NOT editable.
Sets values of built-in fluid attributes such as density, velocity, etc., for
individual grid cells or for all cells in the grid.
-----------------------------------------
Return Value:
None
-----------------------------------------
Flags:
-----------------------------------------
ad : addValue [boolean] []
Add specified value to attribute
-----------------------------------------
at : attribute [string] []
Specifies the fluid attribute for which to set values. Valid attributes are "velocity", "density", "fuel", "color", "falloff", and "temperature".
-----------------------------------------
cl : clear [boolean] []
Set this attribute to 0
-----------------------------------------
fr : floatRandom [float] []
If this was a scalar (e.g. density) attribute, use a random value in +-VALUE If fv is specified, it is used as the base value and combined with the random value. If the fv flag is not specified, the base is assumed to be 0.
-----------------------------------------
fv : floatValue [float] []
If this was a scalar (e.g. density) attribute, use this value
-----------------------------------------
lf : lowerFace [boolean] []
Only valid with "-at velocity". Since velocity values are stored on the edges of each voxel and not at the center, using voxel based indices to set velocity necessarily affects neighboring voxels. Use this flag to only set velocity components on the lower left three faces of a voxel, rather than all six.
-----------------------------------------
re : reset [boolean] []
Set this attribute to default value
-----------------------------------------
vr : vectorRandom [[float, float, float]] []
If this was a vector (e.g. velocity) attribute, use a random value in +-VALUE If vv is specified, it is used as the base value and combined with the random value. If the vv flag is not specified, the base is assumed to be 0,0,0.
-----------------------------------------
vv : vectorValue [[float, float, float]] []
If this was a vector (e.g. velocity) attribute, use this value
-----------------------------------------
xi : xIndex [int] []
Only return values for cells with this X index
-----------------------------------------
x : xvalue [boolean] []
Only set the first component of the vector-valued attribute specified by the "-at/attribute" flag.
-----------------------------------------
yi : yIndex [int] []
Only return values for cells with this Y index
-----------------------------------------
y : yvalue [boolean] []
Only set the second component of the vector-valued attribute specified by the "-at/attribute" flag.
-----------------------------------------
zi : zIndex [int] []
Only return values for cells with this Z index
-----------------------------------------
z : zvalue [boolean]
Only set the third component of the vector-valued attribute specified by the "-at/attribute" flag.
"""
def truncateFluidCache(q=1,e=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/truncateFluidCache.html
-----------------------------------------
truncateFluidCache is undoable, queryable, and editable.
This command sets the end time of a fluid cache to the current time. If the
current time is less than the end time of the cache, the cache is truncated so
that only the portion of the cache up to and including the current time is
preserved.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
"""
def truncateHairCache(q=1,e=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/truncateHairCache.html
-----------------------------------------
truncateHairCache is undoable, queryable, and editable.
This command sets the end time of a hair cache to the current time. If the
current time is less than the end time of the cache, the cache is truncated so
that only the portion of the cache up to and including the current time is
preserved.
-----------------------------------------
Return Value:
None
In query mode, return type is based on queried flag.
"""
|
# -*- coding: utf-8 -*-
VOICE_DATA = [
{
"Id": "Joanna",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Female",
"Name": "Joanna",
},
{
"Id": "Mizuki",
"LanguageCode": "ja-JP",
"LanguageName": "Japanese",
"Gender": "Female",
"Name": "Mizuki",
},
{
"Id": "Filiz",
"LanguageCode": "tr-TR",
"LanguageName": "Turkish",
"Gender": "Female",
"Name": "Filiz",
},
{
"Id": "Astrid",
"LanguageCode": "sv-SE",
"LanguageName": "Swedish",
"Gender": "Female",
"Name": "Astrid",
},
{
"Id": "Tatyana",
"LanguageCode": "ru-RU",
"LanguageName": "Russian",
"Gender": "Female",
"Name": "Tatyana",
},
{
"Id": "Maxim",
"LanguageCode": "ru-RU",
"LanguageName": "Russian",
"Gender": "Male",
"Name": "Maxim",
},
{
"Id": "Carmen",
"LanguageCode": "ro-RO",
"LanguageName": "Romanian",
"Gender": "Female",
"Name": "Carmen",
},
{
"Id": "Ines",
"LanguageCode": "pt-PT",
"LanguageName": "Portuguese",
"Gender": "Female",
"Name": "Inês",
},
{
"Id": "Cristiano",
"LanguageCode": "pt-PT",
"LanguageName": "Portuguese",
"Gender": "Male",
"Name": "Cristiano",
},
{
"Id": "Vitoria",
"LanguageCode": "pt-BR",
"LanguageName": "Brazilian Portuguese",
"Gender": "Female",
"Name": "Vitória",
},
{
"Id": "Ricardo",
"LanguageCode": "pt-BR",
"LanguageName": "Brazilian Portuguese",
"Gender": "Male",
"Name": "Ricardo",
},
{
"Id": "Maja",
"LanguageCode": "pl-PL",
"LanguageName": "Polish",
"Gender": "Female",
"Name": "Maja",
},
{
"Id": "Jan",
"LanguageCode": "pl-PL",
"LanguageName": "Polish",
"Gender": "Male",
"Name": "Jan",
},
{
"Id": "Ewa",
"LanguageCode": "pl-PL",
"LanguageName": "Polish",
"Gender": "Female",
"Name": "Ewa",
},
{
"Id": "Ruben",
"LanguageCode": "nl-NL",
"LanguageName": "Dutch",
"Gender": "Male",
"Name": "Ruben",
},
{
"Id": "Lotte",
"LanguageCode": "nl-NL",
"LanguageName": "Dutch",
"Gender": "Female",
"Name": "Lotte",
},
{
"Id": "Liv",
"LanguageCode": "nb-NO",
"LanguageName": "Norwegian",
"Gender": "Female",
"Name": "Liv",
},
{
"Id": "Giorgio",
"LanguageCode": "it-IT",
"LanguageName": "Italian",
"Gender": "Male",
"Name": "Giorgio",
},
{
"Id": "Carla",
"LanguageCode": "it-IT",
"LanguageName": "Italian",
"Gender": "Female",
"Name": "Carla",
},
{
"Id": "Karl",
"LanguageCode": "is-IS",
"LanguageName": "Icelandic",
"Gender": "Male",
"Name": "Karl",
},
{
"Id": "Dora",
"LanguageCode": "is-IS",
"LanguageName": "Icelandic",
"Gender": "Female",
"Name": "Dóra",
},
{
"Id": "Mathieu",
"LanguageCode": "fr-FR",
"LanguageName": "French",
"Gender": "Male",
"Name": "Mathieu",
},
{
"Id": "Celine",
"LanguageCode": "fr-FR",
"LanguageName": "French",
"Gender": "Female",
"Name": "Céline",
},
{
"Id": "Chantal",
"LanguageCode": "fr-CA",
"LanguageName": "Canadian French",
"Gender": "Female",
"Name": "Chantal",
},
{
"Id": "Penelope",
"LanguageCode": "es-US",
"LanguageName": "US Spanish",
"Gender": "Female",
"Name": "Penélope",
},
{
"Id": "Miguel",
"LanguageCode": "es-US",
"LanguageName": "US Spanish",
"Gender": "Male",
"Name": "Miguel",
},
{
"Id": "Enrique",
"LanguageCode": "es-ES",
"LanguageName": "Castilian Spanish",
"Gender": "Male",
"Name": "Enrique",
},
{
"Id": "Conchita",
"LanguageCode": "es-ES",
"LanguageName": "Castilian Spanish",
"Gender": "Female",
"Name": "Conchita",
},
{
"Id": "Geraint",
"LanguageCode": "en-GB-WLS",
"LanguageName": "Welsh English",
"Gender": "Male",
"Name": "Geraint",
},
{
"Id": "Salli",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Female",
"Name": "Salli",
},
{
"Id": "Kimberly",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Female",
"Name": "Kimberly",
},
{
"Id": "Kendra",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Female",
"Name": "Kendra",
},
{
"Id": "Justin",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Male",
"Name": "Justin",
},
{
"Id": "Joey",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Male",
"Name": "Joey",
},
{
"Id": "Ivy",
"LanguageCode": "en-US",
"LanguageName": "US English",
"Gender": "Female",
"Name": "Ivy",
},
{
"Id": "Raveena",
"LanguageCode": "en-IN",
"LanguageName": "Indian English",
"Gender": "Female",
"Name": "Raveena",
},
{
"Id": "Emma",
"LanguageCode": "en-GB",
"LanguageName": "British English",
"Gender": "Female",
"Name": "Emma",
},
{
"Id": "Brian",
"LanguageCode": "en-GB",
"LanguageName": "British English",
"Gender": "Male",
"Name": "Brian",
},
{
"Id": "Amy",
"LanguageCode": "en-GB",
"LanguageName": "British English",
"Gender": "Female",
"Name": "Amy",
},
{
"Id": "Russell",
"LanguageCode": "en-AU",
"LanguageName": "Australian English",
"Gender": "Male",
"Name": "Russell",
},
{
"Id": "Nicole",
"LanguageCode": "en-AU",
"LanguageName": "Australian English",
"Gender": "Female",
"Name": "Nicole",
},
{
"Id": "Vicki",
"LanguageCode": "de-DE",
"LanguageName": "German",
"Gender": "Female",
"Name": "Vicki",
},
{
"Id": "Marlene",
"LanguageCode": "de-DE",
"LanguageName": "German",
"Gender": "Female",
"Name": "Marlene",
},
{
"Id": "Hans",
"LanguageCode": "de-DE",
"LanguageName": "German",
"Gender": "Male",
"Name": "Hans",
},
{
"Id": "Naja",
"LanguageCode": "da-DK",
"LanguageName": "Danish",
"Gender": "Female",
"Name": "Naja",
},
{
"Id": "Mads",
"LanguageCode": "da-DK",
"LanguageName": "Danish",
"Gender": "Male",
"Name": "Mads",
},
{
"Id": "Gwyneth",
"LanguageCode": "cy-GB",
"LanguageName": "Welsh",
"Gender": "Female",
"Name": "Gwyneth",
},
{
"Id": "Jacek",
"LanguageCode": "pl-PL",
"LanguageName": "Polish",
"Gender": "Male",
"Name": "Jacek",
},
]
# {...} is also shorthand set syntax
LANGUAGE_CODES = {
"cy-GB",
"da-DK",
"de-DE",
"en-AU",
"en-GB",
"en-GB-WLS",
"en-IN",
"en-US",
"es-ES",
"es-US",
"fr-CA",
"fr-FR",
"is-IS",
"it-IT",
"ja-JP",
"nb-NO",
"nl-NL",
"pl-PL",
"pt-BR",
"pt-PT",
"ro-RO",
"ru-RU",
"sv-SE",
"tr-TR",
}
VOICE_IDS = {
"Geraint",
"Gwyneth",
"Mads",
"Naja",
"Hans",
"Marlene",
"Nicole",
"Russell",
"Amy",
"Brian",
"Emma",
"Raveena",
"Ivy",
"Joanna",
"Joey",
"Justin",
"Kendra",
"Kimberly",
"Salli",
"Conchita",
"Enrique",
"Miguel",
"Penelope",
"Chantal",
"Celine",
"Mathieu",
"Dora",
"Karl",
"Carla",
"Giorgio",
"Mizuki",
"Liv",
"Lotte",
"Ruben",
"Ewa",
"Jacek",
"Jan",
"Maja",
"Ricardo",
"Vitoria",
"Cristiano",
"Ines",
"Carmen",
"Maxim",
"Tatyana",
"Astrid",
"Filiz",
}
|
for i in range(10000000):
str_i = str(i)
s1 = 'ABCDEFH' + str_i
s2 = '123456789' + str_i
result = ''
x = 0
if len(s1) < len(s2):
while x < len(s1):
result += s1[x] + s2[x]
x += 1
result += s2[x:]
else:
while x < len(s2):
result += s1[x] + s2[x]
x += 1
result += s1[x:]
if i == 0: print(result)
|
class parent:
counter=10
hit=15
def __init__(self):
print("Parent class initialized.")
def SetCounter(self, num):
self.counter= num
class child(parent): # child is the child class of Parent
def __init__(self):
print("Child class being initialized.")
def SetHit(self, num2):
self.hit=num2
c= child()
print(c.counter)
c.SetCounter(20)
print(c.counter)
print(c.hit)
c.SetHit(30)
print(c.hit)
|
class Node:
def __init__(self, data=None , next_ref=None):
self.data = data
self.next = next_ref
class Stack:
def __init__(self, data=None):
self.__top= None
self.__size = 0
if data:
node = Node(data)
self.__top = node
self.__size = 1
def push(self, data):
node = Node(data,self.__top)
self.__top = node
self.__size += 1
def pop(self):
if self.__top:
value = self.__top.data
self.__top = self.__top.next
self.__size -= 1
return value
else:
raise IndexError('Stack is Empty')
def peek(self):
return self._Stack__top
def search(self, value):
# current = self.__top
# while current:
# if current.data == value:
# return True
# current = current.next
# return False
for data in self.iter():
if data == value:
return True
return False
def get_size(self):
return self.__size
def iter(self):
current = self.__top
while current:
value = current.data
current = current.next
yield value
def clear(self):
self.__top = None
self.__size = 0
def test():
print('Creating a Empty with first value as 1')
my_stack = Stack(1)
print('Adding vlaue 2 3 4 5 6 7 respectively to my_stack')
my_stack.push(2)
my_stack.push(3)
my_stack.push(4)
my_stack.push(5)
my_stack.push(6)
my_stack.push(7)
assert my_stack.get_size() == 7
print('-'*60)
print('print the stack from top to bottom with top being considered as index 1')
i = 0
for value in my_stack.iter():
i +=1
print('Index is %d and value is -> %d'%(i,value))
print('-'*60)
print('Performing the pop opeartion over the stack')
print(my_stack.pop())
assert my_stack.get_size() == 6
print('-'*60)
print('RE-print the stack after one pop operation, with top being considered as index 1')
i = 0
for value in my_stack.iter():
i +=1
print('Index is %d and value is -> %d'%(i,value))
print('-'*60)
print('search a value or to check the presence of a element in stack')
print(my_stack.search(5))
assert my_stack.search(5)
assert not my_stack.search(15)
print('-'*60)
print('Get the size/length / number of element in a stack')
print(my_stack.get_size())
assert my_stack.get_size() == 6
print('-'*60)
print('Clear the stack')
my_stack.clear()
# assert my_stack._Stack__top is None
assert my_stack.get_size() == 0
# Must return our Assert Error of stack is Empty
# print(my_stack.pop())
# test() |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode) -> ListNode:
value = 0
currentNode = head
while currentNode!=None :
node = currentNode
while node.next!=None:
if node.next.value == currentNode.value:
node.next = node.next.next
else:node = node.next
currentNode = currentNode.next
return head
|
__title__ = 'ki'
__version__ = '1.1.0'
__author__ = 'Joshua Scott & Caleb Pina'
__description__ = 'Python bindings and extensions for libki'
|
# filename : Graph.py
# ------------------------------------------------------------------------------------
class Graph:
def __init__(self, number_of_vertex, number_of_edges, is_directed = False, is_weighted = False):
self.number_of_vertices = number_of_vertex
self.number_of_edges = number_of_edges
self.is_directed = is_directed
self.is_weighted = is_weighted
self.graph_list = [[] for i in range(self.number_of_vertices)]
self.initGraph() # initlize the Graph.
def initGraph(self):
for egde in range(self.number_of_edges):
edge_data = list(map(input("").split(" "), int()))
if not self.is_weighted:
start = edge_data[0]
end = edge_data[1]
self.graph_list[start-1].append(end - 1)
else:
# TODO : Work on Weighted Graph or make a seprate class for it, with different initGraph method.
pass
# -------------------------------------------------------------------------------------------
class GraphNode:
def __init__(self):
self.start = None
self.end = None
self.weight = None
|
"""
Authors
-------
Dr. Randal J. Barnes
Department of Civil, Environmental, and Geo- Engineering
University of Minnesota
Richard Soule
Source Water Protection
Minnesota Department of Health
Version
-------
06 May 2020
"""
PROJECTNAME = 'Carlos example'
TARGET = 0
NPATHS = 500
DURATION = 10*365.25
BASE = 0.0
CONDUCTIVITY = 15.2
POROSITY = 0.25
THICKNESS = 25
BUFFER = 100
SPACING = 1
UMBRA = 2
CONFINED = True
TOL = 1
MAXSTEP = 5
WELLS = [(322579, 5093431, 0.2, 179)]
OBSERVATIONS = [
(324125, 5094758.0, 413.0040, 1.6),
(322332, 5093693.0, 411.7848, 1.6),
(322636, 5094024.0, 410.8704, 1.6),
(323438, 5092221.0, 419.1000, 1.6),
(322474, 5092682.0, 415.7472, 1.6),
(323402, 5092650.0, 420.0000, 1.5),
(324334, 5092974.0, 423.0000, 1.5),
(324201, 5092476.0, 421.0000, 1.5),
(321612, 5092354.0, 418.0000, 1.5),
(321739, 5093159.0, 414.0000, 1.5),
(321820, 5093298.0, 414.0000, 1.5),
(323384, 5094353.0, 415.0000, 1.5),
(323060, 5091983.0, 423.0000, 1.5)
]
|
"""
Stack data structure is optimized for quick appends (push) and removal of the last
node (pop)
"""
class Node:
"""Node is a simple data structure holding information"""
def __init__(self, value, node):
self.__value = value
self.__next = node
@property
def value(self):
"""Returns the stored value"""
return self.__value
@property
def next(self):
"""Returns the next node"""
return self.__next
def set_next(self, node):
"""Set the node to next"""
if isinstance(node, Node):
self.__next = node
else:
raise Exception("Not a node instance")
def create_node(value, next_node):
"""Factory function to create a node with value & next"""
return Node(value, next_node)
class Stack:
"""Datastructure for LIFO"""
def __init__(self):
self.__size = 0
self.__head = None
def __len__(self):
return self.__size
def __str__(self):
values = []
curr_node = self.__head
while isinstance(curr_node, Node):
values.append(str(curr_node.value))
curr_node = curr_node.next
return "->".join(values)
def push(self, value):
"""Push the value on to the stack"""
new_node = create_node(value, self.__head)
self.__head = new_node
self.__size += 1
def pop(self):
"""Remove the value from the top"""
if self.__head is None:
return None
else:
value = self.__head.value
self.__head = self.__head.next
self.__size -= 1
return value
def create_stack():
"""Factory function to create a stack"""
return Stack()
def test_simple_stack():
"""Simple visual test for stack"""
stack = create_stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
if __name__ == "__main__":
test_simple_stack()
|
"""
Module cannot be called tool_shed, because this conflicts with lib/tool_shed
also at top level of path.
"""
|
# -*- coding: utf-8 -*-
"""
Unit test package for utils.
"""
|
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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.
"""
class Job(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type.
:param dict attributeMap: The key is attribute name and the value is json key in definition.
"""
self.swagger_types = {
'id': 'str',
'token': 'str',
'type': 'str',
'status': 'Status',
'process': 'bool',
'conversion': 'list[Conversion]',
'input': 'list[InputFile]',
'callback': 'str',
'server': 'str',
'created_at': 'DateTime',
'modified_at': 'DateTime'
}
self.attribute_map = {
'id': 'id',
'token': 'token',
'type': 'type',
'status': 'status',
'process': 'process',
'conversion': 'conversion',
'input': 'input',
'callback': 'callback',
'server': 'server',
'created_at': 'created_at',
'modified_at': 'modified_at'
}
# Unique identifier for the job.
self.id = None # str
# Token to identify client allowed to run the job.
self.token = None # str
# Type of the job created.
self.type = None # str
# Current status for the job
self.status = None # Status
# Determine if the job must be processed as soon as it is ready.
self.process = None # bool
# Type of conversion or conversions to be carried out.
self.conversion = None # list[Conversion]
# Source or sources of the files to be converted.
self.input = None # list[InputFile]
# Callback url to the the status updates
self.callback = None # str
# Server assigned for file uploads and downloads
self.server = None # str
# Date and time when the job was created.
self.created_at = None # DateTime
# Date and time when the job was last modified.
self.modified_at = None # DateTime
def __repr__(self):
properties = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
|
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
n_s = len(s)
n_star = 0
seg = []
i = len(p) - 1
while i > -1:
if p[i] == '*':
n_star += 1
seg.insert(0, p[i - 1:i + 1])
i -= 2
else:
seg.insert(0, p[i])
i -= 1
n_p = len(p) - n_star
m, n = n_p + 1, n_s + 1
dp = [[False for j in xrange(n)] for i in xrange(m)]
dp[0][0] = True
for i in xrange(1, m):
if len(seg[i - 1]) == 2:
dp[i][0] = True
else:
break
for i in xrange(1, m):
for j in xrange(1, n):
if dp[i][j - 1] and len(seg[i - 1]) == 2 and (seg[i - 1][0] == '.' or seg[i - 1][0] == s[j - 1]):
dp[i][j] = True
continue
if dp[i - 1][j] and len(seg[i - 1]) == 2:
dp[i][j] = True
continue
if dp[i - 1][j - 1] and (seg[i - 1][0] == '.' or seg[i - 1][0] == s[j - 1]):
dp[i][j] = True
continue
return dp[-1][-1]
|
class SimulationNotFinished(Exception):
def __init__(self, keyword):
super().__init__(
"Run simulation first before using `{}` method.".format(keyword)
)
class DailyReturnsNotRegistered(Exception):
def __init__(self):
super().__init__("Daily returns data have not yet registered.")
|
''' Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se encontram no
intervalo de 1 até 500.'''
print('\033[1;33m-=\033[m' * 20)
soma = 0
contador = 0
for c in range(1, 501, 2):
if c % 3 == 0:
contador += 1
soma += c
print('\033[35mExiste\033[m {}{}{} \033[35mnúmeros entre 1 e 500 que são impares e múltiplos de três a soma deles e\033[m {}{}{}'.format('\033[34m', contador, '\033[m', '\033[34m', soma, '\033[m'))
print('\033[1;33m-=\033[m' * 20)
### Outro metodo
'''
print('\033[1;33m-=\033[m' * 20)
soma = 0
for c in range(1, 501):
if c % 2 != 0 and c % 3 == 0:
soma = soma + c
print('\033[35mA Soma entre todos os números entre 1 e 500 que são impares e múltiplos de três é\033[m {}{}{}'.format('\033[34m', soma, '\033[m'))
print('\033[1;33m-=\033[m' * 20)
'''
|
def test_sm_tatneft_include_eic_yestoday(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(3, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 50
def test_sm_tatneftt_without_eic_yestoday(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(3, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.find_in_container_number(11, 2, 1)
app.testHelperSMSearch.find_in_container_number(11, 6, 3)
app.testHelperSMSearch.find_in_container_number(11, 6, 4)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 50
def test_sm_tatneft_include_eic_yestoday_today(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(11, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 50
def test_sm_tatneft_without_eic_yestoday_today(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(11, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.find_in_container_number(11, 2, 1)
app.testHelperSMSearch.find_in_container_number(11, 6, 3)
app.testHelperSMSearch.find_in_container_number(11, 6, 4)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 50
def test_sm_tatneft_include_eic_7_days(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(4, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 250
def test_sm_tatneft_without_eic_7_days(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(4, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.find_in_container_number(11, 2, 1)
app.testHelperSMSearch.find_in_container_number(11, 6, 3)
app.testHelperSMSearch.find_in_container_number(11, 6, 4)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 250
def test_sm_tatneft_include_eic_current_month(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(5, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > int(app.testHelperSMSearch.current_date_time_day())*30
def test_sm_tatneft_without_eic_current_month(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(5, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.find_in_container_number(11, 2, 1)
app.testHelperSMSearch.find_in_container_number(11, 6, 3)
app.testHelperSMSearch.find_in_container_number(11, 6, 4)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > int(app.testHelperSMSearch.current_date_time_day())*30
def test_sm_tatneft_include_eic_prev_month(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(6, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 1200
def test_sm_tatneft_without_eic_prev_month(app):
app.testhelpersm.refresh_page()
app.session.open_SM_page(app.smPurchases)
app.session.ensure_login_sm(app.username, app.password)
app.session.ensure_login_sm(app.username, app.password)
app.session.open_SM_page(app.smPurchases)
app.testHelperSMSearch.expand_show_hide()
# Искать в контейнере (всего контейнеров + 1, номер контейнера(если 0 - случайный выбор), номер строки
# в контейнере если 0 - случайный выбор)
name = 'ТАТНЕФТЬ'
app.testHelperSMSearch.select_first_publish_date(6, 0)
app.testHelperSMSearch.find_torgovaya_ploschadka(name)
app.testHelperSMSearch.find_in_container_number(11, 2, 1)
app.testHelperSMSearch.find_in_container_number(11, 6, 3)
app.testHelperSMSearch.find_in_container_number(11, 6, 4)
app.testHelperSMSearch.press_search_button()
assert app.testHelperSMSearch.check_results() != '0'
assert int(app.testHelperSMSearch.check_results()) > 1200 |
# Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# Equilátero: todos os lados iguais.
# Isósceles: dois lados iguais.
# Escaleno: todos os lados diferentes.
reta1 = float(input('Digite o valor da reta 1: '))
reta2 = float(input('Digite o valor da reta 2: '))
reta3 = float(input('Digite o valor da reta 3: '))
if reta1 + reta2 > reta3 and reta1 + reta3 > reta2 and reta2 + reta3 > reta1:
print('Formam um triângulo? SIM')
if reta1 != reta2 and reta2 != reta3 and reta3 != reta1:
print('Escaleno')
elif reta1 == reta2 and reta2 == reta3 and reta3 == reta1:
print('Equilátero')
else:
print('Isósceles')
else:
print('Formam um triângulo? NÃO')
|
"""
SOLUTIONS ROBUST ARE ON GITHUB RAFFSON (OPLEIDER)
"""
mood = input("What is your mood? :")
mood = mood.lower()
if mood == "happy":
print("It is great to see you happy!")
elif mood == "nervous":
print("Take a deep breath 3 times.")
elif mood == "sad":
print("Cheer up, mate!")
elif mood == "excited":
print("Going great!")
elif mood == "relaxed":
print("Taking it slow")
else:
print("I don't recognize this mood")
|
print('=-'*20)
numero = int(input('Digite o número que deseja ver a tabuada: '))
print('=-'*20)
for c in range(1, 11):
print('{} X {} = {}'.format(c, numero, numero * c))
|
class FilterGroupController:
def __init__(self, filterGroups):
self.filterGroups = filterGroups
def sendCoT(self, CoT):
pass
def addUser(self, clientInformation):
pass
def removeUser(self, clientInformation):
pass |
class Solution:
def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
prefix, n, res, left = [0 for _ in range(len(A) + 1)], len(A) + 1, 0, 0
for i in range(1, n):
prefix[i] = prefix[i - 1] + A[i - 1]
for i in range(L + M, n):
left = max(left, prefix[i - M] - prefix[i - M - L])
res = max(res, left + prefix[i] - prefix[i - M])
left = 0
for i in range(L + M, n):
left = max(left, prefix[i - L] - prefix[i - M - L])
res = max(res, left + prefix[i] - prefix[i - L])
return res
|
numbers = """
123.456,789|012,345+678 901
"""
print(numbers.split())
print(numbers.split(","))
separators = ".,|+ "
op = "".join(char if char not in separators else " " for char in numbers).split()
print(op)
|
valores = input().split()
valores = list(map(int,valores))
A, B = valores
if (B%A == 0) or (A%B == 0):
print('Sao Multiplos')
else:
print('Nao sao Multiplos') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
extract statistics from github repos
"""
__version__ = "1.0"
name = "github_stats"
|
def search(str, lst, size):
for i in range(0, size):
if lst[i] == str:
return i
return -1
print(search("a", ["a", "b", "c"], 3))
print(search("b", ["a", "b", "c"], 3))
print(search("c", ["a", "b", "c"], 3))
print(search("d", ["a", "b", "c"], 3))
|
class Renderer:
def __init__(self):
self.render_queue = Queue()
"""
the renderer stores all of the shapes
and renders them on the screen inside the view
the render_queue
[node] -> [node] -> [node]
"""
|
#!/usr/bin/env python3
def divisor(n):
num = 0
i = 1
while i * i <= n:
if n % i == 0:
num += 2
i += 1
if i * i == n:
num -= 1
return num
def main():
i = 1
sum = 0
while True:
sum = divisor(i*(i+1)/2)
if sum >= 500:
print((sum, i*(i+1)/2))
break
i += 1
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
#TODO this could probably just be a list.
digits = {
"0" : True,
"1" : True,
"2" : True,
"3" : True,
"4" : True,
"5" : True,
"6" : True,
"7" : True,
"8" : True,
"9" : True
}
#TODO this could probably just be a list.
lowercaseletters = {
"a" : True,
"b" : True,
"c" : True,
"d" : True,
"e" : True,
"f" : True,
"g" : True,
"h" : True,
"i" : True,
"j" : True,
"k" : True,
"l" : True,
"m" : True,
"n" : True,
"o" : True,
"p" : True,
"q" : True,
"r" : True,
"s" : True,
"t" : True,
"u" : True,
"v" : True,
"w" : True,
"x" : True,
"y" : True,
"z" : True,
"á" : True,
"é" : True,
"í" : True,
"ó" : True,
"ú" : True,
"ḃ" : True,
"ċ" : True,
"ḋ" : True,
"ḟ" : True,
"ġ" : True,
"ṁ" : True,
"ṗ" : True,
"ṡ" : True,
"ṫ" : True,
"ɼ" : True,
"ſ" : True,
"ẛ" : True
}
alternatelowercaseletters = {
"ɼ" : True,
"ſ" : True,
"ẛ" : True
}
de_punc = {
":" : "colon",
";" : "semicolon",
"," : "comma",
"." : "period",
"?" : "question",
"!" : "exclamation",
"-" : "dash",
"'" : "apostrophe",
"’" : "rightsinglequote",
'"' : "doublequote",
'“' : "leftdoublequote",
'”' : "rightdoublequote",
'⁊' : "Tironian-et",
'(' : "leftparen",
')' : "rightparen",
'[' : "leftbracket",
']' : "righbracket",
}
de_accent = {
"á" : "a",
"é" : "e",
"í" : "i",
"ó" : "o",
"ú" : "u",
"Á" : "A",
"É" : "E",
"Í" : "I",
"Ó" : "O",
"Ú" : "U"
}
de_dot = {
"ḃ" : "b",
"ċ" : "c",
"ḋ" : "d",
"ḟ" : "f",
"ġ" : "g",
"ṁ" : "m",
"ṗ" : "p",
"ṡ" : "s",
"ṫ" : "t",
"Ḃ" : "B",
"Ċ" : "C",
"Ḋ" : "D",
"Ḟ" : "F",
"Ġ" : "G",
"Ṁ" : "M",
"Ṗ" : "P",
"Ṡ" : "S",
"Ṫ" : "T",
"ẛ" : "ſ"
}
de_alternatelc = {
"ɼ" : "r",
"ſ" : "s",
"ẛ" : "ṡ"
}
def isdigit(c):
if c in digits:
return True
else:
return False
def islowercase(c):
if c in lowercaseletters:
return True
else:
return False
def isalternatelowercase(c):
if c in alternatelowercaseletters:
return True
else:
return False
def punctuation(c):
if c in de_punc:
return True
else:
return False
def dotted(c):
if c in de_dot:
return True
else:
return False
def accented(c):
if c in de_accent:
return True
else:
return False
def lettername(c):
letter = c
diacritical = ""
size = ""
alternate = ""
if isalternatelowercase(c):
alternate = "-alt"
c = de_alternatelc[c]
letter = c
if accented(c):
diacritical = "-accent"
letter = de_accent[c]
if dotted(c):
diacritical = "-dot"
letter = de_dot[c]
if punctuation(c):
letter = de_punc[c]
else:
if islowercase(c):
size = "-small"
else:
if not isdigit(c):
size = "-caps"
return letter+size+alternate+diacritical
|
# Individuals Script Runs
Y = True
N = False
topics_run = Y
groups_run = Y
events_and_members_run = Y
events_run = Y
members_run = Y
rsvps_run = Y
# Topics searches by keyword query
# topics = ['innovation']
topics = ['startups','entrepreneurship','innovation']
topics_per_page=20
# topics_offset=0 n/a
# How many topics are returned for group search
topic_order = 'ASC' #ASC or DESC
topic_limit = 100
groups_order = 'DESC'
groups_limit=1000
groups_per_page=200
groups_offset=0
#city,state,country, lat, lon, radius(miles)
# cities =[
# ["Vancouver","BC","CA",49.28,-123.11,10],
# # ["Calgary","AB","CA",51.05,-114.07,10],
# # ["Montreal","QC","CA",45.50,-73.57,10],
# # ["Toronto","ON","CA",43.65,-79.38,10],
# ]
event_statuses = ["past","upcoming"]
events_per_page=200
events_offset=0
members_per_page=100
members_offset=0
rsvps_per_page=200
rsvps_offset=0
|
class A:
def __init__(self, a):
self.a = a
a = A(0)
b = a
print(b.a)
b = A(5)
print(a.a)
print(b.a)
|
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
i, j, boats = 0, len(people) - 1, 0
while i <= j:
boats += 1
if people[i] + people[j] <= limit:
i += 1
j -= 1
return boats |
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
count = Counter(s)
for i, c in enumerate(t):
count[c] -= 1
if count[c] == -1:
return c
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 00:49:46 2019
"""
# simple binary detection script
config = {
## model
'num_classes': 1,
'classes': ['background', 'car',],
'img_size': 416,
## train
'weight_decay': 0.0001,
'images_root': r'./data/images',
'train_path': r'./data/train.txt',
'test_path': r'./data/test.txt',
'ckpt_name': 'checkpoint.pth',
## focal loss
'alpha': 0.25,
'gamma': 2.0,
## demo
'conf_thres':0.4,
'nms_thresh_topN':100,
'NMS_thresh':0.4,
} |
class Solution(object):
def checkSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
P = set()
for n in nums:
P = {(m+n) % k if k else m+n for m in P}
if 0 in P:
return True
P.add(n)
return False
|
#!/usr/bin/env python
class Empire(dict):
''' Methods for updating/viewing Empirees '''
def __init__(self, Empire_dict):
super(Empire, self).__init__()
self.update(Empire_dict)
|
class ParserError(Exception):
pass
class ReceiptNotFound(ParserError):
pass
|
text = input().split(", ")
valid_names = ""
for word in text:
if 3 <= len(word) <= 16:
if word.isalnum() or "-" in word or "_" in word:
valid_names = word
print(valid_names)
|
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
temp = dict()
i = 0
max_dis = 0
for k in range(len(s)):
if s[k] in temp:
i = max(temp[s[k]] + 1, i)
temp[s[k]] = k
max_dis = max(k - i + 1, max_dis)
return max_dis |
"""
Write Number in Expanded Form
You will be given a number and you will need to return it as a string in Expanded Form.
For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
"""
def expanded_form(num):
txt = [i for i in str(num)]
lst = []
count = 1
for i in txt:
if i != '0':
lst.append(i + ('0' * (len(str(num)) - count)))
count += 1
return ' + '.join(lst)
print(expanded_form(381395))
|
#!/usr/bin/env python3
sum = 0
prod = 1
for i in range(1,11):
sum += i
prod *= i
print('sum: %d' % sum)
print('prod: %d' % prod)
|
# my name is abhishek. all are comments
# print("hie") # ijko
"""
file = module in python
"""
'''
data type int,float,string,boolean,none- says particular datatype as it doe not have value actually false
data structure - list, dictionary.
'''
# everything in python is call by reference, what is done after delete a file
# none_variable_1 = None
# print(none_variable_
# dictionary is a key value pair
# [] = List
# {} = Dictionary
# () = Tuple
# anything is blank in python is considered as false eg list,string,dictionary
# false is not equal to none
# tupple is non mutable and list is mutable
# press ctrl shift f then it will be seperate all of your elements
|
# In Python, True and False are Boolean objects of class 'bool' and they are immutable.
# Python assumes any non-zero and non-null values as True, otherwise it is False value.
# Python does not provide switch or case statements as in other languages.
# if statement
x = int(input('please enter an integer: '))
# x = int(.......)表示將裡面的東西轉換為int
# input(.......)用來表示要在terminal中輸入東西,而裡面的...是提示,顯示要打什麼進去,可為數字或string
# 在這例子裡面只能打數字,如果打string,會報錯
if x < 0:
# if語句後面記得加:
print('negative number')
# if..else statement
y = int(input('please enter an integer: '))
if y < 0:
print('negative number')
else:
print('positive number')
# if...elif...else statement
y = int(input('please enter an integer: '))
if y < 0:
print('negative number')
elif y > 0:
print('positive number')
else:
print('zero')
# if...elif...else statement 當中的elif可重覆運用
y = int(input('please enter an integer: '))
if -5< y < 0:
print('0 to -5')
elif y > 0:
print('positive number')
elif y < -5:
print('small than -5')
else:
print('zero') |
#No job instantiation, just an interface that could be implemented with a priority queue or map.
class Executor():
def __init__(self, IP, port):
self.server_info = (IP, port)
#server stores info of jobs in centralized location, so should manage encoding
def submit(self, job_name, size, priority = 1, retries = 0, send_data = True):
#just as fn denotes the callable in futures, the submit(job_name....) should schedule the callable
#gets the Futures object according to the name??? NOT the job and the processing itself, rather its a supervisor
new_future = Future(function_name, self.server_info)
#the object doesn't have the job specifications itself
#determine in what format you should send to server
#will have job_name, priority, retries, and send_data sent directly to server, not the future object
self.server_info
#this portion would facilitate communication of job specifications: job_name, size, priority, retries, send_data
#send w http or json
#the future object should hold the info to know the status of the job
#get the results from that future object to assess the info
return new_future
def shutdown(self, wait = True):
#grab server info and try to assess if job is done or not
args = True
#get result from Future.running() to see if the jobs can be shut down
if wait:
args = False
return args
#this is all about the references to the actual job object, a means to reference from client
#the future object is responsible for getting inquiries from the client about the server
#the future object should keep all the info for the server and name, and facilitate communication between server and client
class Future():
def __init__(self, job_name, server_info):
self.job_name = job_name
def cancel(self):
return False
def cancelled(self):
return True
def running(self):
return True
def done(self):
return True
def result(self):
success = False
if success:
return success
else:
return success
def exception(self, timeout = None):
#check for successful run without any exceptions
return None
def add_done_callback(self, function_name):
function_name
|
#!/usr/bin/env python3
"""Super class for all malwares.
"""
class Malware:
"""Defines the lifetime of the malware's domains.
The lifetime is expressed in seconds.
0 means that the malware doesn't implement a DGA.
Returns:
The lifetime of the malware's domains.
"""
@classmethod
def domainsLifetime(self):
return 0
"""Returns the list of domains used by the malware.
This method will return the list of domain for the current day/hour if it is a DGA.
Returns:
An array of the domains used by this malware.
"""
@classmethod
def domains(self):
return []
"""Returns the list of domains used by the malware at a certain time.
If the malware isn't a DGA, this method will return the list of all domains used.
Refer to the method domainsLifetime for the lifetime of these domains.
Params:
date The date and time for which you want the domains used.
Returns:
"""
@classmethod
def domainsFor(self, date):
return []
"""Checks if a domain could be used by the malware.
This method can be used to eliminate potential malware candidates for a domain.
It can only verify that a domain isn't used by the malware.
It won't check if it is actually used by the malware.
Params:
domain The domain to check.
Returns:
False if the malware can't be one of the malware's, true otherwise.
"""
@classmethod
def couldUseDomain(domain):
return False
|
# coding: utf-8
# This file is a part of VK4XMPP transport
# © simpleApps, 2014 (30.08.14 08:08AM GMT) — 2015.
"""
This plugin allows users to publish their status in VK
"""
VK_ACCESS += 1024
GLOBAL_USER_SETTINGS["status_to_vk"] = {"label": "Publish my status in VK", "value": 0}
def statustovk_prs01(source, prs, retry=3):
if source in Transport and prs.getType() in ("available", None):
if prs.getTo() == TransportID:
user = Transport[source]
if user.settings.status_to_vk:
mask = user.vk.method("account.getAppPermissions") or 0
if mask:
status = prs.getStatus()
if not getattr(user, "last_status", None) or user.last_status != status:
if mask & 1024 == 1024:
if not status:
user.vk.method("status.set", {"text": ""})
else:
user.vk.method("status.set", {"text": status})
else:
sendMessage(source, TransportID, _("Not enough permissions to publish your status on the site. Please, register again."))
logger.error("not changing user's status on the site 'cause we do not have enough permissions (jid: %s)" % source)
user.last_status = status
else:
logger.debug("we didn't receive application permissions, so starting a timer (jid: %s)" % source)
if retry:
utils.runThread(statustovk_prs01, (source, prs, (retry -1)), delay=10)
registerHandler("prs01", statustovk_prs01) |
"""
Given a string text, you want to use the characters of text to form as
many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum
number of instances that can be formed.
Example:
Input: text = "nlaebolko"
Output: 1
Example:
Input: text = "loonbalxballpoon"
Output: 2
Example:
Input: text = "leetcode"
Output: 0
Constraints:
- 1 <= text.length <= 10^4
- text consists of lower case English letters only.
"""
#Difficulty: Easy
#23 / 23 test cases passed.
#Runtime: 32 ms
#Memory Usage: 14.3 MB
#Runtime: 32 ms, faster than 67.90% of Python3 online submissions for Maximum Number of Balloons.
#Memory Usage: 14.3 MB, less than 53.34% of Python3 online submissions for Maximum Number of Balloons.
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
balloons = float(inf)
for char in 'balon':
if char in 'lo':
balloons = min(balloons, text.count(char) // 2)
else:
balloons = min(balloons, text.count(char))
return balloons
|
def block_width(block):
try:
return block.index('\n')
except ValueError:
return len(block)
def stack_str_blocks(blocks):
"""Takes a list of multiline strings, and stacks them horizontally.
For example, given 'aaa\naaa' and 'bbbb\nbbbb', it returns
'aaa bbbb\naaa bbbb'. As in:
'aaa + 'bbbb = 'aaa bbbb
aaa' bbbb' aaa bbbb'
Each block must be rectangular (all lines are the same length), but blocks
can be different sizes.
"""
builder = []
block_lens = [block_width(bl) for bl in blocks]
split_blocks = [bl.split('\n') for bl in blocks]
for line_list in itertools.zip_longest(*split_blocks, fillvalue=None):
for i, line in enumerate(line_list):
if line is None:
builder.append(' ' * block_lens[i])
else:
builder.append(line)
if i != len(line_list) - 1:
builder.append(' ') # Padding
builder.append('\n')
return ''.join(builder[:-1])
class ASTNode:
Val = None
def __init__(self, Val, Start, End):
self.Val = Val
self.Start = Start
self.End = End
self.Children = []
self.indent = 0
def add_child(self, Child):
if not isinstance(Child, ASTNode):
return False
self.Children.append(Child)
return True
def get_child(self, ind):
return self.Children[ind]
def __str__(self):
return '{' + self.Val.__repr__() + '}'
def display(self): # Here
if not self.Children:
return self.__str__()
child_strs = [child.display() for child in self.Children]
child_widths = [block_width(s) for s in child_strs]
# How wide is this block?
display_width = max(len(self.__str__()),
sum(child_widths) + len(child_widths) - 1)
# Determines midpoints of child blocks
child_midpoints = []
child_end = 0
for width in child_widths:
child_midpoints.append(child_end + (width // 2))
child_end += width + 1
# Builds up the brace, using the child midpoints
brace_builder = []
for i in range(display_width):
if i < child_midpoints[0] or i > child_midpoints[-1]:
brace_builder.append(' ')
elif i in child_midpoints:
brace_builder.append('+')
else:
brace_builder.append('-')
brace = ''.join(brace_builder)
name_str = '{:^{}}'.format(self.__str__(), display_width)
below = stack_str_blocks(child_strs)
return name_str + '\n' + brace + '\n' + below
def get_val(s, pos):
if pos >= len(s):
return None
return s[pos].Val
|
# -*- coding: utf-8 -*-
"""Top-level package for pistis."""
__author__ = """Michael Benjamin Hall"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
def binary_search(target, num_list):
if not target:
raise Exception
if not num_list:
raise Exception
left, right = 0, len(num_list)-1
mid = left + (right - left)//2
while left <= right:
mid = left + (right - left)//2
if num_list[mid] == target:
return True
elif num_list[mid] < target:
left = mid + 1
else:
right = mid
return False
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : __init__.py
@Time : 2022/2/1 6:51
@Author : Tim Chen
@Version : 0.0.1
@Contact : [email protected]
@License : MIT
@Desc : None
"""
# here put the import lib
|
def rotateMatrixby90(ipMat, size):
opMat = [[0 for i in range(size)] for j in range(size)]
for i in range(size):
for j in range(size):
opMat[j][i] = ipMat[i][j]
return opMat
def reverseMatrix(ipMat, size):
opMat = [[0 for i in range(size)] for j in range(size)]
for i in range(size):
for j in range(size):
opMat[abs(i-(size-1))][j] = ipMat[i][j]
return opMat
def rotateMatrixby180(ipMat, size):
mat_1 = rotateMatrixby90(ipMat, size)
mat_2 = reverseMatrix(mat_1, len(mat_1))
mat_3 = rotateMatrixby90(mat_2, len(mat_2))
mat_4 = reverseMatrix(mat_3, len(mat_3))
return mat_4
def printMatrix(ipMat, size):
for i in range(size):
for j in range(size):
print(ipMat[i][j], end=" ")
print('\n')
matA = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print("Original-Matrix" + '\n')
printMatrix(matA, len(matA))
print("Rotated-Matrix" + '\n')
rotatedMat = rotateMatrixby90(matA, len(matA))
printMatrix(rotatedMat, len(rotatedMat))
matB = [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]
reverseMat = reverseMatrix(matB, len(matB))
print("Reverse-Matrix" + '\n')
printMatrix(reverseMat, len(reverseMat))
print("Rotated-180-Matrix" + '\n')
rotatedMat180 = rotateMatrixby180(matA, len(matA))
printMatrix(rotatedMat180, len(rotatedMat180))
|
""" Based on C code from: http://nlp.cs.nyu.edu/evalb/
"""
def bracketing(ts):
buf = range((len(ts)+1)/2 + 1)
buf = list(reversed(zip(buf[:-1], buf[1:])))
stack = []
ret = []
for t in ts:
if t == 0:
stack.append(buf.pop())
elif t == 1:
R, L = stack.pop(), stack.pop()
stack.append((L[0], R[1]))
if L[0] != L[1]-1:
ret.append(L)
if R[0] != R[1]-1:
ret.append(R)
ret.append(stack[-1])
return ret
def crossing(gold, pred):
try:
gsplits = bracketing(gold)
psplits = bracketing(pred)
crosses = []
for p in psplits:
for g in gsplits:
if (g[0] < p[0] and g[1] > p[0] and g[1] < p[1]) or \
(g[0] > p[0] and g[0] < p[1] and g[1] > p[1]):
crosses.append((g, p))
break
count = len(crosses)
except:
crosses = []
count = -1
return crosses, count
|
#!/usr/bin/env python
#Modify once acccording to your setup
WORKSPACE = "/Users/Gautam/AndroidStudioProjects/AndroidGPSTracking"
#Modify the below lines for each project
PROJECT_NAME = "AndroidGPSTracking"
#Modify if using DB
DB_NAME = "mainTuple"
TABLE_NAME = "footRecords"
MAIN_ACTIVITY = "TrackActivity"
#DO NOT MODIFY
PREFIX = "com.example.gpstracking"
#PROJECT_EXT = PROJECT_NAME.lower()
|
class Solution(object):
def removeKdigits(self, num, k):
if len(num) <= k:
return "0"
ret = []
for i in range(len(num)):
while k > 0 and ret and ret[-1] > num[i]:
ret.pop()
k-=1
ret.append(num[i])
while k > 0 and ret:
ret.pop()
k -= 1
s = "".join(ret).lstrip("0")
return s if s else "0"
num = "1432219"
k = 3
res = Solution().removeKdigits(num, k)
print(res) |
class TooShort(Exception):
pass
class Stale(Exception):
pass
class Incomplete(Exception):
pass
class Boring(Exception):
pass
|
class BasePipeline(object):
"""Main end-point to run the pipeline processes"""
def __init__(self, config):
self.config = config
def initialize_data(self):
""" Initialize dataset: loading, preprocess metadata"""
raise NotImplementedError
def extract_feature(self):
raise NotImplementedError
def normalize_feature(self):
raise NotImplementedError
def search_hyperparams(self):
raise NotImplementedError
def system_train(self):
raise NotImplementedError
def system_test(self):
raise NotImplementedError
def system_evaluate(self):
raise NotImplementedError
def show_parameters(self):
raise NotImplementedError
def show_dataset_info(self):
raise NotImplementedError |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class ExampleData(object):
def __init__(
self,
question: str = None,
is_multi_select: bool = False,
option1: str = None,
option2: str = None,
option3: str = None,
):
self.question = question
self.is_multi_select = is_multi_select
self.option1 = option1
self.option2 = option2
self.option3 = option3
|
#
# PySNMP MIB module CISCO-CEF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CEF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:53:12 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
CefAdminStatus, CefCCAction, CefForwardingElementSpecialType, CefAdjacencySource, CefPathType, CefFailureReason, CefOperStatus, CefIpVersion, CefAdjLinkType, CefCCStatus, CefMplsLabelList, CefPrefixSearchState, CefCCType = mibBuilder.importSymbols("CISCO-CEF-TC", "CefAdminStatus", "CefCCAction", "CefForwardingElementSpecialType", "CefAdjacencySource", "CefPathType", "CefFailureReason", "CefOperStatus", "CefIpVersion", "CefAdjLinkType", "CefCCStatus", "CefMplsLabelList", "CefPrefixSearchState", "CefCCType")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
EntPhysicalIndexOrZero, = mibBuilder.importSymbols("CISCO-TC", "EntPhysicalIndexOrZero")
entPhysicalIndex, PhysicalIndex = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex", "PhysicalIndex")
CounterBasedGauge64, = mibBuilder.importSymbols("HCNUM-TC", "CounterBasedGauge64")
InterfaceIndexOrZero, ifIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "ifIndex")
InetAddress, InetAddressPrefixLength, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressPrefixLength", "InetAddressType")
MplsVpnId, = mibBuilder.importSymbols("MPLS-VPN-MIB", "MplsVpnId")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
TimeTicks, IpAddress, Counter32, MibIdentifier, Counter64, Unsigned32, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Integer32, ModuleIdentity, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "IpAddress", "Counter32", "MibIdentifier", "Counter64", "Unsigned32", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Integer32", "ModuleIdentity", "Bits", "Gauge32")
TimeStamp, TextualConvention, TruthValue, TestAndIncr, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TextualConvention", "TruthValue", "TestAndIncr", "RowStatus", "DisplayString")
ciscoCefMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 492))
ciscoCefMIB.setRevisions(('2006-01-30 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoCefMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoCefMIB.setLastUpdated('200601300000Z')
if mibBuilder.loadTexts: ciscoCefMIB.setOrganization('Cisco System, Inc.')
if mibBuilder.loadTexts: ciscoCefMIB.setContactInfo('Postal: Cisco Systems, Inc. 170 West Tasman Drive San Jose, CA 95134-1706 USA Tel: +1 800 553-NETS E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoCefMIB.setDescription('Cisco Express Forwarding (CEF) describes a high speed switching mechanism that a router uses to forward packets from the inbound to the outbound interface. CEF uses two sets of data structures or tables, which it stores in router memory: Forwarding information base (FIB) - Describes a database of information used to make forwarding decisions. It is conceptually similar to a routing table or route-cache, although its implementation is different. Adjacency - Two nodes in the network are said to be adjacent if they can reach each other via a single hop across a link layer. CEF path is a valid route to reach to a destination IP prefix. Multiple paths may exist out of a router to the same destination prefix. CEF Load balancing capability share the traffic to the destination IP prefix over all the active paths. After obtaining the prefix in the CEF table with the longest match, output forwarding follows the chain of forwarding elements. Forwarding element (FE) may process the packet, forward the packet, drop or punt the packet or it may also pass the packet to the next forwarding element in the chain for further processing. Forwarding Elements are of various types but this MIB only represents the forwarding elements of adjacency and label types. Hence a forwarding element chain will be represented as a list of labels and adjacency. The adjacency may point to a forwarding element list again, if it is not the last forwarding element in this chain. For the simplest IP forwarding case, the prefix entry will point at an adjacency forwarding element. The IP adjacency processing function will apply the output features, add the encapsulation (performing any required fixups), and may send the packet out. If loadbalancing is configured, the prefix entry will point to lists of forwarding elements. One of these lists will be selected to forward the packet. Each forwarding element list dictates which of a set of possible packet transformations to apply on the way to the same neighbour. The following diagram represents relationship between three of the core tables in this MIB module. cefPrefixTable cefFESelectionTable +---------------+ points +--------------+ | | | | a set +----> | | | | | |---------------| of FE | |--------------| | | | | Selection | | | | | | |---------------| Entries | |--------------| | | | |------------+ | |<----+ |---------------| |--------------| | | | +--------------| | | | | | +---------------+ | +--------------+ | | | points to an | adjacency entry | | | | cefAdjTable | | +---------------+ may point | +->| | | | to a set | |---------------| of FE | | | | | Selection | |---------------| Entries | | | | |----------------+ |---------------| | | +---------------+ Some of the Cisco series routers (e.g. 7500 & 12000) support distributed CEF (dCEF), in which the line cards (LCs) make the packet forwarding decisions using locally stored copies of the same Forwarding information base (FIB) and adjacency tables as the Routing Processor (RP). Inter-Process Communication (IPC) is the protocol used by routers that support distributed packet forwarding. CEF updates are encoded as external Data Representation (XDR) information elements inside IPC messages. This MIB reflects the distributed nature of CEF, e.g. CEF has different instances running on the RP and the line cards. There may be instances of inconsistency between the CEF forwarding databases(i.e between CEF forwarding database on line cards and the CEF forwarding database on the RP). CEF consistency checkers (CC) detects this inconsistency. When two databases are compared by a consistency checker, a set of records from the first (master) database is looked up in the second (slave). There are two types of consistency checkers, active and passive. Active consistency checkers are invoked in response to some stimulus, i.e. when a packet cannot be forwarded because the prefix is not in the forwarding table or in response to a Management Station request. Passive consistency checkers operate in the background, scanning portions of the databases on a periodic basis. The full-scan checkers are active consistency checkers which are invoked in response to a Management Station Request. If 64-bit counter objects in this MIB are supported, then their associated 32-bit counter objects must also be supported. The 32-bit counters will report the low 32-bits of the associated 64-bit counter count (e.g., cefPrefixPkts will report the least significant 32 bits of cefPrefixHCPkts). The same rule should be applied for the 64-bit gauge objects and their assocaited 32-bit gauge objects. If 64-bit counters in this MIB are not supported, then an agent MUST NOT instantiate the corresponding objects with an incorrect value; rather, it MUST respond with the appropriate error/exception condition (e.g., noSuchInstance or noSuchName). Counters related to CEF accounting (e.g., cefPrefixPkts) MUST NOT be instantiated if the corresponding accounting method has been disabled. This MIB allows configuration and monitoring of CEF related objects.')
ciscoCefMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 0))
ciscoCefMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1))
ciscoCefMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 2))
cefFIB = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1))
cefAdj = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2))
cefFE = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3))
cefGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4))
cefInterface = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5))
cefPeer = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6))
cefCC = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7))
cefStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8))
cefNotifCntl = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9))
cefFIBSummary = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 1))
cefFIBSummaryTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 1, 1), )
if mibBuilder.loadTexts: cefFIBSummaryTable.setStatus('current')
if mibBuilder.loadTexts: cefFIBSummaryTable.setDescription('This table contains the summary information for the cefPrefixTable.')
cefFIBSummaryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"))
if mibBuilder.loadTexts: cefFIBSummaryEntry.setStatus('current')
if mibBuilder.loadTexts: cefFIBSummaryEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the FIB summary related attributes for the managed entity. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefFIBIpVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 1, 1, 1, 1), CefIpVersion())
if mibBuilder.loadTexts: cefFIBIpVersion.setStatus('current')
if mibBuilder.loadTexts: cefFIBIpVersion.setDescription('The version of IP forwarding.')
cefFIBSummaryFwdPrefixes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 1, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFIBSummaryFwdPrefixes.setStatus('current')
if mibBuilder.loadTexts: cefFIBSummaryFwdPrefixes.setDescription('Total number of forwarding Prefixes in FIB for the IP version specified by cefFIBIpVersion object.')
cefPrefixTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2), )
if mibBuilder.loadTexts: cefPrefixTable.setStatus('current')
if mibBuilder.loadTexts: cefPrefixTable.setDescription('A list of CEF forwarding prefixes.')
cefPrefixEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefPrefixType"), (0, "CISCO-CEF-MIB", "cefPrefixAddr"), (0, "CISCO-CEF-MIB", "cefPrefixLen"))
if mibBuilder.loadTexts: cefPrefixEntry.setStatus('current')
if mibBuilder.loadTexts: cefPrefixEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the forwarding prefix attributes. CEF prefix based non-recursive stats are maintained in internal and external buckets (depending upon the value of cefIntNonrecursiveAccouting object in the CefIntEntry). entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefPrefixType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 1), InetAddressType())
if mibBuilder.loadTexts: cefPrefixType.setStatus('current')
if mibBuilder.loadTexts: cefPrefixType.setDescription('The Network Prefix Type. This object specifies the address type used for cefPrefixAddr. Prefix entries are only valid for the address type of ipv4(1) and ipv6(2).')
cefPrefixAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: cefPrefixAddr.setStatus('current')
if mibBuilder.loadTexts: cefPrefixAddr.setDescription('The Network Prefix Address. The type of this address is determined by the value of the cefPrefixType object. This object is a Prefix Address containing the prefix with length specified by cefPrefixLen. Any bits beyond the length specified by cefPrefixLen are zeroed.')
cefPrefixLen = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 3), InetAddressPrefixLength())
if mibBuilder.loadTexts: cefPrefixLen.setStatus('current')
if mibBuilder.loadTexts: cefPrefixLen.setDescription('Length in bits of the FIB Address prefix.')
cefPrefixForwardingInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 4), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixForwardingInfo.setStatus('current')
if mibBuilder.loadTexts: cefPrefixForwardingInfo.setDescription('This object indicates the associated forwarding element selection entries in cefFESelectionTable. The value of this object is index value (cefFESelectionName) of cefFESelectionTable.')
cefPrefixPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 5), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixPkts.setDescription("If CEF accounting is set to enable per prefix accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'perPrefix' accounting), then this object represents the number of packets switched to this prefix.")
cefPrefixHCPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 6), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixHCPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixHCPkts.setDescription("If CEF accounting is set to enable per prefix accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'perPrefix' accounting), then this object represents the number of packets switched to this prefix. This object is a 64-bit version of cefPrefixPkts.")
cefPrefixBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 7), Counter32()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixBytes.setDescription("If CEF accounting is set to enable per prefix accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'perPrefix' accounting), then this object represents the number of bytes switched to this prefix.")
cefPrefixHCBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 8), Counter64()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixHCBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixHCBytes.setDescription("If CEF accounting is set to enable per prefix accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'perPrefix' accounting), then this object represents the number of bytes switched to this prefix. This object is a 64-bit version of cefPrefixBytes.")
cefPrefixInternalNRPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 9), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixInternalNRPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixInternalNRPkts.setDescription("If CEF accounting is set to enable non-recursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive packets in the internal bucket switched using this prefix.")
cefPrefixInternalNRHCPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 10), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixInternalNRHCPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixInternalNRHCPkts.setDescription("If CEF accounting is set to enable non-recursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive packets in the internal bucket switched using this prefix. This object is a 64-bit version of cefPrefixInternalNRPkts.")
cefPrefixInternalNRBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 11), Counter32()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixInternalNRBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixInternalNRBytes.setDescription("If CEF accounting is set to enable nonRecursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive bytes in the internal bucket switched using this prefix.")
cefPrefixInternalNRHCBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 12), Counter64()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixInternalNRHCBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixInternalNRHCBytes.setDescription("If CEF accounting is set to enable nonRecursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive bytes in the internal bucket switched using this prefix. This object is a 64-bit version of cefPrefixInternalNRBytes.")
cefPrefixExternalNRPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 13), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixExternalNRPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixExternalNRPkts.setDescription("If CEF accounting is set to enable non-recursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive packets in the external bucket switched using this prefix.")
cefPrefixExternalNRHCPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 14), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixExternalNRHCPkts.setStatus('current')
if mibBuilder.loadTexts: cefPrefixExternalNRHCPkts.setDescription("If CEF accounting is set to enable non-recursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive packets in the external bucket switched using this prefix. This object is a 64-bit version of cefPrefixExternalNRPkts.")
cefPrefixExternalNRBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 15), Counter32()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixExternalNRBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixExternalNRBytes.setDescription("If CEF accounting is set to enable nonRecursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive bytes in the external bucket switched using this prefix.")
cefPrefixExternalNRHCBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 2, 1, 16), Counter64()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPrefixExternalNRHCBytes.setStatus('current')
if mibBuilder.loadTexts: cefPrefixExternalNRHCBytes.setDescription("If CEF accounting is set to enable nonRecursive accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'nonRecursive' accounting), then this object represents the number of non-recursive bytes in the external bucket switched using this prefix. This object is a 64-bit version of cefPrefixExternalNRBytes.")
cefLMPrefixSpinLock = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 3), TestAndIncr()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefLMPrefixSpinLock.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixSpinLock.setDescription("An advisory lock used to allow cooperating SNMP Command Generator applications to coordinate their use of the Set operation in creating Longest Match Prefix Entries in cefLMPrefixTable. When creating a new longest prefix match entry, the value of cefLMPrefixSpinLock should be retrieved. The destination address should be determined to be unique by the SNMP Command Generator application by consulting the cefLMPrefixTable. Finally, the longest prefix entry may be created (Set), including the advisory lock. If another SNMP Command Generator application has altered the longest prefix entry in the meantime, then the spin lock's value will have changed, and so this creation will fail because it will specify the wrong value for the spin lock. Since this is an advisory lock, the use of this lock is not enforced, but not using this lock may lead to conflict with the another SNMP command responder application which may also be acting on the cefLMPrefixTable.")
cefLMPrefixTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4), )
if mibBuilder.loadTexts: cefLMPrefixTable.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixTable.setDescription('A table of Longest Match Prefix Query requests. Generator application should utilize the cefLMPrefixSpinLock to try to avoid collisions. See DESCRIPTION clause of cefLMPrefixSpinLock.')
cefLMPrefixEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefLMPrefixDestAddrType"), (0, "CISCO-CEF-MIB", "cefLMPrefixDestAddr"))
if mibBuilder.loadTexts: cefLMPrefixEntry.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixEntry.setDescription("If CEF is enabled on the managed device, then each entry represents a longest Match Prefix request. A management station wishing to get the longest Match prefix for a given destination address should create the associate instance of the row status. The row status should be set to active(1) to initiate the request. Note that this entire procedure may be initiated via a single set request which specifies a row status of createAndGo(4). Once the request completes, the management station should retrieve the values of the objects of interest, and should then delete the entry. In order to prevent old entries from clogging the table, entries will be aged out, but an entry will never be deleted within 5 minutes of completion. Entries are lost after an agent restart. I.e. to find out the longest prefix match for destination address of A.B.C.D on entity whose entityPhysicalIndex is 1, the Management station will create an entry in cefLMPrefixTable with cefLMPrefixRowStatus.1(entPhysicalIndex).1(ipv4).A.B.C.D set to createAndGo(4). Management Station may query the value of objects cefLMPrefix and cefLMPrefixLen to find out the corresponding prefix entry from the cefPrefixTable once the value of cefLMPrefixState is set to matchFound(2). entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF. ")
cefLMPrefixDestAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 1), InetAddressType())
if mibBuilder.loadTexts: cefLMPrefixDestAddrType.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixDestAddrType.setDescription('The Destination Address Type. This object specifies the address type used for cefLMPrefixDestAddr. Longest Match Prefix entries are only valid for the address type of ipv4(1) and ipv6(2).')
cefLMPrefixDestAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 2), InetAddress())
if mibBuilder.loadTexts: cefLMPrefixDestAddr.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixDestAddr.setDescription('The Destination Address. The type of this address is determined by the value of the cefLMPrefixDestAddrType object.')
cefLMPrefixState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 3), CefPrefixSearchState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefLMPrefixState.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixState.setDescription('Indicates the state of this prefix search request.')
cefLMPrefixAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 4), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefLMPrefixAddr.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixAddr.setDescription('The Network Prefix Address. Index to the cefPrefixTable. The type of this address is determined by the value of the cefLMPrefixDestAddrType object.')
cefLMPrefixLen = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 5), InetAddressPrefixLength()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefLMPrefixLen.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixLen.setDescription('The Network Prefix Length. Index to the cefPrefixTable.')
cefLMPrefixRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 4, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cefLMPrefixRowStatus.setStatus('current')
if mibBuilder.loadTexts: cefLMPrefixRowStatus.setDescription('The status of this table entry. Once the entry status is set to active(1), the associated entry cannot be modified until the request completes (cefLMPrefixState transitions to matchFound(2) or noMatchFound(3)). Once the longest match request has been created (i.e. the cefLMPrefixRowStatus has been made active), the entry cannot be modified - the only operation possible after this is to delete the row.')
cefPathTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5), )
if mibBuilder.loadTexts: cefPathTable.setStatus('current')
if mibBuilder.loadTexts: cefPathTable.setDescription('CEF prefix path is a valid route to reach to a destination IP prefix. Multiple paths may exist out of a router to the same destination prefix. This table specify lists of CEF paths.')
cefPathEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefPrefixType"), (0, "CISCO-CEF-MIB", "cefPrefixAddr"), (0, "CISCO-CEF-MIB", "cefPrefixLen"), (0, "CISCO-CEF-MIB", "cefPathId"))
if mibBuilder.loadTexts: cefPathEntry.setStatus('current')
if mibBuilder.loadTexts: cefPathEntry.setDescription("If CEF is enabled on the Managed device, each entry contain a CEF prefix path. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefPathId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: cefPathId.setStatus('current')
if mibBuilder.loadTexts: cefPathId.setDescription('The locally arbitrary, but unique identifier associated with this prefix path entry.')
cefPathType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1, 2), CefPathType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPathType.setStatus('current')
if mibBuilder.loadTexts: cefPathType.setDescription('Type for this CEF Path.')
cefPathInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1, 3), InterfaceIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPathInterface.setStatus('current')
if mibBuilder.loadTexts: cefPathInterface.setDescription('Interface associated with this CEF path. A value of zero for this object will indicate that no interface is associated with this path entry.')
cefPathNextHopAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1, 4), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPathNextHopAddr.setStatus('current')
if mibBuilder.loadTexts: cefPathNextHopAddr.setDescription('Next hop address associated with this CEF path. The value of this object is only relevant for attached next hop and recursive next hop path types (when the object cefPathType is set to attachedNexthop(4) or recursiveNexthop(5)). and will be set to zero for other path types. The type of this address is determined by the value of the cefPrefixType object.')
cefPathRecurseVrfName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 1, 5, 1, 5), MplsVpnId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPathRecurseVrfName.setStatus('current')
if mibBuilder.loadTexts: cefPathRecurseVrfName.setDescription("The recursive vrf name associated with this path. The value of this object is only relevant for recursive next hop path types (when the object cefPathType is set to recursiveNexthop(5)), and '0x00' will be returned for other path types.")
cefAdjSummary = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1))
cefAdjSummaryTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1), )
if mibBuilder.loadTexts: cefAdjSummaryTable.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryTable.setDescription('This table contains the summary information for the cefAdjTable.')
cefAdjSummaryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefAdjSummaryLinkType"))
if mibBuilder.loadTexts: cefAdjSummaryEntry.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the CEF Adjacency summary related attributes for the Managed entity. A row exists for each adjacency link type. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefAdjSummaryLinkType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1, 1), CefAdjLinkType())
if mibBuilder.loadTexts: cefAdjSummaryLinkType.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryLinkType.setDescription('The link type of the adjacency.')
cefAdjSummaryComplete = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjSummaryComplete.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryComplete.setDescription('The total number of complete adjacencies. The total number of adjacencies which can be used to switch traffic to a neighbour.')
cefAdjSummaryIncomplete = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjSummaryIncomplete.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryIncomplete.setDescription('The total number of incomplete adjacencies. The total number of adjacencies which cannot be used to switch traffic in their current state.')
cefAdjSummaryFixup = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjSummaryFixup.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryFixup.setDescription('The total number of adjacencies for which the Layer 2 encapsulation string (header) may be updated (fixed up) at packet switch time.')
cefAdjSummaryRedirect = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjSummaryRedirect.setReference('1. Internet Architecture Extensions for Shared Media, RFC 1620, May 1994.')
if mibBuilder.loadTexts: cefAdjSummaryRedirect.setStatus('current')
if mibBuilder.loadTexts: cefAdjSummaryRedirect.setDescription('The total number of adjacencies for which ip redirect (or icmp redirection) is enabled. The value of this object is only relevant for ipv4 and ipv6 link type (when the index object cefAdjSummaryLinkType value is ipv4(1) or ipv6(2)) and will be set to zero for other link types. ')
cefAdjTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2), )
if mibBuilder.loadTexts: cefAdjTable.setStatus('current')
if mibBuilder.loadTexts: cefAdjTable.setDescription('A list of CEF adjacencies.')
cefAdjEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "IF-MIB", "ifIndex"), (0, "CISCO-CEF-MIB", "cefAdjNextHopAddrType"), (0, "CISCO-CEF-MIB", "cefAdjNextHopAddr"), (0, "CISCO-CEF-MIB", "cefAdjConnId"), (0, "CISCO-CEF-MIB", "cefAdjSummaryLinkType"))
if mibBuilder.loadTexts: cefAdjEntry.setStatus('current')
if mibBuilder.loadTexts: cefAdjEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the adjacency attributes. Adjacency entries may exist for all the interfaces on which packets can be switched out of the device. The interface is instantiated by ifIndex. Therefore, the interface index must have been assigned, according to the applicable procedures, before it can be meaningfully used. Generally, this means that the interface must exist. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefAdjNextHopAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 1), InetAddressType())
if mibBuilder.loadTexts: cefAdjNextHopAddrType.setStatus('current')
if mibBuilder.loadTexts: cefAdjNextHopAddrType.setDescription('Address type for the cefAdjNextHopAddr. This object specifies the address type used for cefAdjNextHopAddr. Adjacency entries are only valid for the address type of ipv4(1) and ipv6(2).')
cefAdjNextHopAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: cefAdjNextHopAddr.setStatus('current')
if mibBuilder.loadTexts: cefAdjNextHopAddr.setDescription('The next Hop address for this adjacency. The type of this address is determined by the value of the cefAdjNextHopAddrType object.')
cefAdjConnId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 3), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4294967295), )))
if mibBuilder.loadTexts: cefAdjConnId.setStatus('current')
if mibBuilder.loadTexts: cefAdjConnId.setDescription('In cases where cefLinkType, interface and the next hop address are not able to uniquely define an adjacency entry (e.g. ATM and Frame Relay Bundles), this object is a unique identifier to differentiate between these adjacency entries. In all the other cases the value of this index object will be 0.')
cefAdjSource = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 4), CefAdjacencySource()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjSource.setStatus('current')
if mibBuilder.loadTexts: cefAdjSource.setDescription('If the adjacency is created because some neighbour discovery mechanism has discovered a neighbour and all the information required to build a frame header to encapsulate traffic to the neighbour is available then the source of adjacency is set to the mechanism by which the adjacency is learned.')
cefAdjEncap = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 5), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjEncap.setStatus('current')
if mibBuilder.loadTexts: cefAdjEncap.setDescription('The layer 2 encapsulation string to be used for sending the packet out using this adjacency.')
cefAdjFixup = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 6), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjFixup.setStatus('current')
if mibBuilder.loadTexts: cefAdjFixup.setDescription("For the cases, where the encapsulation string is decided at packet switch time, the adjacency encapsulation string specified by object cefAdjEncap require a fixup. I.e. for the adjacencies out of IP Tunnels, the string prepended is an IP header which has fields which can only be setup at packet switch time. The value of this object represent the kind of fixup applied to the packet. If the encapsulation string doesn't require any fixup, then the value of this object will be of zero length.")
cefAdjMTU = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 7), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjMTU.setStatus('current')
if mibBuilder.loadTexts: cefAdjMTU.setDescription('The Layer 3 MTU which can be transmitted using this adjacency.')
cefAdjForwardingInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 8), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjForwardingInfo.setStatus('current')
if mibBuilder.loadTexts: cefAdjForwardingInfo.setDescription('This object selects a forwarding info entry defined in the cefFESelectionTable. The selected target is defined by an entry in the cefFESelectionTable whose index value (cefFESelectionName) is equal to this object. The value of this object will be of zero length if this adjacency entry is the last forwarding element in the forwarding path.')
cefAdjPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 9), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjPkts.setStatus('current')
if mibBuilder.loadTexts: cefAdjPkts.setDescription('Number of pkts transmitted using this adjacency.')
cefAdjHCPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 10), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjHCPkts.setStatus('current')
if mibBuilder.loadTexts: cefAdjHCPkts.setDescription('Number of pkts transmitted using this adjacency. This object is a 64-bit version of cefAdjPkts.')
cefAdjBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 11), Counter32()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjBytes.setStatus('current')
if mibBuilder.loadTexts: cefAdjBytes.setDescription('Number of bytes transmitted using this adjacency.')
cefAdjHCBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 2, 2, 1, 12), Counter64()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefAdjHCBytes.setStatus('current')
if mibBuilder.loadTexts: cefAdjHCBytes.setDescription('Number of bytes transmitted using this adjacency. This object is a 64-bit version of cefAdjBytes.')
cefFESelectionTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1), )
if mibBuilder.loadTexts: cefFESelectionTable.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionTable.setDescription('A list of forwarding element selection entries.')
cefFESelectionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFESelectionName"), (0, "CISCO-CEF-MIB", "cefFESelectionId"))
if mibBuilder.loadTexts: cefFESelectionEntry.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionEntry.setDescription("If CEF is enabled on the Managed device, each entry contain a CEF forwarding element selection list. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefFESelectionName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: cefFESelectionName.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionName.setDescription('The locally arbitrary, but unique identifier used to select a set of forwarding element lists.')
cefFESelectionId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: cefFESelectionId.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionId.setDescription('Secondary index to identify a forwarding elements List in this Table.')
cefFESelectionSpecial = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 3), CefForwardingElementSpecialType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionSpecial.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionSpecial.setDescription('Special processing for a destination is indicated through the use of special forwarding element. If the forwarding element list contains the special forwarding element, then this object represents the type of special forwarding element.')
cefFESelectionLabels = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 4), CefMplsLabelList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionLabels.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionLabels.setDescription("This object represent the MPLS Labels associated with this forwarding Element List. The value of this object will be irrelevant and will be set to zero length if the forwarding element list doesn't contain a label forwarding element. A zero length label list will indicate that there is no label forwarding element associated with this selection entry.")
cefFESelectionAdjLinkType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 5), CefAdjLinkType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionAdjLinkType.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionAdjLinkType.setDescription("This object represent the link type for the adjacency associated with this forwarding Element List. The value of this object will be irrelevant and will be set to unknown(5) if the forwarding element list doesn't contain an adjacency forwarding element.")
cefFESelectionAdjInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 6), InterfaceIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionAdjInterface.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionAdjInterface.setDescription("This object represent the interface for the adjacency associated with this forwarding Element List. The value of this object will be irrelevant and will be set to zero if the forwarding element list doesn't contain an adjacency forwarding element.")
cefFESelectionAdjNextHopAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 7), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionAdjNextHopAddrType.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionAdjNextHopAddrType.setDescription("This object represent the next hop address type for the adjacency associated with this forwarding Element List. The value of this object will be irrelevant and will be set to unknown(0) if the forwarding element list doesn't contain an adjacency forwarding element.")
cefFESelectionAdjNextHopAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 8), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionAdjNextHopAddr.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionAdjNextHopAddr.setDescription("This object represent the next hop address for the adjacency associated with this forwarding Element List. The value of this object will be irrelevant and will be set to zero if the forwarding element list doesn't contain an adjacency forwarding element.")
cefFESelectionAdjConnId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 9), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4294967295), ))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionAdjConnId.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionAdjConnId.setDescription("This object represent the connection id for the adjacency associated with this forwarding Element List. The value of this object will be irrelevant and will be set to zero if the forwarding element list doesn't contain an adjacency forwarding element. In cases where cefFESelectionAdjLinkType, interface and the next hop address are not able to uniquely define an adjacency entry (e.g. ATM and Frame Relay Bundles), this object is a unique identifier to differentiate between these adjacency entries.")
cefFESelectionVrfName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 10), MplsVpnId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionVrfName.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionVrfName.setDescription("This object represent the Vrf name for the lookup associated with this forwarding Element List. The value of this object will be irrelevant and will be set to a string containing the single octet 0x00 if the forwarding element list doesn't contain a lookup forwarding element.")
cefFESelectionWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 3, 1, 1, 11), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4294967295), ))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefFESelectionWeight.setStatus('current')
if mibBuilder.loadTexts: cefFESelectionWeight.setDescription('This object represent the weighting for load balancing between multiple Forwarding Element Lists. The value of this object will be zero if load balancing is associated with this selection entry.')
cefCfgTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1), )
if mibBuilder.loadTexts: cefCfgTable.setStatus('current')
if mibBuilder.loadTexts: cefCfgTable.setDescription('This table contains global config parameter of CEF on the Managed device.')
cefCfgEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"))
if mibBuilder.loadTexts: cefCfgEntry.setStatus('current')
if mibBuilder.loadTexts: cefCfgEntry.setDescription("If the Managed device supports CEF, each entry contains the CEF config parameter for the managed entity. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefCfgAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 1), CefAdminStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgAdminState.setStatus('current')
if mibBuilder.loadTexts: cefCfgAdminState.setDescription('The desired state of CEF.')
cefCfgOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 2), CefOperStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCfgOperState.setStatus('current')
if mibBuilder.loadTexts: cefCfgOperState.setDescription('The current operational state of CEF. If the cefCfgAdminState is disabled(2), then cefOperState will eventually go to the down(2) state unless some error has occurred. If cefCfgAdminState is changed to enabled(1) then cefCfgOperState should change to up(1) only if the CEF entity is ready to forward the packets using Cisco Express Forwarding (CEF) else it should remain in the down(2) state. The up(1) state for this object indicates that CEF entity is forwarding the packet using Cisco Express Forwarding.')
cefCfgDistributionAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 3), CefAdminStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgDistributionAdminState.setStatus('current')
if mibBuilder.loadTexts: cefCfgDistributionAdminState.setDescription('The desired state of CEF distribution.')
cefCfgDistributionOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 4), CefOperStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCfgDistributionOperState.setStatus('current')
if mibBuilder.loadTexts: cefCfgDistributionOperState.setDescription('The current operational state of CEF distribution. If the cefCfgDistributionAdminState is disabled(2), then cefDistributionOperState will eventually go to the down(2) state unless some error has occurred. If cefCfgDistributionAdminState is changed to enabled(1) then cefCfgDistributionOperState should change to up(1) only if the CEF entity is ready to forward the packets using Distributed Cisco Express Forwarding (dCEF) else it should remain in the down(2) state. The up(1) state for this object indicates that CEF entity is forwarding the packet using Distributed Cisco Express Forwarding.')
cefCfgAccountingMap = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 5), Bits().clone(namedValues=NamedValues(("nonRecursive", 0), ("perPrefix", 1), ("prefixLength", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgAccountingMap.setStatus('current')
if mibBuilder.loadTexts: cefCfgAccountingMap.setDescription('This object represents a bitmap of network accounting options. CEF network accounting is disabled by default. CEF network accounting can be enabled by selecting one or more of the following CEF accounting option for the value of this object. nonRecursive(0): enables accounting through nonrecursive prefixes. perPrefix(1): enables the collection of the numbers of pkts and bytes express forwarded to a destination (prefix) prefixLength(2): enables accounting through prefixlength. Once the accounting is enabled, the corresponding stats can be retrieved from the cefPrefixTable and cefStatsPrefixLenTable. ')
cefCfgLoadSharingAlgorithm = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("original", 2), ("tunnel", 3), ("universal", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgLoadSharingAlgorithm.setStatus('current')
if mibBuilder.loadTexts: cefCfgLoadSharingAlgorithm.setDescription("Indicates the CEF Load balancing algorithm. Setting this object to none(1) will disable the Load sharing for the specified entry. CEF load balancing can be enabled by setting this object to one of following Algorithms: original(2) : This algorithm is based on a source and destination hash tunnel(3) : This algorithm is used in tunnels environments or in environments where there are only a few source universal(4) : This algorithm uses a source and destination and ID hash If the value of this object is set to 'tunnel' or 'universal', then the FIXED ID for these algorithms may be specified by the managed object cefLoadSharingID. ")
cefCfgLoadSharingID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 7), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4294967295), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgLoadSharingID.setStatus('current')
if mibBuilder.loadTexts: cefCfgLoadSharingID.setDescription('The Fixed ID associated with the managed object cefCfgLoadSharingAlgorithm. The hash of this object value may be used by the Load Sharing Algorithm. The value of this object is not relevant and will be set to zero if the value of managed object cefCfgLoadSharingAlgorithm is set to none(1) or original(2). The default value of this object is calculated by the device at the time of initialization.')
cefCfgTrafficStatsLoadInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 8), Unsigned32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgTrafficStatsLoadInterval.setStatus('current')
if mibBuilder.loadTexts: cefCfgTrafficStatsLoadInterval.setDescription('The interval time over which the CEF traffic statistics are collected.')
cefCfgTrafficStatsUpdateRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 1, 1, 9), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 65535), ))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCfgTrafficStatsUpdateRate.setStatus('current')
if mibBuilder.loadTexts: cefCfgTrafficStatsUpdateRate.setDescription('The frequency with which the line card sends the traffic load statistics to the Router Processor. Setting the value of this object to 0 will disable the CEF traffic statistics collection.')
cefResourceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 2), )
if mibBuilder.loadTexts: cefResourceTable.setStatus('current')
if mibBuilder.loadTexts: cefResourceTable.setDescription('This table contains global resource information of CEF on the Managed device.')
cefResourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"))
if mibBuilder.loadTexts: cefResourceEntry.setStatus('current')
if mibBuilder.loadTexts: cefResourceEntry.setDescription("If the Managed device supports CEF, each entry contains the CEF Resource parameters for the managed entity. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefResourceMemoryUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 2, 1, 1), Gauge32()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefResourceMemoryUsed.setStatus('current')
if mibBuilder.loadTexts: cefResourceMemoryUsed.setDescription('Indicates the number of bytes from the Processor Memory Pool that are currently in use by CEF on the managed entity.')
cefResourceFailureReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 4, 2, 1, 2), CefFailureReason()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefResourceFailureReason.setStatus('current')
if mibBuilder.loadTexts: cefResourceFailureReason.setDescription('The CEF resource failure reason which may lead to CEF being disabled on the managed entity.')
cefIntTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5, 1), )
if mibBuilder.loadTexts: cefIntTable.setStatus('current')
if mibBuilder.loadTexts: cefIntTable.setDescription('This Table contains interface specific information of CEF on the Managed device.')
cefIntEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"), (0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cefIntEntry.setStatus('current')
if mibBuilder.loadTexts: cefIntEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the CEF attributes associated with an interface. The interface is instantiated by ifIndex. Therefore, the interface index must have been assigned, according to the applicable procedures, before it can be meaningfully used. Generally, this means that the interface must exist. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefIntSwitchingState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cefEnabled", 1), ("distCefEnabled", 2), ("cefDisabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefIntSwitchingState.setStatus('current')
if mibBuilder.loadTexts: cefIntSwitchingState.setDescription('The CEF switching State for the interface. If CEF is enabled but distributed CEF(dCEF) is disabled then CEF is in cefEnabled(1) state. If distributed CEF is enabled, then CEF is in distCefEnabled(2) state. The cefDisabled(3) state indicates that CEF is disabled. The CEF switching state is only applicable to the received packet on the interface.')
cefIntLoadSharing = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("perPacket", 1), ("perDestination", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefIntLoadSharing.setStatus('current')
if mibBuilder.loadTexts: cefIntLoadSharing.setDescription('The status of load sharing on the interface. perPacket(1) : Router to send data packets over successive equal-cost paths without regard to individual hosts or user sessions. perDestination(2) : Router to use multiple, equal-cost paths to achieve load sharing Load sharing is enabled by default for an interface when CEF is enabled.')
cefIntNonrecursiveAccouting = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internal", 1), ("external", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefIntNonrecursiveAccouting.setStatus('current')
if mibBuilder.loadTexts: cefIntNonrecursiveAccouting.setDescription('The CEF accounting mode for the interface. CEF prefix based non-recursive accounting on an interface can be configured to store the stats for non-recursive prefixes in a internal or external bucket. internal(1) : Count input traffic in the nonrecursive internal bucket external(2) : Count input traffic in the nonrecursive external bucket The value of this object will only be effective if value of the object cefAccountingMap is set to enable nonRecursive(1) accounting.')
cefPeerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 1), )
if mibBuilder.loadTexts: cefPeerTable.setStatus('current')
if mibBuilder.loadTexts: cefPeerTable.setDescription('Entity acting as RP (Routing Processor) keeps the CEF states for the line card entities and communicates with the line card entities using XDR. This Table contains the CEF information related to peer entities on the managed device.')
cefPeerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "entPeerPhysicalIndex"))
if mibBuilder.loadTexts: cefPeerEntry.setStatus('current')
if mibBuilder.loadTexts: cefPeerEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the CEF related attributes associated with a CEF peer entity. entPhysicalIndex and entPeerPhysicalIndex are also indexes for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
entPeerPhysicalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 1, 1, 1), PhysicalIndex())
if mibBuilder.loadTexts: entPeerPhysicalIndex.setStatus('current')
if mibBuilder.loadTexts: entPeerPhysicalIndex.setDescription("The entity index for the CEF peer entity. Only the entities of 'module' entPhysicalClass are included here.")
cefPeerOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("peerDisabled", 1), ("peerUp", 2), ("peerHold", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPeerOperState.setStatus('current')
if mibBuilder.loadTexts: cefPeerOperState.setDescription('The current CEF operational state of the CEF peer entity. Cef peer entity oper state will be peerDisabled(1) in the following condition: : Cef Peer entity encounters fatal error i.e. resource allocation failure, ipc failure etc : When a reload/delete request is received from the Cef Peer Entity Once the peer entity is up and no fatal error is encountered, then the value of this object will transits to the peerUp(3) state. If the Cef Peer entity is in held stage, then the value of this object will be peerHold(3). Cef peer entity can only transit to peerDisabled(1) state from the peerHold(3) state.')
cefPeerNumberOfResets = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPeerNumberOfResets.setStatus('current')
if mibBuilder.loadTexts: cefPeerNumberOfResets.setDescription('Number of times the session with CEF peer entity has been reset.')
cefPeerFIBTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 2), )
if mibBuilder.loadTexts: cefPeerFIBTable.setStatus('current')
if mibBuilder.loadTexts: cefPeerFIBTable.setDescription('Entity acting as RP (Routing Processor) keep the CEF FIB states for the line card entities and communicate with the line card entities using XDR. This Table contains the CEF FIB State related to peer entities on the managed device.')
cefPeerFIBEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "entPeerPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"))
if mibBuilder.loadTexts: cefPeerFIBEntry.setStatus('current')
if mibBuilder.loadTexts: cefPeerFIBEntry.setDescription("If CEF is enabled on the Managed device, each entry contains the CEF FIB State associated a CEF peer entity. entPhysicalIndex and entPeerPhysicalIndex are also indexes for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefPeerFIBOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("peerFIBDown", 1), ("peerFIBUp", 2), ("peerFIBReloadRequest", 3), ("peerFIBReloading", 4), ("peerFIBSynced", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefPeerFIBOperState.setStatus('current')
if mibBuilder.loadTexts: cefPeerFIBOperState.setDescription('The current CEF FIB Operational State for the CEF peer entity. ')
cefStatsPrefixLenTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1), )
if mibBuilder.loadTexts: cefStatsPrefixLenTable.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixLenTable.setDescription('This table specifies the CEF stats based on the Prefix Length.')
cefStatsPrefixLenEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"), (0, "CISCO-CEF-MIB", "cefStatsPrefixLen"))
if mibBuilder.loadTexts: cefStatsPrefixLenEntry.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixLenEntry.setDescription("If CEF is enabled on the Managed device and if CEF accounting is set to enable prefix length based accounting (value of cefCfgAccountingMap object in the cefCfgEntry is set to enable 'prefixLength' accounting), each entry contains the traffic statistics for a prefix length. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefStatsPrefixLen = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 1), InetAddressPrefixLength())
if mibBuilder.loadTexts: cefStatsPrefixLen.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixLen.setDescription('Length in bits of the Destination IP prefix. As 0.0.0.0/0 is a valid prefix, hence 0 is a valid prefix length.')
cefStatsPrefixQueries = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixQueries.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixQueries.setDescription('Number of queries received in the FIB database for the specified IP prefix length.')
cefStatsPrefixHCQueries = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixHCQueries.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixHCQueries.setDescription('Number of queries received in the FIB database for the specified IP prefix length. This object is a 64-bit version of cefStatsPrefixQueries.')
cefStatsPrefixInserts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixInserts.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixInserts.setDescription('Number of insert operations performed to the FIB database for the specified IP prefix length.')
cefStatsPrefixHCInserts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixHCInserts.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixHCInserts.setDescription('Number of insert operations performed to the FIB database for the specified IP prefix length. This object is a 64-bit version of cefStatsPrefixInsert.')
cefStatsPrefixDeletes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixDeletes.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixDeletes.setDescription('Number of delete operations performed to the FIB database for the specified IP prefix length.')
cefStatsPrefixHCDeletes = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixHCDeletes.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixHCDeletes.setDescription('Number of delete operations performed to the FIB database for the specified IP prefix length. This object is a 64-bit version of cefStatsPrefixDelete.')
cefStatsPrefixElements = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 8), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixElements.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixElements.setDescription('Total number of elements in the FIB database for the specified IP prefix length.')
cefStatsPrefixHCElements = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 1, 1, 9), CounterBasedGauge64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefStatsPrefixHCElements.setStatus('current')
if mibBuilder.loadTexts: cefStatsPrefixHCElements.setDescription('Total number of elements in the FIB database for the specified IP prefix length. This object is a 64-bit version of cefStatsPrefixElements.')
cefSwitchingStatsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2), )
if mibBuilder.loadTexts: cefSwitchingStatsTable.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingStatsTable.setDescription('This table specifies the CEF switch stats.')
cefSwitchingStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-CEF-MIB", "cefFIBIpVersion"), (0, "CISCO-CEF-MIB", "cefSwitchingIndex"))
if mibBuilder.loadTexts: cefSwitchingStatsEntry.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingStatsEntry.setDescription("If CEF is enabled on the Managed device, each entry specifies the switching stats. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device. entPhysicalIndex is also an index for this table which represents entities of 'module' entPhysicalClass which are capable of running CEF.")
cefSwitchingIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: cefSwitchingIndex.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingIndex.setDescription('The locally arbitrary, but unique identifier associated with this switching stats entry.')
cefSwitchingPath = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingPath.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingPath.setDescription('Switch path where the feature was executed. Available switch paths are platform-dependent. Following are the examples of switching paths: RIB : switching with CEF assistance Low-end switching (LES) : CEF switch path PAS : CEF turbo switch path. ')
cefSwitchingDrop = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 3), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingDrop.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingDrop.setDescription('Number of packets dropped by CEF.')
cefSwitchingHCDrop = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 4), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingHCDrop.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingHCDrop.setDescription('Number of packets dropped by CEF. This object is a 64-bit version of cefSwitchingDrop.')
cefSwitchingPunt = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 5), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingPunt.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingPunt.setDescription('Number of packets that could not be switched in the normal path and were punted to the next-fastest switching vector.')
cefSwitchingHCPunt = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 6), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingHCPunt.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingHCPunt.setDescription('Number of packets that could not be switched in the normal path and were punted to the next-fastest switching vector. This object is a 64-bit version of cefSwitchingPunt.')
cefSwitchingPunt2Host = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 7), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingPunt2Host.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingPunt2Host.setDescription('Number of packets that could not be switched in the normal path and were punted to the host (process switching path). For most of the switching paths, the value of this object may be similar to cefSwitchingPunt.')
cefSwitchingHCPunt2Host = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 8, 2, 1, 8), Counter64()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cefSwitchingHCPunt2Host.setStatus('current')
if mibBuilder.loadTexts: cefSwitchingHCPunt2Host.setDescription('Number of packets that could not be switched in the normal path and were punted to the host (process switching path). For most of the switching paths, the value of this object may be similar to cefSwitchingPunt. This object is a 64-bit version of cefSwitchingPunt2Host.')
cefCCGlobalTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1), )
if mibBuilder.loadTexts: cefCCGlobalTable.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalTable.setDescription('This table contains CEF consistency checker (CC) global parameters for the managed device.')
cefCCGlobalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1), ).setIndexNames((0, "CISCO-CEF-MIB", "cefFIBIpVersion"))
if mibBuilder.loadTexts: cefCCGlobalEntry.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalEntry.setDescription('If the managed device supports CEF, each entry contains the global consistency checker parameter for the managed device. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device.')
cefCCGlobalAutoRepairEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCGlobalAutoRepairEnabled.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalAutoRepairEnabled.setDescription('Once an inconsistency has been detected, CEF has the ability to repair the problem. This object indicates the status of auto-repair function for the consistency checkers.')
cefCCGlobalAutoRepairDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 2), Unsigned32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCGlobalAutoRepairDelay.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalAutoRepairDelay.setDescription("Indiactes how long the consistency checker waits to fix an inconsistency. The value of this object has no effect when the value of object cefCCGlobalAutoRepairEnabled is 'false'.")
cefCCGlobalAutoRepairHoldDown = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 3), Unsigned32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCGlobalAutoRepairHoldDown.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalAutoRepairHoldDown.setDescription("Indicates how long the consistency checker waits to re-enable auto-repair after auto-repair runs. The value of this object has no effect when the value of object cefCCGlobalAutoRepairEnabled is 'false'.")
cefCCGlobalErrorMsgEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 4), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCGlobalErrorMsgEnabled.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalErrorMsgEnabled.setDescription('Enables the consistency checker to generate an error message when it detects an inconsistency.')
cefCCGlobalFullScanAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 5), CefCCAction().clone('ccActionNone')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCGlobalFullScanAction.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalFullScanAction.setDescription("Setting the value of this object to ccActionStart(1) will start the full scan consistency checkers. The Management station should poll the cefCCGlobalFullScanStatus object to get the state of full-scan operation. Once the full-scan operation completes (value of cefCCGlobalFullScanStatus object is ccStatusDone(3)), the Management station should retrieve the values of the related stats object from the cefCCTypeTable. Setting the value of this object to ccActionAbort(2) will abort the full-scan operation. The value of this object can't be set to ccActionStart(1), if the value of object cefCCGlobalFullScanStatus is ccStatusRunning(2). The value of this object will be set to cefActionNone(1) when the full scan consistency checkers have never been activated. A Management Station cannot set the value of this object to cefActionNone(1).")
cefCCGlobalFullScanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 1, 1, 6), CefCCStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCCGlobalFullScanStatus.setStatus('current')
if mibBuilder.loadTexts: cefCCGlobalFullScanStatus.setDescription('Indicates the status of the full scan consistency checker request.')
cefCCTypeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2), )
if mibBuilder.loadTexts: cefCCTypeTable.setStatus('current')
if mibBuilder.loadTexts: cefCCTypeTable.setDescription('This table contains CEF consistency checker types specific parameters on the managed device. All detected inconsistency are signaled to the Management Station via cefInconsistencyDetection notification. ')
cefCCTypeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1), ).setIndexNames((0, "CISCO-CEF-MIB", "cefFIBIpVersion"), (0, "CISCO-CEF-MIB", "cefCCType"))
if mibBuilder.loadTexts: cefCCTypeEntry.setStatus('current')
if mibBuilder.loadTexts: cefCCTypeEntry.setDescription('If the managed device supports CEF, each entry contains the consistency checker statistics for a consistency checker type. A row may exist for each IP version type (v4 and v6) depending upon the IP version supported on the device.')
cefCCType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 1), CefCCType())
if mibBuilder.loadTexts: cefCCType.setStatus('current')
if mibBuilder.loadTexts: cefCCType.setDescription('Type of the consistency checker.')
cefCCEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 2), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCEnabled.setStatus('current')
if mibBuilder.loadTexts: cefCCEnabled.setDescription("Enables the passive consistency checker. Passive consistency checkers are disabled by default. Full-scan consistency checkers are always enabled. An attempt to set this object to 'false' for an active consistency checker will result in 'wrongValue' error.")
cefCCCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 3), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCCount.setStatus('current')
if mibBuilder.loadTexts: cefCCCount.setDescription('The maximum number of prefixes to check per scan. The default value for this object depends upon the consistency checker type. The value of this object will be irrelevant for some of the consistency checkers and will be set to 0. A Management Station cannot set the value of this object to 0.')
cefCCPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 4), Unsigned32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefCCPeriod.setStatus('current')
if mibBuilder.loadTexts: cefCCPeriod.setDescription('The period between scans for the consistency checker.')
cefCCQueriesSent = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCCQueriesSent.setStatus('current')
if mibBuilder.loadTexts: cefCCQueriesSent.setDescription('Number of prefix consistency queries sent to CEF forwarding databases by this consistency checker.')
cefCCQueriesIgnored = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCCQueriesIgnored.setStatus('current')
if mibBuilder.loadTexts: cefCCQueriesIgnored.setDescription('Number of prefix consistency queries for which the consistency checks were not performed by this consistency checker. This may be because of some internal error or resource failure.')
cefCCQueriesChecked = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCCQueriesChecked.setStatus('current')
if mibBuilder.loadTexts: cefCCQueriesChecked.setDescription('Number of prefix consistency queries processed by this consistency checker.')
cefCCQueriesIterated = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 2, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefCCQueriesIterated.setStatus('current')
if mibBuilder.loadTexts: cefCCQueriesIterated.setDescription('Number of prefix consistency queries iterated back to the master database by this consistency checker.')
cefInconsistencyRecordTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3), )
if mibBuilder.loadTexts: cefInconsistencyRecordTable.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyRecordTable.setDescription('This table contains CEF inconsistency records.')
cefInconsistencyRecordEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1), ).setIndexNames((0, "CISCO-CEF-MIB", "cefFIBIpVersion"), (0, "CISCO-CEF-MIB", "cefInconsistencyRecId"))
if mibBuilder.loadTexts: cefInconsistencyRecordEntry.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyRecordEntry.setDescription('If the managed device supports CEF, each entry contains the inconsistency record.')
cefInconsistencyRecId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: cefInconsistencyRecId.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyRecId.setDescription('The locally arbitrary, but unique identifier associated with this inconsistency record entry.')
cefInconsistencyPrefixType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 2), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyPrefixType.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyPrefixType.setDescription('The network prefix type associated with this inconsistency record.')
cefInconsistencyPrefixAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 3), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyPrefixAddr.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyPrefixAddr.setDescription('The network prefix address associated with this inconsistency record. The type of this address is determined by the value of the cefInconsistencyPrefixType object.')
cefInconsistencyPrefixLen = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 4), InetAddressPrefixLength()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyPrefixLen.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyPrefixLen.setDescription('Length in bits of the inconsistency address prefix.')
cefInconsistencyVrfName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 5), MplsVpnId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyVrfName.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyVrfName.setDescription('Vrf name associated with this inconsistency record.')
cefInconsistencyCCType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 6), CefCCType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyCCType.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyCCType.setDescription('The type of consistency checker who generated this inconsistency record.')
cefInconsistencyEntity = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 7), EntPhysicalIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyEntity.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyEntity.setDescription('The entity for which this inconsistency record was generated. The value of this object will be irrelevant and will be set to 0 when the inconsisency record is applicable for all the entities.')
cefInconsistencyReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("missing", 1), ("checksumErr", 2), ("unknown", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyReason.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyReason.setDescription('The reason for generating this inconsistency record. missing(1): the prefix is missing checksumErr(2): checksum error was found unknown(3): reason is unknown ')
entLastInconsistencyDetectTime = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 4), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: entLastInconsistencyDetectTime.setStatus('current')
if mibBuilder.loadTexts: entLastInconsistencyDetectTime.setDescription('The value of sysUpTime at the time an inconsistency is detecetd.')
cefInconsistencyReset = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 5), CefCCAction().clone('ccActionNone')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefInconsistencyReset.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyReset.setDescription("Setting the value of this object to ccActionStart(1) will reset all the active consistency checkers. The Management station should poll the cefInconsistencyResetStatus object to get the state of inconsistency reset operation. This operation once started, cannot be aborted. Hence, the value of this object cannot be set to ccActionAbort(2). The value of this object can't be set to ccActionStart(1), if the value of object cefInconsistencyResetStatus is ccStatusRunning(2). ")
cefInconsistencyResetStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 7, 6), CefCCStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cefInconsistencyResetStatus.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyResetStatus.setDescription('Indicates the status of the consistency reset request.')
cefResourceFailureNotifEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefResourceFailureNotifEnable.setStatus('current')
if mibBuilder.loadTexts: cefResourceFailureNotifEnable.setDescription('Indicates whether or not a notification should be generated on the detection of CEF resource Failure.')
cefPeerStateChangeNotifEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9, 2), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefPeerStateChangeNotifEnable.setStatus('current')
if mibBuilder.loadTexts: cefPeerStateChangeNotifEnable.setDescription('Indicates whether or not a notification should be generated on the detection of CEF peer state change.')
cefPeerFIBStateChangeNotifEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9, 3), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefPeerFIBStateChangeNotifEnable.setStatus('current')
if mibBuilder.loadTexts: cefPeerFIBStateChangeNotifEnable.setDescription('Indicates whether or not a notification should be generated on the detection of CEF FIB peer state change.')
cefNotifThrottlingInterval = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 3600), ))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefNotifThrottlingInterval.setStatus('current')
if mibBuilder.loadTexts: cefNotifThrottlingInterval.setDescription("This object controls the generation of the cefInconsistencyDetection notification. If this object has a value of zero, then the throttle control is disabled. If this object has a non-zero value, then the agent must not generate more than one cefInconsistencyDetection 'notification-event' in the indicated period, where a 'notification-event' is the transmission of a single trap or inform PDU to a list of notification destinations. If additional inconsistency is detected within the throttling period, then notification-events for these inconsistencies should be suppressed by the agent until the current throttling period expires. At the end of a throttling period, one notification-event should be generated if any inconsistency was detected since the start of the throttling period. In such a case, another throttling period is started right away. An NMS should periodically poll cefInconsistencyRecordTable to detect any missed cefInconsistencyDetection notification-events, e.g., due to throttling or transmission loss. If cefNotifThrottlingInterval notification generation is enabled, the suggested default throttling period is 60 seconds, but generation of the cefInconsistencyDetection notification should be disabled by default. If the agent is capable of storing non-volatile configuration, then the value of this object must be restored after a re-initialization of the management system. The actual transmission of notifications is controlled via the MIB modules in RFC 3413.")
cefInconsistencyNotifEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 492, 1, 9, 5), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cefInconsistencyNotifEnable.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyNotifEnable.setDescription('Indicates whether cefInconsistencyDetection notification should be generated for this managed device.')
cefResourceFailure = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 492, 0, 1)).setObjects(("CISCO-CEF-MIB", "cefResourceFailureReason"))
if mibBuilder.loadTexts: cefResourceFailure.setStatus('current')
if mibBuilder.loadTexts: cefResourceFailure.setDescription('A cefResourceFailure notification is generated when CEF resource failure on the managed entity is detected. The reason for this failure is indicated by cefResourcefFailureReason.')
cefPeerStateChange = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 492, 0, 2)).setObjects(("CISCO-CEF-MIB", "cefPeerOperState"))
if mibBuilder.loadTexts: cefPeerStateChange.setStatus('current')
if mibBuilder.loadTexts: cefPeerStateChange.setDescription('A cefPeerStateChange notification is generated if change in cefPeerOperState is detected for the peer entity.')
cefPeerFIBStateChange = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 492, 0, 3)).setObjects(("CISCO-CEF-MIB", "cefPeerFIBOperState"))
if mibBuilder.loadTexts: cefPeerFIBStateChange.setStatus('current')
if mibBuilder.loadTexts: cefPeerFIBStateChange.setDescription('A cefPeerFIBStateChange notification is generated if change in cefPeerFIBOperState is detected for the peer entity.')
cefInconsistencyDetection = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 492, 0, 4)).setObjects(("CISCO-CEF-MIB", "entLastInconsistencyDetectTime"))
if mibBuilder.loadTexts: cefInconsistencyDetection.setStatus('current')
if mibBuilder.loadTexts: cefInconsistencyDetection.setDescription("A cefInconsistencyDetection notification is generated when CEF consistency checkers detects an inconsistent prefix in one of the CEF forwarding databases. Note that the generation of cefInconsistencyDetection notifications is throttled by the agent, as specified by the 'cefNotifThrottlingInterval' object.")
cefMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1))
cefMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 2))
cefMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 2, 1)).setObjects(("CISCO-CEF-MIB", "cefGroup"), ("CISCO-CEF-MIB", "cefNotifCntlGroup"), ("CISCO-CEF-MIB", "cefNotificationGroup"), ("CISCO-CEF-MIB", "cefDistributedGroup"), ("CISCO-CEF-MIB", "cefHCStatsGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefMIBCompliance = cefMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: cefMIBCompliance.setDescription('The compliance statement for SNMP Agents which implement this MIB.')
cefGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1, 1)).setObjects(("CISCO-CEF-MIB", "cefFIBSummaryFwdPrefixes"), ("CISCO-CEF-MIB", "cefPrefixForwardingInfo"), ("CISCO-CEF-MIB", "cefPrefixPkts"), ("CISCO-CEF-MIB", "cefPrefixBytes"), ("CISCO-CEF-MIB", "cefPrefixInternalNRPkts"), ("CISCO-CEF-MIB", "cefPrefixInternalNRBytes"), ("CISCO-CEF-MIB", "cefPrefixExternalNRPkts"), ("CISCO-CEF-MIB", "cefPrefixExternalNRBytes"), ("CISCO-CEF-MIB", "cefLMPrefixSpinLock"), ("CISCO-CEF-MIB", "cefLMPrefixState"), ("CISCO-CEF-MIB", "cefLMPrefixAddr"), ("CISCO-CEF-MIB", "cefLMPrefixLen"), ("CISCO-CEF-MIB", "cefLMPrefixRowStatus"), ("CISCO-CEF-MIB", "cefPathType"), ("CISCO-CEF-MIB", "cefPathInterface"), ("CISCO-CEF-MIB", "cefPathNextHopAddr"), ("CISCO-CEF-MIB", "cefPathRecurseVrfName"), ("CISCO-CEF-MIB", "cefAdjSummaryComplete"), ("CISCO-CEF-MIB", "cefAdjSummaryIncomplete"), ("CISCO-CEF-MIB", "cefAdjSummaryFixup"), ("CISCO-CEF-MIB", "cefAdjSummaryRedirect"), ("CISCO-CEF-MIB", "cefAdjSource"), ("CISCO-CEF-MIB", "cefAdjEncap"), ("CISCO-CEF-MIB", "cefAdjFixup"), ("CISCO-CEF-MIB", "cefAdjMTU"), ("CISCO-CEF-MIB", "cefAdjForwardingInfo"), ("CISCO-CEF-MIB", "cefAdjPkts"), ("CISCO-CEF-MIB", "cefAdjBytes"), ("CISCO-CEF-MIB", "cefFESelectionSpecial"), ("CISCO-CEF-MIB", "cefFESelectionLabels"), ("CISCO-CEF-MIB", "cefFESelectionAdjLinkType"), ("CISCO-CEF-MIB", "cefFESelectionAdjInterface"), ("CISCO-CEF-MIB", "cefFESelectionAdjNextHopAddrType"), ("CISCO-CEF-MIB", "cefFESelectionAdjNextHopAddr"), ("CISCO-CEF-MIB", "cefFESelectionAdjConnId"), ("CISCO-CEF-MIB", "cefFESelectionVrfName"), ("CISCO-CEF-MIB", "cefFESelectionWeight"), ("CISCO-CEF-MIB", "cefCfgAdminState"), ("CISCO-CEF-MIB", "cefCfgOperState"), ("CISCO-CEF-MIB", "cefCfgAccountingMap"), ("CISCO-CEF-MIB", "cefCfgLoadSharingAlgorithm"), ("CISCO-CEF-MIB", "cefCfgLoadSharingID"), ("CISCO-CEF-MIB", "cefCfgTrafficStatsLoadInterval"), ("CISCO-CEF-MIB", "cefCfgTrafficStatsUpdateRate"), ("CISCO-CEF-MIB", "cefResourceMemoryUsed"), ("CISCO-CEF-MIB", "cefResourceFailureReason"), ("CISCO-CEF-MIB", "cefIntSwitchingState"), ("CISCO-CEF-MIB", "cefIntLoadSharing"), ("CISCO-CEF-MIB", "cefIntNonrecursiveAccouting"), ("CISCO-CEF-MIB", "cefStatsPrefixQueries"), ("CISCO-CEF-MIB", "cefStatsPrefixInserts"), ("CISCO-CEF-MIB", "cefStatsPrefixDeletes"), ("CISCO-CEF-MIB", "cefStatsPrefixElements"), ("CISCO-CEF-MIB", "cefSwitchingPath"), ("CISCO-CEF-MIB", "cefSwitchingDrop"), ("CISCO-CEF-MIB", "cefSwitchingPunt"), ("CISCO-CEF-MIB", "cefSwitchingPunt2Host"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefGroup = cefGroup.setStatus('current')
if mibBuilder.loadTexts: cefGroup.setDescription('This group consists of all the managed objects which are applicable to CEF irrespective of the value of object cefDistributionOperState.')
cefDistributedGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1, 2)).setObjects(("CISCO-CEF-MIB", "cefCfgDistributionAdminState"), ("CISCO-CEF-MIB", "cefCfgDistributionOperState"), ("CISCO-CEF-MIB", "cefPeerOperState"), ("CISCO-CEF-MIB", "cefPeerNumberOfResets"), ("CISCO-CEF-MIB", "cefPeerFIBOperState"), ("CISCO-CEF-MIB", "cefCCGlobalAutoRepairEnabled"), ("CISCO-CEF-MIB", "cefCCGlobalAutoRepairDelay"), ("CISCO-CEF-MIB", "cefCCGlobalAutoRepairHoldDown"), ("CISCO-CEF-MIB", "cefCCGlobalErrorMsgEnabled"), ("CISCO-CEF-MIB", "cefCCGlobalFullScanStatus"), ("CISCO-CEF-MIB", "cefCCGlobalFullScanAction"), ("CISCO-CEF-MIB", "cefCCEnabled"), ("CISCO-CEF-MIB", "cefCCCount"), ("CISCO-CEF-MIB", "cefCCPeriod"), ("CISCO-CEF-MIB", "cefCCQueriesSent"), ("CISCO-CEF-MIB", "cefCCQueriesIgnored"), ("CISCO-CEF-MIB", "cefCCQueriesChecked"), ("CISCO-CEF-MIB", "cefCCQueriesIterated"), ("CISCO-CEF-MIB", "entLastInconsistencyDetectTime"), ("CISCO-CEF-MIB", "cefInconsistencyPrefixType"), ("CISCO-CEF-MIB", "cefInconsistencyPrefixAddr"), ("CISCO-CEF-MIB", "cefInconsistencyPrefixLen"), ("CISCO-CEF-MIB", "cefInconsistencyVrfName"), ("CISCO-CEF-MIB", "cefInconsistencyCCType"), ("CISCO-CEF-MIB", "cefInconsistencyEntity"), ("CISCO-CEF-MIB", "cefInconsistencyReason"), ("CISCO-CEF-MIB", "cefInconsistencyReset"), ("CISCO-CEF-MIB", "cefInconsistencyResetStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefDistributedGroup = cefDistributedGroup.setStatus('current')
if mibBuilder.loadTexts: cefDistributedGroup.setDescription("This group consists of all the Managed objects which are only applicable to CEF is the value of object cefDistributionOperState is 'up'.")
cefHCStatsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1, 3)).setObjects(("CISCO-CEF-MIB", "cefPrefixHCPkts"), ("CISCO-CEF-MIB", "cefPrefixHCBytes"), ("CISCO-CEF-MIB", "cefPrefixInternalNRHCPkts"), ("CISCO-CEF-MIB", "cefPrefixInternalNRHCBytes"), ("CISCO-CEF-MIB", "cefPrefixExternalNRHCPkts"), ("CISCO-CEF-MIB", "cefPrefixExternalNRHCBytes"), ("CISCO-CEF-MIB", "cefAdjHCPkts"), ("CISCO-CEF-MIB", "cefAdjHCBytes"), ("CISCO-CEF-MIB", "cefStatsPrefixHCQueries"), ("CISCO-CEF-MIB", "cefStatsPrefixHCInserts"), ("CISCO-CEF-MIB", "cefStatsPrefixHCDeletes"), ("CISCO-CEF-MIB", "cefStatsPrefixHCElements"), ("CISCO-CEF-MIB", "cefSwitchingHCDrop"), ("CISCO-CEF-MIB", "cefSwitchingHCPunt"), ("CISCO-CEF-MIB", "cefSwitchingHCPunt2Host"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefHCStatsGroup = cefHCStatsGroup.setStatus('current')
if mibBuilder.loadTexts: cefHCStatsGroup.setDescription('This group consists of all the 64-bit counter objects which are applicable to CEF irrespective of the value of object cefDistributionOperState.')
cefNotifCntlGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1, 5)).setObjects(("CISCO-CEF-MIB", "cefResourceFailureNotifEnable"), ("CISCO-CEF-MIB", "cefPeerStateChangeNotifEnable"), ("CISCO-CEF-MIB", "cefPeerFIBStateChangeNotifEnable"), ("CISCO-CEF-MIB", "cefNotifThrottlingInterval"), ("CISCO-CEF-MIB", "cefInconsistencyNotifEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefNotifCntlGroup = cefNotifCntlGroup.setStatus('current')
if mibBuilder.loadTexts: cefNotifCntlGroup.setDescription('This group of objects controls the sending of CEF Notifications.')
cefNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 492, 2, 1, 6)).setObjects(("CISCO-CEF-MIB", "cefResourceFailure"), ("CISCO-CEF-MIB", "cefPeerStateChange"), ("CISCO-CEF-MIB", "cefPeerFIBStateChange"), ("CISCO-CEF-MIB", "cefInconsistencyDetection"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cefNotificationGroup = cefNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: cefNotificationGroup.setDescription('This group contains the notifications for the CEF MIB.')
mibBuilder.exportSymbols("CISCO-CEF-MIB", ciscoCefMIBObjects=ciscoCefMIBObjects, cefInconsistencyDetection=cefInconsistencyDetection, cefAdjConnId=cefAdjConnId, cefCCQueriesIgnored=cefCCQueriesIgnored, cefFESelectionAdjConnId=cefFESelectionAdjConnId, cefFESelectionEntry=cefFESelectionEntry, cefLMPrefixLen=cefLMPrefixLen, cefResourceMemoryUsed=cefResourceMemoryUsed, cefFIBSummaryEntry=cefFIBSummaryEntry, cefCfgTable=cefCfgTable, cefCfgTrafficStatsLoadInterval=cefCfgTrafficStatsLoadInterval, ciscoCefMIBNotifs=ciscoCefMIBNotifs, cefFIBSummaryTable=cefFIBSummaryTable, cefCCCount=cefCCCount, cefInconsistencyRecordTable=cefInconsistencyRecordTable, cefCCTypeEntry=cefCCTypeEntry, cefPeerStateChange=cefPeerStateChange, cefLMPrefixDestAddrType=cefLMPrefixDestAddrType, cefPathType=cefPathType, cefAdjSource=cefAdjSource, cefSwitchingPath=cefSwitchingPath, cefAdjTable=cefAdjTable, cefCCPeriod=cefCCPeriod, cefFESelectionLabels=cefFESelectionLabels, cefStatsPrefixInserts=cefStatsPrefixInserts, cefAdjBytes=cefAdjBytes, cefIntLoadSharing=cefIntLoadSharing, cefStatsPrefixHCDeletes=cefStatsPrefixHCDeletes, cefLMPrefixTable=cefLMPrefixTable, cefSwitchingDrop=cefSwitchingDrop, entLastInconsistencyDetectTime=entLastInconsistencyDetectTime, cefInconsistencyNotifEnable=cefInconsistencyNotifEnable, cefCfgAdminState=cefCfgAdminState, cefCCGlobalAutoRepairHoldDown=cefCCGlobalAutoRepairHoldDown, cefResourceFailureNotifEnable=cefResourceFailureNotifEnable, cefFESelectionWeight=cefFESelectionWeight, cefPrefixAddr=cefPrefixAddr, cefPrefixLen=cefPrefixLen, cefCfgLoadSharingAlgorithm=cefCfgLoadSharingAlgorithm, cefInconsistencyPrefixAddr=cefInconsistencyPrefixAddr, cefSwitchingStatsEntry=cefSwitchingStatsEntry, cefPrefixType=cefPrefixType, cefPrefixInternalNRPkts=cefPrefixInternalNRPkts, cefAdjSummaryLinkType=cefAdjSummaryLinkType, cefAdjMTU=cefAdjMTU, cefPrefixExternalNRHCPkts=cefPrefixExternalNRHCPkts, cefAdjFixup=cefAdjFixup, cefFESelectionSpecial=cefFESelectionSpecial, cefFESelectionAdjLinkType=cefFESelectionAdjLinkType, cefPathRecurseVrfName=cefPathRecurseVrfName, cefNotificationGroup=cefNotificationGroup, cefCfgEntry=cefCfgEntry, cefCCQueriesSent=cefCCQueriesSent, cefPathNextHopAddr=cefPathNextHopAddr, cefLMPrefixEntry=cefLMPrefixEntry, cefPrefixEntry=cefPrefixEntry, cefPrefixInternalNRHCPkts=cefPrefixInternalNRHCPkts, cefFESelectionName=cefFESelectionName, cefInconsistencyVrfName=cefInconsistencyVrfName, cefLMPrefixRowStatus=cefLMPrefixRowStatus, cefCCType=cefCCType, cefFESelectionAdjNextHopAddrType=cefFESelectionAdjNextHopAddrType, cefMIBCompliance=cefMIBCompliance, cefPathId=cefPathId, cefPrefixHCBytes=cefPrefixHCBytes, cefSwitchingHCPunt2Host=cefSwitchingHCPunt2Host, cefPeerFIBEntry=cefPeerFIBEntry, cefInconsistencyReset=cefInconsistencyReset, cefStats=cefStats, cefResourceFailureReason=cefResourceFailureReason, cefStatsPrefixLenTable=cefStatsPrefixLenTable, cefPeer=cefPeer, cefCCEnabled=cefCCEnabled, cefAdjNextHopAddr=cefAdjNextHopAddr, cefStatsPrefixElements=cefStatsPrefixElements, cefCCGlobalErrorMsgEnabled=cefCCGlobalErrorMsgEnabled, cefFE=cefFE, cefAdjNextHopAddrType=cefAdjNextHopAddrType, cefInconsistencyResetStatus=cefInconsistencyResetStatus, cefCCQueriesChecked=cefCCQueriesChecked, cefCCGlobalAutoRepairDelay=cefCCGlobalAutoRepairDelay, cefAdjSummaryIncomplete=cefAdjSummaryIncomplete, cefAdjSummary=cefAdjSummary, cefResourceTable=cefResourceTable, cefNotifCntl=cefNotifCntl, cefFIBSummaryFwdPrefixes=cefFIBSummaryFwdPrefixes, cefPeerTable=cefPeerTable, cefGroup=cefGroup, cefAdjSummaryComplete=cefAdjSummaryComplete, cefFESelectionTable=cefFESelectionTable, cefCfgDistributionOperState=cefCfgDistributionOperState, cefInconsistencyRecordEntry=cefInconsistencyRecordEntry, cefPathTable=cefPathTable, cefPeerNumberOfResets=cefPeerNumberOfResets, cefCCGlobalFullScanAction=cefCCGlobalFullScanAction, cefFESelectionId=cefFESelectionId, cefPrefixHCPkts=cefPrefixHCPkts, cefSwitchingPunt=cefSwitchingPunt, cefIntTable=cefIntTable, cefCCGlobalFullScanStatus=cefCCGlobalFullScanStatus, cefSwitchingIndex=cefSwitchingIndex, cefSwitchingHCDrop=cefSwitchingHCDrop, cefGlobal=cefGlobal, cefCCGlobalTable=cefCCGlobalTable, cefInconsistencyPrefixType=cefInconsistencyPrefixType, cefDistributedGroup=cefDistributedGroup, cefResourceFailure=cefResourceFailure, cefAdjHCBytes=cefAdjHCBytes, cefAdjSummaryEntry=cefAdjSummaryEntry, cefAdjSummaryRedirect=cefAdjSummaryRedirect, cefPrefixBytes=cefPrefixBytes, cefInconsistencyPrefixLen=cefInconsistencyPrefixLen, cefHCStatsGroup=cefHCStatsGroup, cefFIBSummary=cefFIBSummary, cefInconsistencyCCType=cefInconsistencyCCType, cefCfgOperState=cefCfgOperState, cefIntEntry=cefIntEntry, cefPrefixForwardingInfo=cefPrefixForwardingInfo, cefInconsistencyEntity=cefInconsistencyEntity, cefCCTypeTable=cefCCTypeTable, cefCC=cefCC, cefStatsPrefixDeletes=cefStatsPrefixDeletes, cefPeerOperState=cefPeerOperState, cefStatsPrefixLenEntry=cefStatsPrefixLenEntry, cefPrefixExternalNRBytes=cefPrefixExternalNRBytes, entPeerPhysicalIndex=entPeerPhysicalIndex, cefPrefixInternalNRHCBytes=cefPrefixInternalNRHCBytes, cefCfgTrafficStatsUpdateRate=cefCfgTrafficStatsUpdateRate, ciscoCefMIB=ciscoCefMIB, cefPrefixExternalNRPkts=cefPrefixExternalNRPkts, cefAdj=cefAdj, cefAdjSummaryFixup=cefAdjSummaryFixup, cefStatsPrefixQueries=cefStatsPrefixQueries, cefMIBCompliances=cefMIBCompliances, cefFESelectionVrfName=cefFESelectionVrfName, cefLMPrefixSpinLock=cefLMPrefixSpinLock, cefPrefixTable=cefPrefixTable, cefFIB=cefFIB, cefPrefixInternalNRBytes=cefPrefixInternalNRBytes, cefLMPrefixState=cefLMPrefixState, PYSNMP_MODULE_ID=ciscoCefMIB, cefCfgAccountingMap=cefCfgAccountingMap, cefSwitchingStatsTable=cefSwitchingStatsTable, cefSwitchingPunt2Host=cefSwitchingPunt2Host, cefPrefixExternalNRHCBytes=cefPrefixExternalNRHCBytes, cefFIBIpVersion=cefFIBIpVersion, cefStatsPrefixHCQueries=cefStatsPrefixHCQueries, cefIntNonrecursiveAccouting=cefIntNonrecursiveAccouting, cefFESelectionAdjInterface=cefFESelectionAdjInterface, cefCCGlobalAutoRepairEnabled=cefCCGlobalAutoRepairEnabled, cefPathEntry=cefPathEntry, cefPathInterface=cefPathInterface, cefCCQueriesIterated=cefCCQueriesIterated, cefAdjForwardingInfo=cefAdjForwardingInfo, cefResourceEntry=cefResourceEntry, cefStatsPrefixLen=cefStatsPrefixLen, cefAdjSummaryTable=cefAdjSummaryTable, cefStatsPrefixHCElements=cefStatsPrefixHCElements, cefPeerFIBStateChange=cefPeerFIBStateChange, cefInconsistencyRecId=cefInconsistencyRecId, cefPeerStateChangeNotifEnable=cefPeerStateChangeNotifEnable, cefLMPrefixAddr=cefLMPrefixAddr, cefAdjEncap=cefAdjEncap, cefAdjEntry=cefAdjEntry, cefPeerEntry=cefPeerEntry, cefNotifCntlGroup=cefNotifCntlGroup, cefPeerFIBTable=cefPeerFIBTable, cefAdjHCPkts=cefAdjHCPkts, cefInterface=cefInterface, cefIntSwitchingState=cefIntSwitchingState, cefNotifThrottlingInterval=cefNotifThrottlingInterval, cefFESelectionAdjNextHopAddr=cefFESelectionAdjNextHopAddr, cefInconsistencyReason=cefInconsistencyReason, cefLMPrefixDestAddr=cefLMPrefixDestAddr, cefCCGlobalEntry=cefCCGlobalEntry, cefPeerFIBStateChangeNotifEnable=cefPeerFIBStateChangeNotifEnable, cefMIBGroups=cefMIBGroups, cefPeerFIBOperState=cefPeerFIBOperState, ciscoCefMIBConform=ciscoCefMIBConform, cefPrefixPkts=cefPrefixPkts, cefCfgLoadSharingID=cefCfgLoadSharingID, cefCfgDistributionAdminState=cefCfgDistributionAdminState, cefAdjPkts=cefAdjPkts, cefStatsPrefixHCInserts=cefStatsPrefixHCInserts, cefSwitchingHCPunt=cefSwitchingHCPunt)
|
"""Utilities for speech recognition."""
class TranscriptMap(object):
"""An abstract class representing a map from transcripts to labels.
All other datasets should subclass it. All subclasses should override
``trans2label``.
"""
def trans2label(self, transcript):
"""Convert a transcript to (a sequence of) labels."""
raise NotImplementedError
def trans2oov(self, transcript):
"""Convert a transcript to out-of-vocabulary words."""
raise NotImplementedError
def trans2vocab(self, transcript):
"""Convert a transcript to a list of vocabularies."""
raise NotImplementedError
def label2vocab(self, labels):
"""Convert a label sequence to a vocabulary sequence."""
raise NotImplementedError
def vocab2trans(self, vocabs):
"""Convert a vocabulary sequence to a string."""
raise NotImplementedError
def transcribable(self, transcript):
"""Determine if transcript is transcribable."""
return len(self.trans2oov(transcript)) == 0
def __len__(self):
"""Return number of vocabularies in the map."""
raise NotImplementedError
def __str__(self):
"""Print transcript map info."""
report = """
[{}]: Total [{}] available vocabularies.
""".format(self.__class__.__name__,
len(self))
return report
class PhonemeMap(TranscriptMap):
"""Construct a phoneme set, filler set, and a dictionary for speech rec."""
def __init__(self, dictpath, phonepath=None, fillerpath=None,
replacemap=None):
"""Construct a phoneme (and filler) map from a dictionary.
Optionally, if `phonepath` and `fillerpath` are predefined, use them
as the default map and filter out-of-vocabulary words in dictionary.
"""
if phonepath is not None: # use user-defined phone list
pset = self.load_phoneset(phonepath)
if fillerpath is not None:
pset.union(self.load_fillerset(fillerpath))
# Construct dictionary
self.dict, _ = self.load_dictionary(dictpath, phoneset=pset)
else: # infer phone list from dictionary
self.dict, pset = self.load_dictionary(dictpath, phoneset=None)
self.vocabdict = {p: ii for ii, p in enumerate(sorted(pset))}
self.replacedict = replacemap
def load_phoneset(self, path):
"""Load phoneme set from `path`.
Assume the file has the following format:
<phone 1>
<phone 2>
...
<phone N>
"""
plist = []
with open(path) as fp:
for line in fp.readlines():
plist.append(line.strip())
return set(plist)
def load_fillerset(self, path):
"""Load filler set from `path`.
Assume the file has the following format:
<filler 1>
<filler 2>
...
<filler N>
"""
return self.load_phoneset(path)
def load_dictionary(self, path, phoneset=None):
"""Load dictionary from `path`.
Assume the file has the following format:
<word 1> <phone 1> <phone 2> ...
<word 2> <phone 1> <phone 2> ...
... ...
<word N> <phone 1> <phone 2> ...
Returns the dictionary and the phoneme set.
"""
d = {}
if phoneset is None: # construct pset on-the-fly
pset = set([])
else: # assume existing pset; returns nothing
pset = None
with open(path) as fp:
for line in fp.readlines():
line = line.strip().split()
word, plist = line[0].upper(), line[1:]
assert word not in d, "Redefinition of word: [{}]".format(d)
if phoneset is None: # no default set - construct one
d[word] = plist
pset.update(set(plist))
else: # filter out OOV words
oov = False
for p in plist:
if p not in phoneset:
oov = True
break
if not oov:
d[word] = plist
return d, pset
def validate_phone(self, vocabset, dictionary):
"""Validate the vocabulary set and dictionary.
This should be called upon loading a phoneset and dictionary.
"""
for word, vlist in dictionary.items():
for v in vlist:
assert v in vocabset, "[{}] of [{}] not in vocabset!".format(
v, word)
def trans2label(self, transcript):
"""Convert a transcript string to phoneme indices.
Assuming all CAPITALIZED words in transcript exist in dictionary.
"""
out = []
for word in self._replace(transcript.upper()).split():
out.extend([self.vocabdict[p] for p in self.dict[word]])
return out
def trans2oov(self, transcript):
"""Convert a transcript string to a list of out-of-vocabulary words.
Assuming dictionary words are CAPITALIZED.
"""
out = []
for word in self._replace(transcript.upper()).split():
if word.upper() not in self.dict:
out.append(word)
return {w: out.count(w) for w in set(out)}
def trans2vocab(self, transcript):
"""Convert a transcript string to a list of phonemes.
Assuming dictionary words are CAPITALIZED.
"""
out = []
for word in self._replace(transcript.upper()).split():
out.extend(self.dict[word.upper()])
return out
def _replace(self, transcript):
"""Replace a transcript using `replacedict`."""
if self.replacedict is None:
return transcript
for orig, repl in self.replacedict.items():
transcript = transcript.replace(orig.upper(), repl.upper())
return transcript
def __len__(self):
"""Return number of phones in the map."""
return len(self.vocabdict)
class CharacterMap(TranscriptMap):
"""Construct a character map for speech rec."""
def __init__(self, charset, replacemap=None):
"""Construct a character map from a character set.
Optionally, take a replacement dictionary in which some particular
strings are mapped to another string. This is useful for removing
special characters and replacing special strings such as ?QUESTIONMARK.
"""
sorted_char = sorted(charset)
self.vocabdict = {c.upper(): ii for ii, c in enumerate(sorted_char)}
self.labeldict = {ii: c.upper() for ii, c in enumerate(sorted_char)}
self.replacedict = None
if replacemap is not None:
self.replacedict = replacemap
def trans2label(self, transcript):
"""Convert a transcript string to a sequence of labels."""
out = []
for c in self._replace(transcript.upper()):
out.append(self.vocabdict[c])
return out
def trans2vocab(self, transcript):
"""Convert a transcript string to a sequence of characters."""
out = []
for c in self._replace(transcript.upper()):
out.append(c)
return out
def label2vocab(self, labels):
"""Convert a label sequence to character sequence."""
return [self.labeldict[l] for l in labels]
def vocab2trans(self, vocab):
"""Convert a sequence of characters to a string."""
return ''.join(vocab)
def trans2oov(self, transcript):
"""Convert a transcript string to a list of oov chars."""
out = []
for c in self._replace(transcript.upper()):
if c not in self.vocabdict:
out.append(c)
return {w: out.count(w) for w in set(out)}
def _replace(self, transcript):
"""Replace a transcript using `replacedict`."""
if self.replacedict is None:
return transcript
for orig, repl in self.replacedict.items():
transcript = transcript.replace(orig.upper(), repl.upper())
return transcript
def __len__(self):
"""Return number of characters in the map."""
return len(self.vocabdict)
def levenshtein(src, tar):
"""Compute the Levenshtein (edit) distance between two strings.
The edit distance is the number of steps taken to transform `src` to
`tar`. Break tie by preferring deletion, then insertion, and finally
substitution.
Parameters
----------
src: str
src string.
tar: str
tar string.
Returns
-------
type: tuple of 4 int
Total distance, number of deletions, insertions, and substitutions.
"""
ss = len(src)
tt = len(tar)
if ss == 0:
return tt, 0, tt, 0
if tt == 0:
return ss, ss, 0, 0
UP, LEFT, UPLEFT = 'DIS' # order is important for tiebreak
costs = [] # holds cached cost and parent node at each (i,j)
for ii in range(ss+1):
if ii == 0:
costs.append([(0, None)] + [(i, LEFT) for i in range(1, tt+1)])
continue
costs.append([])
for jj in range(tt+1):
if jj == 0:
costs[ii].append((ii, UP))
continue
cost = 0 if (src[ii-1] == tar[jj-1]) else 1
up = jj + 1 if ii-1 < 0 else costs[ii-1][jj][0]
left = ii + 1 if jj-1 < 0 else costs[ii][jj-1][0]
if ii-1 < 0 and jj-1 < 0:
upleft = 0
elif ii-1 < 0:
upleft = jj
elif jj-1 < 0:
upleft = ii
else:
upleft = costs[ii-1][jj-1][0]
# break tie by: deletion, insertion, substitution
costs[ii].append(min(zip((up+1, left+1, upleft+cost),
(UP, LEFT, UPLEFT))))
# Backtrack to beginning and record types of error along the way
insert = 0
delete = 0
substitute = 0
ii, jj = ss, tt
cost, parent = costs[ii][jj] # start from bottom right
while parent:
if parent == UP:
ii -= 1
delete += 1
elif parent == LEFT:
jj -= 1
insert += 1
else:
ii -= 1
jj -= 1
if cost != costs[ii][jj][0]:
substitute += 1
cost, parent = costs[ii][jj]
return costs[-1][-1][0], delete, insert, substitute
|
arr = [[1, 2, 3, 12],
[4, 5, 6, 45],
[7, 8, 9, 78]]
x = 3
print("start")
w = len(arr)
h = len(arr[0])
i = 0
j = 0
while i < w and j < h and arr[i][j] < x:
ib = i
ie = w - 1
i2 = -1
while ib < ie:
i2n = (ie - ib) // 2
if i2 == i2n:
break
i2 = i2n
print("i2 ", i2, ib, ie)
if arr[i2][j] < x:
ib = i2
elif arr[i2][j] == x:
print("present")
break
else:
ie = i2
while arr[i2][j] > x and i2 >= i:
print("i back")
i2 -= 1
if arr[i2][j] == x:
print("present")
break
elif arr[i2][j] > x:
print("not present")
i = i2
print("i ", i)
jb = j
je = h - 1
j2 = -1
while jb < je:
j2n = (je - jb) // 2
print("j2n ", j2n)
if j2 == j2n:
print("b")
break
j2 = j2n
print("j2 ", j2, jb, je)
if arr[i][j2] < x:
jb = j2
elif arr[i][j2] == x:
print("present")
break
else:
je = j2
while arr[i][j2] > x and j2 >= j:
print("j back")
j2 -= 1
if arr[i][j2] == x:
print("present")
elif arr[i][j2] > x:
print("not present")
j = j2
print("j ", j2)
print("present" if arr[i][j] == x else "not present")
|
"""
Copyright 2016 Pawel Bartusiak
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.
"""
class ConfigDefaults:
def __init__(self, sqlconn):
self.sqlConnectionChannel, self.sqlCursorChannel = sqlconn
self.columns = {
"grouping": 0,
"variable": 1,
"value": 2,
"args": 3,
"userlevel": 4,
}
self.defaults = {
"birthdays": self.birthdays,
"commands": self.commands,
"config": self.config,
"faq": self.faq,
"filters": self.filters,
"regulars": self.regulars,
}
self.sqlInsertString = "INSERT INTO config (grouping, variable, value, args, userlevel) VALUES (?, ?, ?, ?, ?)"
self.sqlUpdateString = "UPDATE config SET value=?, args=?, userlevel=? WHERE grouping=? AND variable=?"
self.sqlDeleteString = "DELETE FROM config WHERE grouping=? AND variable=?"
self.sqlExecute = self.sqlCursorChannel.execute
def all_(self, defaultto=0):
self.bot(defaultto)
self.birthdays(defaultto)
self.commands(defaultto)
self.config(defaultto)
self.faq(defaultto)
self.filters(defaultto)
self.regulars(defaultto)
return
def updatesql(self, grouping, variables, defaultto, variable):
self.sqlExecute("SELECT grouping, variable FROM config WHERE grouping = ?", (grouping,))
sqlCursorOffload = self.sqlCursorChannel.fetchall()
# Default-to Modes
#
# -1 - Delete
# 0 - Pass
# 1 - Append and Overwrite
# 2 - Append
# 3 - Overwrite
if defaultto == -1:
for entry in sqlCursorOffload:
if not [varset[1] == entry[1] for varset in variables]:
self.sqlCursorChannel.execute(self.sqlDeleteString, (entry[0], entry[1]))
else:
pass
self.sqlConnectionChannel.commit()
return
if defaultto == 0:
return
if defaultto == 1:
for varset in variables:
if True in [entry[1] == varset[1] for entry in sqlCursorOffload]:
self.sqlCursorChannel.execute(self.sqlUpdateString, (varset[2], varset[3], varset[4],
varset[0], varset[1]))
else:
self.sqlCursorChannel.execute(self.sqlInsertString, varset)
self.sqlConnectionChannel.commit()
return
if defaultto == 2:
for varset in variables:
if True in [entry[1] == varset[1] for entry in sqlCursorOffload]:
pass
else:
self.sqlCursorChannel.execute(self.sqlInsertString, varset)
self.sqlConnectionChannel.commit()
return
if defaultto == 3:
for varset in variables:
if True in [entry[1] == variable for entry in sqlCursorOffload] and varset[1] == variable:
self.sqlCursorChannel.execute(self.sqlUpdateString, (varset[2], varset[3], varset[4],
varset[0], varset[1]))
else:
pass
self.sqlConnectionChannel.commit()
return
def bot(self, defaultto, variable=None):
variables = [
("bot", "silence", False, "boolean", 400),
]
self.updatesql("bot", variables, defaultto, variable)
def birthdays(self, defaultto, variable=None):
variables = [
("birthdays", "enabled", True, "boolean", 400),
("birthdays", "keyword", "$birthdays", "string", 400),
("birthdays", "min_userlevel", 150, "integer,700-0", 400),
("birthdays", "min_userlevel_edit", 400, "integer,700-0", 400),
]
self.updatesql("birthdays", variables, defaultto, variable)
return
def commands(self, defaultto, variable=None):
variables = [
("commands", "enabled", True, "boolean", 400),
("commands", "keyword", "$commands", "string", 400),
("commands", "min_userlevel", 0, "integer,700-0", 400),
("commands", "min_userlevel_edit", 250, "integer,700-0", 400),
]
self.updatesql("commands", variables, defaultto, variable)
return
def config(self, defaultto, variable=None):
variables = [
("config", "min_userlevel_edit", 250, "integer,700-0", 400),
]
self.updatesql("config", variables, defaultto, variable)
return
def faq(self, defaultto, variable=None):
variables = [
("faq", "enabled", True, "boolean", 400),
("faq", "keyword", "$faq", "string", 400),
("faq", "min_userlevel", 0, "integer,700-0", 400),
("faq", "min_userlevel_edit", 400, "integer,700-0", 400),
]
self.updatesql("faq", variables, defaultto, variable)
return
def filters(self, defaultto, variable=None):
variables = [
("filters", "enabled", True, "boolean", 400),
("filters", "keyword", "$filters", "string", 400),
("filters", "min_userlevel", 0, "integer,700-0", 400),
("filters", "min_userlevel_edit", 250, "integer,700-0", 400),
("filters", "banphrases_enabled", True, "boolean", 400),
("filters", "banphrases_max_userlevel", 150, "integer,249-0", 400),
("filters", "banphrases_first_timeout", 10, "integer,86400-1", 400),
("filters", "banphrases_second_timeout", 600, "integer,86400-1", 400),
("filters", "banphrases_third_timeout", 600, "integer,86400-1", 400),
("filters", "banphrases_ban_after_third", False, "boolean", 400),
("filters", "banphrases_message", None, "string", 400),
("filters", "emotespam_enabled", True, "boolean", 400),
("filters", "emotespam_max_userlevel", 150, "integer,249-0", 400),
("filters", "emotespam_first_timeout", 10, "integer,86400-1", 400),
("filters", "emotespam_second_timeout", 600, "integer,86400-1", 400),
("filters", "emotespam_third_timeout", 600, "integer,86400-1", 400),
("filters", "emotespam_ban_after_third", False, "boolean", 400),
("filters", "emotespam_message", None, "string", 400),
("filters", "link_enabled", True, "boolean", 400),
("filters", "link_max_userlevel", 150, "integer,249-0", 400),
("filters", "link_first_timeout", 10, "integer,86400-1", 400),
("filters", "link_second_timeout", 600, "integer,86400-1", 400),
("filters", "link_third_timeout", 600, "integer,86400-1", 400),
("filters", "link_ban_after_third", False, "boolean", 400),
("filters", "link_message", None, "string", 400),
("filters", "spam_enabled", True, "boolean", 400),
("filters", "spam_max_userlevel", 150, "integer,249-0", 400),
("filters", "spam_first_timeout", 10, "integer,86400-1", 400),
("filters", "spam_second_timeout", 600, "integer,86400-1", 400),
("filters", "spam_third_timeout", 600, "integer,86400-1", 400),
("filters", "spam_ban_after_third", False, "boolean", 400),
("filters", "spam_message", None, "string", 400),
]
self.updatesql("filters", variables, defaultto, variable)
return
def regulars(self, defaultto, variable=None):
variables = [
("regulars", "enabled", True, "boolean", 400),
("regulars", "keyword", "$regulars", "string", 400),
("regulars", "min_userlevel", 0, "integer,700-0", 400),
("regulars", "min_userlevel_edit", 250, "integer,700-0", 400),
]
self.updatesql("regulars", variables, defaultto, variable)
return
class DefaultCommandNames:
def __init__(self, sqlconn):
self.sqlConnectionChannel, self.sqlCursorChannel = sqlconn
def boolean(value):
truevalues = ["True", "true", "1"]
return value in truevalues
|
"""Skinny, measuring nudity and skin percentage in images.
This module measures the skin coefficient of images in order to determine
if the people in it are nude or not.
Example:
The module is a twistd plugin so it can be run by::
$ twistd -n skinny
Flags:
--port -p (int): Port number for the plugin to run. Defaults to 8000
"""
|
'''
Min Depth of Binary Tree
Asked in: Facebook, Amazon
https://www.interviewbit.com/problems/min-depth-of-binary-tree/
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
NOTE : The path has to end on a leaf node.
Example :
1
/
2
min depth = 2.
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def minDepth(A):
if not A: return 0
min_depth = None
stack = [(A, 1)]
while stack:
n, d = stack.pop()
if not n.left and not n.right:
if min_depth is None or min_depth>d:
min_depth = d
if n.right:
stack.append((n.right, d+1))
if n.left:
stack.append((n.left, d+1))
return min_depth
|
def selection_sort(nums):
# This value of i corresponds to how many values were sorted
for i in range(len(nums)):
# We assume that the first item of the unsorted segment is the smallest
lowest_value_index = i
# This loop iterates over the unsorted items
for j in range(i + 1, len(nums)):
if nums[j] < nums[lowest_value_index]:
lowest_value_index = j
# Swap values of the lowest unsorted element with the first unsorted
# element
nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i]
# Verify it works
random_list_of_nums = [12, 8, 3, 20, 11]
selection_sort(random_list_of_nums)
print(random_list_of_nums) |
# Q: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000, Find the product abc.
def main():
print (find_abc(1000))
# We do this in a function to avoid breaking from nested loops and instead just return
def find_abc(total):
# since a, b, c are natural numbers and a+b+c = 1000, they all cannot be larger than 998 or less than 1
for a in range(1, total - 2): # -2 bc the minimum value for b and c is 1 (natural numbers)
for b in range(a, total - 2):
c = total - a - b
if a * a + b * b == c * c:
return (a*b*c) # the question specifies there exists exactly one case so we can return at this point
if __name__ == '__main__':
main()
|
annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percent of your salary to save, as a '
'decimal: '))
total_cost = float(input('Enter cost of your dream home: '))
portion_down_payment = 0.25
current_savings = 0
r = 0.04
months = 0
portion_monthly_salary = portion_saved * annual_salary / 12
while current_savings < portion_down_payment * total_cost:
return_on_investment = current_savings * r / 12
current_savings += return_on_investment + portion_monthly_salary
months += 1
print('Number of months: %d' % months)
|
def greet(name):
get_greet = f"Hi, {name}"
return get_greet
greeting = greet("Ahmed")
print(greeting)
|
def submission_choice(assignment, user_id, subs):
"""
If a student has multiple submissions, interactively prompt
the user to choose one
"""
# If they have multiple submissions, make them choose
if len(subs) > 1:
print("{0} submissions found for {1}, choose one:\n"
.format(len(subs), user_id))
i = 1
print("Index\tCreated")
for s in subs:
info = assignment.docker_cli.inspect_container(s.full_id)
print("{0}\t{1}".format(i, info['Created']))
i += 1
choice = -1
while choice < 0 or choice >= len(subs):
choice = input("Please enter your selection: ")
try:
choice = int(choice)-1
except TypeError:
pass
return subs[choice]
else:
return subs[0]
def make_help_parser(parser, subparsers, help_text):
def show_help(args):
new_args = list(args.command)
new_args.append("--help")
parser.parse_args(new_args)
help_parser = subparsers.add_parser("help", help=help_text)
help_parser.add_argument("command", nargs="*",
help="Command to get help with")
help_parser.set_defaults(run=show_help)
|
def removeElement(nums, val):
newArray = [n for n in nums if n != val]
print(newArray)
print(len(newArray))
|
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data # Pointer to data
self.next = None # Initialize next as null
def deleteNode(head, position):
if head is None:
return head
elif position == 0:
return head.next
prev_node = head
current_node = head
current_position = 0
while current_position < position:
current_position = current_position + 1
prev_node = current_node
current_node = current_node.next
prev_node.next = current_node.next
return head |
# -*- coding: utf-8 -*-
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[2][2])
sum = 0
for x in range(101):
sum = sum + x
print(sum)
sum1 = 0
n = 99
while n>0:
sum1 = sum1 + n
n = n -2
print(sum1)
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print('Hello , %s !'%(name))
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2)) |
class Soldado:
def __init__(self, nombre, raza):
self.nombre = nombre
self.raza = raza
"""Incluyo el arma como variable propia del objeto y valor inicial vacío"""
self.arma = ""
if raza == "Elfo":
self.vida = 80
self.velocidad = 10
self.coste = 200
elif raza == "Humano":
self.vida = 100
self.velocidad = 7
self.coste = 100
elif raza == "Enano":
self.vida = 120
self.velocidad = 3
self.coste = 180
def armar(self, arma):
self.arma = arma
print("Muchas gracias, ahora tengo un",self.arma)
mi_primer_soldado = Soldado("Eldelbar","Elfo")
mi_primer_soldado.arma = "Arco"
primer_soldado = Soldado("Juan","Humano")
primer_soldado.armar("Espada")
segundo_soldado = Soldado("Bran","Humano")
segundo_soldado.armar("Espada")
tercer_soldado = Soldado("Glóin","Enano")
tercer_soldado.armar("Hacha")
|
ori_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP.txt'
save_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP1.txt'
lable = '0'
ori_lines = []
with open(ori_file, 'r')as f:
ori_lines = f.readlines()
with open(save_file, 'w')as f:
for line in ori_lines:
line = line.strip()
new_line = '{} {}\n'.format(line, lable)
f.write(new_line)
|
messages = {
0: [
"You don’t need a mask in terms of the air pollution today. But since we are facing a global pandemic of Covid-19 right now please wear a mask.",
"It is actually a perfect day to go on a hike today but since the cases of Covid-19 is increasing rapidly I would recommend you to stay indoors as much as possible and follow the guidelines of the Ministry of Health and Population. ",
],
1: [
"KN95/N95 masks are recommended for protection against the Covid-19. "
"It is a good day to go outside and hang out with friends according to the air quality in your locality, but with the current scenario of Covid-19 it is your responsibility to avoid going outside. If you have to go due to any emergencies do not forget your mask. "
],
2: [
"The cases of Covid-19 has been increasing everyday so the use of a KN95/N95 mask is recommended. ",
"The air quality in your locality might affect vulnerable and sensitive groups.void going outside amidst this pandemic of global pandemic and please do follow the local guidelines. "],
3: [
"Air quality is poor so people with heart or lung disease, older adults, children, and teenagers should avoid outdoor activities. Consider using a valve mask or N95/KN95 mask for ultimate protection against the pollutants as well as the Covid-19. "
],
4: [
"You should avoid going outside anyways because there is double trouble waiting for you the unhealthy air quality and the risk of acquiring Covid-19. ",
"The air quality is very harmful outside. Try not going outside at any costs. Wear a N95/KN95 mask while going outside for protection against air pollutants and corona virus. "
],
5: [
"Everyone should avoid outdoor exertion because the pollutants are present at harmful levels. You should avoid going outside anyways because of the increasing cases of Covid-19. If you have to go out for an emergency like a medical emergency please wear a N95/KN95 mask. "
]
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ======================================================
#
# File name: test_console_outputs
# Author: [email protected]
# Date created: 30.06.2018 17:36
# Python Version: 3.7
#
# ======================================================
# https://www.computerhope.com/unix/uifconfi.htm
SAMPLE_OUTPUT_LINUX_SYNTAX_1 = """
eth0 Link encap:Ethernet HWaddr 09:00:12:90:e3:e5
inet addr:192.168.1.29 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe70:e3f5/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:54071 errors:1 dropped:0 overruns:0 frame:0
TX packets:48515 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:22009423 (20.9 MiB) TX bytes:25690847 (24.5 MiB)
Interrupt:10 Base address:0xd020
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:83 errors:0 dropped:0 overruns:0 frame:0
TX packets:83 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:7766 (7.5 KiB) TX bytes:7766 (7.5 KiB)
wlan0 Link encap:Ethernet HWaddr 58:a2:c2:93:27:36
inet addr:192.168.1.64 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::6aa3:c4ff:fe93:4746/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:436968 errors:0 dropped:0 overruns:0 frame:0
TX packets:364103 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:115886055 (110.5 MiB) TX bytes:83286188 (79.4 MiB)
"""
# http://www.aboutlinux.info/2006/11/ifconfig-dissected-and-demystified.html
SAMPLE_OUTPUT_LINUX_SYNTAX_2 = """
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:8 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:480 (480.0 b) TX bytes:480 (480.0 b)
p2p1 Link encap:Ethernet HWaddr 00:1C:C0:AE:B5:E6
inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::21c:c0ff:feae:b5e6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:41620 errors:0 dropped:0 overruns:0 frame:0
TX packets:40231 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:21601203 (20.6 MiB) TX bytes:6145876 (5.8 MiB)
Interrupt:21 Base address:0xe000
"""
# http://linux-ip.net/html/tools-ifconfig.html
SAMPLE_OUTPUT_LINUX_SYNTAX_3 = """
eth0 Link encap:Ethernet HWaddr 00:80:C8:F8:4A:51
inet addr:192.168.99.35 Bcast:192.168.99.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:190312 errors:0 dropped:0 overruns:0 frame:0
TX packets:86955 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:30701229 (29.2 Mb) TX bytes:7878951 (7.5 Mb)
Interrupt:9 Base address:0x5000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:306 errors:0 dropped:0 overruns:0 frame:0
TX packets:306 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:29504 (28.8 Kb) TX bytes:29504 (28.8 Kb)
"""
# http://blmrgnn.blogspot.com/2014/01/linux-ifconfig-command-output-explained.html
SAMPLE_OUTPUT_LINUX_SYNTAX_4 = """
eth0 Link encap:Ethernet HWaddr 00:0C:29:40:93:9C
inet addr:192.168.154.102 Bcast:192.168.154.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1771 errors:0 dropped:0 overruns:0 frame:0
TX packets:359 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:138184 (134.9 KiB) TX bytes:49108 (47.9 KiB)
Interrupt:67 Base address:0x2000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:390 errors:0 dropped:0 overruns:0 frame:0
TX packets:390 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:29204 (28.5 KiB) TX bytes:29204 (28.5 KiB)
"""
# https://www.tutorialspoint.com/unix_commands/ifconfig.htm
SAMPLE_OUTPUT_LINUX_SYNTAX_5 = """
eth0 Link encap:Ethernet HWaddr 00:0c:29:9b:49:bc
inet addr:192.168.134.128 Bcast:192.168.134.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe9b:49bc/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:11545 errors:0 dropped:0 overruns:0 frame:0
TX packets:6177 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:923360 (923.3 KB) TX bytes:1712607 (1.7 MB)
eth1 Link encap:Ethernet HWaddr 00:0c:29:8b:89:bc
inet addr: Bcast: Mask:
inet6 addr: fe80::20c:29ff:fe9b:49bc/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:11545 errors:0 dropped:0 overruns:0 frame:0
TX packets:6177 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:923360 (923.3 KB) TX bytes:1712607 (1.7 MB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
virbr0 Link encap:Ethernet HWaddr 3a:bf:4c:fb:90:b6
inet addr:192.168.122.1 Bcast:192.168.122.255 Mask:255.255.255.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
"""
# http://goinbigdata.com/demystifying-ifconfig-and-network-interfaces-in-linux/
SAMPLE_OUTPUT_LINUX_SYNTAX_6 = """
docker0 Link encap:Ethernet HWaddr 02:42:2d:66:fc:f1
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:2dff:fe66:fcf1/64 Scope:Link
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:2 errors:0 dropped:0 overruns:0 frame:0
TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:152 (152.0 B) TX bytes:258 (258.0 B)
eth0 Link encap:Ethernet HWaddr 08:00:27:31:65:b5
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::3db9:eaaa:e0ae:6e09/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1089467 errors:0 dropped:0 overruns:0 frame:0
TX packets:508121 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:903808796 (903.8 MB) TX bytes:31099448 (31.0 MB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:9643 errors:0 dropped:0 overruns:0 frame:0
TX packets:9643 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:719527 (719.5 KB) TX bytes:719527 (719.5 KB)
"""
# https://ubuntuforums.org/showthread.php?t=2309060
SAMPLE_OUTPUT_LINUX_SYNTAX_7 = """
enp11s0 Link encap:Ethernet HWaddr 78:2b:cb:ce:1d:92
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:17
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:902 errors:0 dropped:0 overruns:0 frame:0
TX packets:902 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:120802 (120.8 KB) TX bytes:120802 (120.8 KB)
wlp2s0b1 Link encap:Ethernet HWaddr 68:a3:c4:2f:07:b0
inet addr:192.168.2.11 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::6aa3:c4ff:fe2f:7b0/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3542 errors:0 dropped:0 overruns:0 frame:0
TX packets:2860 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3080782 (3.0 MB) TX bytes:377587 (377.5 KB)
"""
# https://ubuntuforums.org/showthread.php?t=2309060
SAMPLE_OUTPUT_LINUX_SYNTAX_8 = """
eth0 Link encap:Ethernet HWaddr 78:2b:cb:ce:1d:92
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:17
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:382 errors:0 dropped:0 overruns:0 frame:0
TX packets:382 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:84203 (84.2 KB) TX bytes:84203 (84.2 KB)
wlan0 Link encap:Ethernet HWaddr 68:a3:c4:2f:07:b0
inet addr:192.168.2.11 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::6aa3:c4ff:fe2f:7b0/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:242 errors:0 dropped:0 overruns:0 frame:0
TX packets:256 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:253320 (253.3 KB) TX bytes:29623 (29.6 KB)
"""
# https://forums.fedoraforum.org/showthread.php?305492-Understanding-ifconfig-command-s-output
SAMPLE_OUTPUT_OPENBSD_SYNTAX_1 = """
enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 0.0.0.100 netmask 255.255.255.0 broadcast 0.0.0.0
inet6 aaaa::aaaa:aaaa:aaaa:aaaa prefixlen 64 scopeid 0x20<link>
ether aa:aa:aa:aa:aa:aa txqueuelen 1000 (Ethernet)
RX packets 64219 bytes 82340039 (78.5 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 37986 bytes 4117999 (3.9 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 12 bytes 1596 (1.5 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 12 bytes 1596 (1.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 0.0.0.0 netmask 255.255.255.0 broadcast 0.0.0.0
ether 11:11:11:11:11:11 txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
"""
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=820212
SAMPLE_OUTPUT_OPENBSD_SYNTAX_2 = """
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 96.126.108.191 netmask 255.255.255.0 broadcast 96.126.108.255
inet6 2600:3c03::f03c:91ff:fe70:989d prefixlen 64 scopeid 0x0<global>
inet6 fe80::f03c:91ff:fe70:989d prefixlen 64 scopeid 0x20<link>
ether f2:3c:91:70:98:9d txqueuelen 1000 (Ethernet)
RX packets 8861190 bytes 4193527512 (3.9 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8562901 bytes 3997697400 (3.7 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
eth0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.135.145 netmask 255.255.128.0 broadcast 0.0.0.0
ether f2:3c:91:70:98:9d txqueuelen 1000 (Ethernet)
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 2988597 bytes 2376311697 (2.2 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2988597 bytes 2376311697 (2.2 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898060/ifconfig-centos.txt
SAMPLE_OUTPUT_OPENBSD_SYNTAX_3 = """
docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0
ether 02:42:1a:0a:77:e4 txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.71.138 netmask 255.255.255.0 broadcast 192.168.71.255
inet6 fe80::c1cb:715d:bc3e:b8a0 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:3b:58:0e txqueuelen 1000 (Ethernet)
RX packets 62408 bytes 23770378 (22.6 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 25974 bytes 3523483 (3.3 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 37068 bytes 14181021 (13.5 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 37068 bytes 14181021 (13.5 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898061/ifconfig-ubuntu.txt
SAMPLE_OUTPUT_OPENBSD_SYNTAX_4 = """
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.71.131 netmask 255.255.255.0 broadcast 192.168.71.255
inet6 fe80::20c:29ff:fe99:4517 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:99:45:17 txqueuelen 1000 (Ethernet)
RX packets 35444 bytes 38714337 (38.7 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 9940 bytes 995718 (995.7 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 331 bytes 29530 (29.5 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 331 bytes 29530 (29.5 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
"""
# https://www.freebsd.org/doc/en_US.ISO8859-1/articles/linux-users/network.html
SAMPLE_OUTPUT_FREEBSD_SYNTAX_1 = """
em0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=b<RXCSUM,TXCSUM,VLAN_MTU>
inet 10.10.10.100 netmask 0xffffff00 broadcast 10.10.10.255
ether 00:50:56:a7:70:b2
media: Ethernet autoselect (1000baseTX <full-duplex>)
status: active
em1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=b<RXCSUM,TXCSUM,VLAN_MTU>
inet 192.168.10.222 netmask 0xffffff00 broadcast 192.168.10.255
ether 00:50:56:a7:03:2b
media: Ethernet autoselect (1000baseTX <full-duplex>)
status: active
"""
# https://forums.freebsd.org/threads/loopback-ifconfig-output-different-in-jail.49843/
SAMPLE_OUTPUT_FREEBSD_SYNTAX_2 = """
re0: flags=8802<BROADCAST,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=8209b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,WOL_MAGIC,LINKSTATE>
ether b8:97:5a:23:26:32
media: Ethernet autoselect (none)
status: no carrier
re1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=8209b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,WOL_MAGIC,LINKSTATE>
ether 00:14:d1:2b:9c:b5
inet 192.168.0.104 netmask 0xffffffff broadcast 192.168.0.104
media: Ethernet autoselect (1000baseT <full-duplex>)
status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=600003<RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6>
inet 127.0.0.1 netmask 0xff000000
lo1: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=600003<RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6>
inet 127.0.0.1 netmask 0xffffffff
"""
# https://www.freebsd.org/doc/handbook/config-network-setup.html
SAMPLE_OUTPUT_FREEBSD_SYNTAX_3 = """
dc0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=80008<VLAN_MTU,LINKSTATE>
ether 00:a0:cc:da:da:da
inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
dc1: flags=8802<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=80008<VLAN_MTU,LINKSTATE>
ether 00:a0:cc:da:da:db
inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255
media: Ethernet 10baseT/UTP
status: no carrier
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
nd6 options=3<PERFORMNUD,ACCEPT_RTADV>
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898413/ifconfig-osx-10.11.6-2.txt
SAMPLE_OUTPUT_FREEBSD_SYNTAX_4 = """
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 68:a8:6d:12:f5:75
inet6 fe80::6aa8:6dff:fe12:f575%en0 prefixlen 64 scopeid 0x4
inet6 2600:1700:bab0:d40:6aa8:6dff:fe12:f575 prefixlen 64 autoconf
inet6 2600:1700:bab0:d40:c0d1:97f7:a613:3ed3 prefixlen 64 autoconf temporary
inet 192.168.1.81 netmask 0xffffff00 broadcast 192.168.1.255
inet6 2600:1700:bab0:d40::26 prefixlen 64 dynamic
nd6 options=1<PERFORMNUD>
media: autoselect
status: active
en1: flags=963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX> mtu 1500
options=60<TSO4,TSO6>
ether b2:00:19:cb:f5:50
media: autoselect <full-duplex>
status: inactive
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 0a:a8:6d:12:f5:75
media: autoselect
status: inactive
bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether 6a:a8:6d:21:38:00
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en1 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 5 priority 0 path cost 0
nd6 options=1<PERFORMNUD>
media: <unknown type>
status: inactive
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898414/ifconfig-osx-10.11.6.txt
SAMPLE_OUTPUT_FREEBSD_SYNTAX_5 = """
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 60:c5:47:0a:ce:0b
inet6 fe80::62c5:47ff:fe0a:ce0b%en0 prefixlen 64 scopeid 0x4
inet 192.168.1.65 netmask 0xffffff00 broadcast 192.168.1.255
inet6 2600:1700:bab0:d40:62c5:47ff:fe0a:ce0b prefixlen 64 autoconf
inet6 2600:1700:bab0:d40:ad4b:19b2:2ce5:9a1b prefixlen 64 autoconf temporary
inet6 2600:1700:bab0:d40::2b prefixlen 64 dynamic
nd6 options=1<PERFORMNUD>
media: autoselect
status: active
en1: flags=963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX> mtu 1500
options=60<TSO4,TSO6>
ether b2:00:14:06:39:21
media: autoselect <full-duplex>
status: inactive
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 02:c5:47:0a:ce:0b
media: autoselect
status: inactive
bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether 62:c5:47:a0:f7:10
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en1 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 5 priority 0 path cost 0
nd6 options=1<PERFORMNUD>
media: <unknown type>
status: inactive
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898415/ifconfig-osx-10.14.6-2.txt
SAMPLE_OUTPUT_FREEBSD_SYNTAX_6 = """
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP>
inet 127.0.0.1 netmask 0xff000000
inet6 ::1 prefixlen 128
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=201<PERFORMNUD,DAD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
XHC0: flags=0<> mtu 0
XHC1: flags=0<> mtu 0
XHC20: flags=0<> mtu 0
VHC128: flags=0<> mtu 0
en5: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether ac:de:48:00:10:20
inet6 fe80::aede:48ff:fe00:1020%en5 prefixlen 64 scopeid 0x8
nd6 options=201<PERFORMNUD,DAD>
media: autoselect (100baseTX <full-duplex>)
status: active
ap1: flags=8802<BROADCAST,SIMPLEX,MULTICAST> mtu 1500
ether a6:83:e7:2d:63:8e
media: autoselect
status: inactive
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether a4:83:e7:2d:63:8e
inet6 fe80::4dd:cbd7:2743:da63%en0 prefixlen 64 secured scopeid 0xa
inet 192.168.1.221 netmask 0xffffff00 broadcast 192.168.1.255
inet6 2600:1700:bab0:d40:1874:4566:6499:f3d1 prefixlen 64 autoconf secured
inet6 2600:1700:bab0:d40:30d4:c067:a56d:5888 prefixlen 64 deprecated autoconf temporary
inet6 2600:1700:bab0:d40:342e:1ac7:8bdb:6c3d prefixlen 64 deprecated autoconf temporary
inet6 2600:1700:bab0:d40:fdd1:e943:edd4:5187 prefixlen 64 autoconf temporary
inet6 2600:1700:bab0:d40::39 prefixlen 64 dynamic
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 06:83:e7:2d:63:8e
media: autoselect
status: inactive
awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1484
ether 7e:05:c1:24:14:ca
inet6 fe80::7c05:c1ff:fe24:14ca%awdl0 prefixlen 64 scopeid 0xc
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
en1: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether ea:00:fd:08:58:02
media: autoselect <full-duplex>
status: inactive
en2: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether ea:00:fd:08:58:01
media: autoselect <full-duplex>
status: inactive
en3: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether ea:00:fd:08:58:06
media: autoselect <full-duplex>
status: inactive
en4: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether ea:00:fd:08:58:05
media: autoselect <full-duplex>
status: inactive
bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether ea:00:fd:08:58:02
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en1 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 13 priority 0 path cost 0
member: en2 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 14 priority 0 path cost 0
member: en3 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 15 priority 0 path cost 0
member: en4 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 16 priority 0 path cost 0
nd6 options=201<PERFORMNUD,DAD>
media: <unknown type>
status: inactive
utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 2000
inet6 fe80::7b12:adc2:a089:c4d8%utun0 prefixlen 64 scopeid 0x12
nd6 options=201<PERFORMNUD,DAD>
vmnet1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 00:50:56:c0:00:01
inet 192.168.101.1 netmask 0xffffff00 broadcast 192.168.101.255
vmnet8: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 00:50:56:c0:00:08
inet 192.168.71.1 netmask 0xffffff00 broadcast 192.168.71.255
utun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
inet6 fe80::a08a:46aa:a738:2ea7%utun1 prefixlen 64 scopeid 0x15
nd6 options=201<PERFORMNUD,DAD>
"""
# https://github.com/KnightWhoSayNi/ifconfig-parser/files/3898416/ifconfig-osx-10.14.6.txt
SAMPLE_OUTPUT_FREEBSD_SYNTAX_7 = """
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP>
inet 127.0.0.1 netmask 0xff000000
inet6 ::1 prefixlen 128
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=201<PERFORMNUD,DAD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
XHC1: flags=0<> mtu 0
XHC0: flags=0<> mtu 0
XHC20: flags=0<> mtu 0
en5: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether ac:de:48:00:13:23
inet6 fe80::aede:48ff:fe00:1323%en5 prefixlen 64 scopeid 0x7
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether f0:18:98:03:d9:30
inet6 fe80::8b7:1281:7499:b504%en0 prefixlen 64 secured scopeid 0x8
inet 192.168.1.72 netmask 0xffffff00 broadcast 192.168.1.255
inet6 2600:1700:bab0:d40:bb:9ad:34c5:2e9a prefixlen 64 autoconf secured
inet6 2600:1700:bab0:d40:4573:9380:5ecb:ef52 prefixlen 64 autoconf temporary
inet6 2600:1700:bab0:d40::24 prefixlen 64 dynamic
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 02:18:98:03:f8:49
media: autoselect
status: inactive
awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1484
ether 1e:06:52:da:9b:86
inet6 fe80::1c06:52ff:feda:9b86%awdl0 prefixlen 64 scopeid 0xa
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
en1: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 02:00:31:81:83:05
media: autoselect <full-duplex>
status: inactive
en2: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 02:00:31:81:94:10
media: autoselect <full-duplex>
status: inactive
en3: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 02:00:31:81:94:06
media: autoselect <full-duplex>
status: inactive
en4: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 02:00:31:81:94:05
media: autoselect <full-duplex>
status: inactive
bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether 02:00:31:81:94:02
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en1 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 11 priority 0 path cost 0
member: en2 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 12 priority 0 path cost 0
member: en3 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 13 priority 0 path cost 0
member: en4 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 14 priority 0 path cost 0
nd6 options=201<PERFORMNUD,DAD>
media: <unknown type>
status: inactive
utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 2000
inet6 fe80::cec:23d0:8cf7:c88e%utun0 prefixlen 64 scopeid 0x10
nd6 options=201<PERFORMNUD,DAD>
utun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
inet6 fe80::cf42:647e:9077:7bcb%utun1 prefixlen 64 scopeid 0x11
nd6 options=201<PERFORMNUD,DAD>
utun2: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
inet6 fe80::f67f:be47:695a:f5b1%utun2 prefixlen 64 scopeid 0x12
nd6 options=201<PERFORMNUD,DAD>
utun3: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
inet6 fe80::2998:653d:a6da:9ca5%utun3 prefixlen 64 scopeid 0x13
nd6 options=201<PERFORMNUD,DAD>
utun4: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
inet6 fe80::8e0f:4631:2328:5209%utun4 prefixlen 64 scopeid 0x14
nd6 options=201<PERFORMNUD,DAD>
"""
|
"""Defines the `graalvm_native_image_cc_library` macro, which is a helper macro
for declaring a `graalvm_native_image_library` rule and wraping its outputs
in appropriate rules from `@rules_cc`.
"""
load(
"@dwtj_rules_java//experimental/graalvm:rules/graalvm_native_image_library/defs.bzl",
"graalvm_native_image_library",
)
load("@rules_cc//cc:defs.bzl", "cc_import", "cc_library")
_NAME_SUFFIXES = {
"graalvm_native_image_library": "_graalvm_native_image_library",
"library": ".so",
"header": ".h",
"dynamic_header": "_dynamic.h",
"graal_isolate_header_cc_library": "_graal_isolate_header_cc_library",
"graal_isolate_header_cc_library_dynamic": "_graal_isolate_header_cc_library_dynamic",
"cc_import": "_cc_import",
"cc_import_dynamic": "_cc_import_dynamic",
"main_cc_library": "",
"main_cc_library_dynamic": "_dynamic",
}
def _graal_isolate_header_strip_include_prefix():
# TODO(dwtj): Check that this conditional is actually necessary.
pkg = native.package_name()
if pkg == "":
return ""
else:
return "/" + pkg
# TODO(dwtj): In starlark, can we elide re-passing the `name` argument somehow?
# Maybe a closure? Or maybe with a class and a class instance?
def _names(name, key):
return name + _NAME_SUFFIXES[key]
def _main_library(name, main_library_visibility):
# Wrap `graal_isolate.h` and strip the package include prefix. We strip the
# prefix so it can be found with via a `#include <graal_isolate.h>`
# directive. This is useful because the generated header file includes
# such a directive.
# NOTE(dwtj): I expect that this will result in header file conflicts (about
# which Bazel is sure to complain) if two GraalVM native-image libraries
# created with this macro are linked together. However, in that case, a
# user can fall back on using the `graalvm_native_image_library` directly.
# NOTE(dwtj): I believe that because `graal_isolate.h` doesn't use a prefix,
# it will name-clash with other `graal_isolate.h` files generated by other
# instantiations of this macro within this package, causing them to fail.
# similarly for the `graal_isolate_dynamic.h` file.
# TODO(dwtj): Fix this problem to let the user instantiate the macro twice
# within the same bazel package.
cc_library(
name = _names(name, "graal_isolate_header_cc_library"),
hdrs = ["graal_isolate.h"],
strip_include_prefix = _graal_isolate_header_strip_include_prefix(),
)
# Import the shared library along with the generated header. This header
# will be package-relative.
cc_import(
name = _names(name, "cc_import"),
hdrs = [_names(name, "header")],
shared_library = _names(name, "library"),
)
# Declare a `cc_library` which includes both the above library (to get the
# `graal_isolate.h` file) and the above import (to get the `.h` and `.so`
# files).
cc_library(
name = _names(name, "main_cc_library"),
deps = [
_names(name, "graal_isolate_header_cc_library"),
_names(name, "cc_import"),
],
)
def _main_library_dynamic(name, main_library_visibility):
# NOTE(dwtj): See comments in `_main_library()`. This function is
# basically the same except w.r.t. the "dynamic" header file.
cc_library(
name = _names(name, "graal_isolate_header_cc_library_dynamic"),
hdrs = ["graal_isolate_dynamic.h"],
strip_include_prefix = _graal_isolate_header_strip_include_prefix(),
)
cc_import(
name = _names(name, "cc_import_dynamic"),
hdrs = [_names(name, "dynamic_header")],
shared_library = _names(name, "library"),
)
cc_library(
name = _names(name, "main_cc_library_dynamic"),
deps = [
_names(name, "graal_isolate_header_cc_library_dynamic"),
_names(name, "cc_import_dynamic"),
],
visibility = main_library_visibility,
)
def graalvm_native_image_cc_library(
name,
main_class,
deps,
native_image_options = list(),
visibility = ["//visibility:__pkg__"],
):
'''Declares a `graalvm_native_image_library`; wraps it in two `cc_library`s.
This macro creates various files and targets. However, the user should only
need to use two of these targets: the `cc_library` named `<name>` and the
`cc_library` named `<name>_dynamic`.
Args:
name: The name used for the main `cc_library` rule. This is also used as a
prefix for various other intermediate/internal targets and files
declared by this macro.
main_class: Passed to the `graalvm_native_image_library` rule.
deps: Passed to the `graalvm_native_image_library` rule.
native_image_options: Passed to the `graalvm_native_image_library`
rule. This no value is passed for this parameter, then this defaults
to the empty list.
visibility: The visibility applied to the main `cc_library` rules created
by this macro. Other rules will have package default visibility. If no
value is passed for this parameter, then `[//visibility:__pkg__]` is
used.
'''
graalvm_native_image_library(
name = _names(name, "graalvm_native_image_library"),
main_class = main_class,
deps = deps,
native_image_options = native_image_options,
library_output = _names(name, "library"),
header_output = _names(name, "header"),
dynamic_header_output = _names(name, "dynamic_header"),
graal_isolate_header_output = "graal_isolate.h",
graal_isolate_dynamic_header_output = "graal_isolate_dynamic.h",
)
_main_library(name, visibility)
_main_library_dynamic(name, visibility)
|
"""
Scripts to parse and convert LAMMPS log files.
"""
class LogFileReader:
def __init__(self, filename):
"""
Attributes
----------
runs :
List of the run objects
Todo
----
rigid bodies
not implemented ridig body integrator
multiple integrators / thermostat / barostat
not implemented yet (so we can temp different groups)
"""
self.filename = filename
self._run = dict(
n_steps = 0, # number of simulation steps
active_fixes = {}, # dictionary of active fixes
)
# list of WARNINGS
self.WARNINGS = []
# some defaults
self.runs = []
if hasattr(self.filename,'__iter__') and hasattr(self.filename, 'read'):
# parse logfile
self.parse_file(self.filename, fileobj=self.filename)
else:
# parse logfile
self.parse_file(self.filename)
def parse_file(self, filename, fileobj=None):
"""
Parse a lammps logfile
"""
if fileobj is None:
fp = open(filename)
else:
fp = fileobj
for line in fp:
line_strip = line.strip()
if len(line_strip) == 0: continue # empty line
if line_strip[0] == "#": continue # comment line
line_split = line_strip.split()
if line_strip.find("$") == -1:
self.interprete_line(line_strip)
if fileobj is None:
fp.close()
self.compile_infos()
def interprete_line(self, line):
"""
Function to interprete the line
"""
line_split = line.split()
keyword = line_split[0]
# Handle fixes
if keyword == 'units':
self._run['units'] = line_split[1]
elif keyword == 'timestep':
self._run['time_step'] = float(line_split[1])
elif keyword in ['fix', 'unfix']:
self.handle_fix(line_split)
elif keyword == 'minimize':
self.handle_minimize(line_split)
elif keyword == 'run':
self.handle_run(line_split)
elif keyword == 'WARNING:':
self.WARNINGS.append(line)
def handle_fix(self, line_split):
"""
Handle a fix & unfix
"""
keyword = line_split[0]
if keyword == 'fix':
fix_id = line_split[1] # id
fix_grp = line_split[2] # group
fix_type = line_split[3] # type
fix_args = line_split[4:] # args
self._run['active_fixes'][fix_id] = [fix_grp, fix_type, fix_args]
elif keyword == 'unfix':
del self._run['active_fixes'][line_split[1]]
def handle_run(self, line_split):
"""
Add a run
"""
self.compile_infos()
run = dict(
active_fixes={},
)
for key in self._run.keys():
if not key.startswith("_"):
run[key] = self._run[key]
run['n_steps'] = int(line_split[1])
if self._run['n_steps'] is None:
self._run['n_steps'] = 0
self._run['n_steps'] += int(line_split[1])
self.runs.append(run)
def handle_minimize(self, line_split):
"""
Add a minimization
"""
run = dict(
active_fixes={},
)
if 'units' in self._run:
run['units'] = self._run['units']
run['integrator'] = 'minimize'
run['ensemble'] = 'EM'
run['minimize_prop'] = dict(
etol=float(line_split[1]),
ftol=float(line_split[2]),
maxiter=int(line_split[3]),
maxeval=int(line_split[4]),
)
self.runs.append(run)
def compile_infos(self):
"""
Function to compile the infos.
Finds integrator, thermostat, barostat
"""
# Todo: add support for multiple thermostat, barostat
# create dict in advance
# add thermostat_X
# add counter X
# push thermostat at assert statement
integrator = None
thermostat = {}
barostat = {}
options_thermostat_w_value = [
'tchain',
'tloop',
'drag',
]
options_barostat_w_value = [
'pchain',
'ploop',
'drag',
'mtk',
]
# go over all fix IDS
for fixid, (fix_grp, fix_type, fix_args) in self._run['active_fixes'].items():
# check if have set an integrator
if fix_type in ['nve', 'nvt', 'npt', 'nph']:
assert integrator is None, "Multiple Integreators are not implemented"
integrator = fix_type
# check for thermostat
for part in fix_type.split("/"): # get rid of combinations
if part in ['nvt', 'npt', 'temp', 'langevin']:
assert 'type' not in thermostat , "Multiple Thermostats are not implemented"
thermostat['type'] = fix_type
if part in ['nvt', 'npt']:
i = fix_args.index("temp")
thermostat['Tstart'] = fix_args[i + 1]
thermostat['Tstop'] = fix_args[i + 2]
thermostat['Tdamp'] = fix_args[i + 3]
for i, arg in enumerate(fix_args):
if arg in options_thermostat_w_value:
thermostat[arg] = fix_args[i + 1]
else:
thermostat['Tstart'] = fix_args[0]
thermostat['Tstop'] = fix_args[1]
thermostat['Tdamp'] = fix_args[2]
# check for barostat
for part in fix_type.split("/"): # get rid of combinations
if part in ['nph', 'npt', 'press']:
assert 'type' not in barostat, "Multiple Barostats are not implemented"
barostat['type'] = fix_type
for i, arg in enumerate(fix_args):
# default couplings
if arg in ['iso', 'aniso', 'tri']:
barostat['Pcoupling'] = arg
barostat['Pstart'] = fix_args[i + 1]
barostat['Pstop'] = fix_args[i + 2]
barostat['Pdamp'] = fix_args[i + 3]
# if its an individual coupling of dimensions
elif arg in ['x', 'y', 'z', 'xy', 'yz', 'xz']:
if 'Pcoupling' not in barostat:
barostat['Pcoupling'] = []
barostat['Pstart'] = []
barostat['Pstop'] = []
barostat['Pdamp'] = []
barostat['Pcoupling'].append(arg)
barostat['Pstart'].append(fix_args[i + 1])
barostat['Pstop'].append(fix_args[i + 2])
barostat['Pdamp'].append(fix_args[i + 3])
if arg in options_barostat_w_value:
barostat[arg] = fix_args[i + 1]
# update thermostat and barostat
self._run['integrator'] = integrator
if len(thermostat.keys()) != 0:
self._run['thermostat'] = thermostat
if len(barostat.keys()) != 0:
self._run['barostat'] = barostat
if 'thermostat' in self._run and len(self._run['thermostat']) > 0\
and 'barostat' in self._run and len(self._run['barostat']) > 0:
self._run['ensemble'] = 'npt'
elif 'thermostat' in self._run and len(self._run['thermostat']) > 0:
self._run['ensemble'] = 'nvt'
elif 'barostat' in self._run and len(self._run['barostat']) > 0:
self._run['ensemble'] = 'nph'
else:
self._run['ensemble'] = 'nve'
def map_lammps_to_database(keywords):
# type: (dict) -> dict
"""
Takes a dictionary of mdp-parameters
and converts it to the keywords used in the database.
Parameters
----------
keywords : dict
dictionary from LogFileReader
Returns
-------
dict
dictionary of mapped parameters to be feed in the database
"""
master_dict = dict()
rv = dict()
dict_units = {
'metal' : {
'conv_time': 1,
'conv_press': 1,
},
'real': {
'conv_time': 0.001,
'conv_press': 1.01325,
},
'lj': {
'conv_time': 0.005,
'conv_press': 1,
},
'UNKNOWN' : {
'conv_time': 1,
'conv_press': 1,
}
}
# handling units
conv_time = dict_units.get(keywords.get('units', 'lj'), 'UNKNOWN')['conv_time']
conv_press = dict_units.get(keywords.get('units', 'lj'), 'UNKNOWN')['conv_press']
rv['units'] = keywords['units']
# handling timestep
rv['time_step'] = float(keywords.get('time_step', 1))*conv_time
# mapping general stuff
if 'n_steps' in keywords.keys():
rv['n_steps'] = int(keywords['n_steps'])
if 'ensemble' in keywords.keys():
rv['ensemble'] = keywords['ensemble']
master_dict.update(rv)
# mapping barostats
rv = dict()
if 'barostat' in keywords:
barostat = keywords['barostat']
if barostat['type'] in ['npt', 'nph']:
rv['type'] = 'Parrinello-Rahman'
elif barostat['type'] == 'press/berendsen':
rv['type'] = 'Berendsen'
else:
rv['type'] = barostat['type']
# remove type from here
del barostat['type']
mapping = {
'Pstart': ['p_init', lambda x: str(float(x) * conv_press)],
'Pstop': ['p_target', lambda x: str(float(x) * conv_press)],
'Pdamp': ['p_rel', lambda x: str(float(x) * conv_press)],
'Pcoupling': ['p_coupling', None],
'mtk': ['mtk', None],
'modulus': ['p_compressibility', lambda x: str(1. / (float(x) * conv_press))]
}
for name_lammps,(name_db, fun) in mapping.items():
if name_lammps in barostat.keys():
value = barostat[name_lammps]
if fun is None:
fun = str
if isinstance(value, (tuple, list)):
value = ",".join([fun(v) for v in value])
else:
value = fun(value)
# add the value to the dict
rv[name_db] = value
# remove the entry
del barostat[name_lammps]
# add the rest unconverted
for key, value in barostat.items():
rv[key] = value
master_dict['barostat'] = rv
# mapping barostats
rv = dict()
if 'thermostat' in keywords:
thermostat = keywords['thermostat']
if thermostat['type'] in ['nvt', 'npt']:
rv['type'] = 'Nose-Hoover'
elif thermostat['type'] == 'temp/berendsen':
rv['type'] = 'Berendsen'
elif thermostat['type'] == 'temp/csvr':
rv['type'] = 'v-rescale'
else:
rv['type'] = thermostat['type']
# remove type from here
del thermostat['type']
mapping = {
'Tstart': ['T_init', None],
'Tstop' : ['T_target', None],
'Tdamp': ['T_rel', None],
}
for name_lammps, (name_db, fun) in mapping.items():
if name_lammps in thermostat.keys():
value = thermostat[name_lammps]
# if we have to do conversion
if fun is not None:
value = fun(value)
# add the value to the dict
rv[name_db] = value
# remove the entry
del thermostat[name_lammps]
# add the rest unconverted
for key, value in thermostat.items():
rv[key] = value
master_dict['thermostat'] = rv
return master_dict
def check_combinable_runs(run1, run2):
"""
Checks if two runs are combinable.
pops items that are additive, then checks the rest
Parameters
----------
run1 : LogFileReader.run
run2 : LogFileReader.run
Returns
-------
bool
True if combinable, False if not.
"""
if 'n_steps' in run1 and 'n_steps' in run2:
run1 = dict((k,v) for k,v in run1.items() if k != 'n_steps')
run2 = dict((k, v) for k, v in run2.items() if k != 'n_steps')
elif 'n_steps' in run1 and not 'n_steps' in run2\
or 'n_steps' in run2 and not 'n_steps' in run1:
return False
return run1 == run2
def combine_runs(runs):
"""
Function to combine a list of runs.
Parameters
----------
runs : List[LogFileReader.run]
List of runs.
Returns
-------
List[LogFileReader.run]
List of combined runs if they could be combined.
"""
n_runs = len(runs)
if n_runs < 2:
return runs
s = 1
previous_run, current_run = runs[0], runs[s]
rv = []
for i in range(n_runs):
if check_combinable_runs(previous_run, current_run):
previous_run['n_steps']+= current_run['n_steps']
s+=1
if s == n_runs:
rv.append(previous_run)
break
previous_run, current_run = previous_run, runs[s]
else:
rv.append(previous_run)
s+=1
if s == n_runs:
rv.append(current_run)
break
previous_run, current_run = current_run, runs[s]
return rv
def combine_metagroups(list_meta_groups):
"""
Function to combine multiple metagroups be renaming them.
So they can be added into the database with different names.
A `suffix` is appended going ``1 .. n_metagroups`` with a padding zero if needed.
Parameters
----------
list_meta_groups : List[dict]
Returns
-------
combined_meta_groups : dict
Renamed list of metagroups
"""
combined_meta_groups = dict()
n_runs = len(list_meta_groups)
if n_runs == 0:
return combined_meta_groups
elif n_runs > 1:
suffix_pattern = '{{:0{:d}d}}'.format(len(str(n_runs)))
for i in range(n_runs):
meta_groups = list_meta_groups[i]
# add suffix_pattern at the end of the runs
combined_meta_groups.update(dict((k+suffix_pattern.format(i+1),v) for k,v in meta_groups.items()))
else:
combined_meta_groups.update(list_meta_groups[0])
return combined_meta_groups
def convert_run_to_metagroups(run):
"""
Function to convert runs to metagroups like dictionaries.
Parameters
----------
run : LogFileReader.run
Run dictionary.
Returns
-------
meta_groups : dict
Dictionary of metagroups.
"""
meta_groups = dict(
simulation=dict(engine='LAMMPS'),
thermostat=dict(),
barostat=dict(),
)
simulation_keywords = ['n_steps', 'time_step', 'units']
for keyword in simulation_keywords:
if keyword in run:
meta_groups['simulation'][keyword] = run[keyword]
if 'thermostat' in run:
meta_groups['thermostat'].update(run['thermostat'])
if 'barostat' in run:
meta_groups['barostat'].update(run['barostat'])
for key in list(meta_groups.keys()):
if len(meta_groups[key]) == 0:
meta_groups.pop(key)
return meta_groups
def logfile_to_metagroups(logfiles,
combine=True,
sort=False,
sort_key=None,
):
"""
Function to convert a LAMMPS logfile to metagroups
Parameters
----------
logfiles : str or List[str]
List of paths to logfiles or single path.
combine : bool
Switch if to combine consecutive runs if they are additive. (Default is ``True``.)
sort : bool
Switch if the logfiles should be sorted. (Default is ``True``.)
sort_key : function
Function used to sort the logfiles. Default is sort logfiles of the pattern `log.*.lammps`
Returns
-------
dict_metagroups : dict
Dictionary of metagroups
"""
if not isinstance(logfiles, str):
if sort:
try:
logfiles.sort(key=sort_key)
except:
print("sort_key fails, fall back to normal sorting")
logfiles.sort()
# get the different runs from the logfiles
list_runs = [map_lammps_to_database(run)
for logfile in logfiles
for run in LogFileReader(logfile).runs]
else:
# get the different runs from the logfiles
list_runs = [map_lammps_to_database(run)
for run in LogFileReader(logfiles).runs]
# combine additive runs
if combine:
list_runs = combine_runs(list_runs)
# transform it to metagroups
list_metagroups = [convert_run_to_metagroups(run)
for run in list_runs]
# rename if needed
dict_metagroups = combine_metagroups(list_metagroups)
return dict_metagroups |
class QueryParams:
def _append_query_list(query_list, key, values):
if isinstance(values, list):
for value in values:
QueryParams._append_query_list(query_list, key, value)
elif isinstance(values, bool):
if values == True:
QueryParams._append_query_list(query_list, key, "true")
else:
QueryParams._append_query_list(query_list, key, "false")
else:
query_list.append((key, values))
def process_kwargs(**kwargs):
query_list = []
for key in kwargs.keys():
values = kwargs[key]
QueryParams._append_query_list(query_list, key, values)
return query_list
|
def partition(arr, low, high):
i = low -1
pivot = arr[high]
for j in range(low, high):
if arr[j] < pivot:
i+=1
arr[i], arr[j] =arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quicksort(arr, low,high):
if low < high:
pi = partition(arr, low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
|
# -*- coding: utf-8 -*-
{
'name': "wechat_mall",
'application': True,
'summary': u"""
微信小程序商城管理后台""",
'description': u"""
微信小程序商城管理后台
""",
'author': "Gzp",
'website': "http://wechat.elfgzp.cn",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml
# for the full list
'category': 'Website',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base', 'mail', 'website'],
# always loaded
'data': [
'security/wechat_mall_security.xml',
'security/ir.model.access.csv',
'views/parent_menus.xml',
# logistics views
'views/logistics/wechat_mall_city_views.xml',
'views/logistics/wechat_mall_district_views.xml',
'views/logistics/wechat_mall_logistics_views.xml',
'views/logistics/wechat_mall_province_views.xml',
'views/logistics/wechat_mall_shipper_views.xml',
'views/logistics/menu_logistics.xml',
# order views
'views/order/wechat_mall_order_views.xml',
'views/order/menu_order.xml',
# product views
'views/product/wechat_mall_category_views.xml',
'views/product/wechat_mall_goods_views.xml',
'views/product/wechat_mall_subshop_views.xml',
'views/product/menu_product.xml',
# setting views
'views/setting/wechat_mall_banner_views.xml',
'views/setting/wechat_mall_config_settings_views.xml',
'views/setting/wechat_mall_user_views.xml',
'views/setting/wechat_mall_address_views.xml',
'views/setting/menu_setting.xml',
# other
'views/ir_attachment_view.xml',
'views/wechat_mall_modify_price_wizard_views.xml',
'views/wechat_mall_deliver_wizard_views.xml',
'views/webclient_templates.xml',
'data/order_num_sequence.xml',
'data/payment_num_sequence.xml',
'data/mail_template.xml',
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-07 12:07:46
# @Author : Lewis Tian ([email protected])
# @Link : github.com/taseikyo
# @Version : Python3.7
# https://projecteuler.net/problem=1
def main():
return sum([i for i in range(1, 1000) if (i % 3 == 0) or (i % 5 == 0)])
if __name__ == "__main__":
# 233168
print(main())
|
"""
Tipos de dados
str = string = 'Assim' ou "Assim"
int = inteiro = 1234 ou -12 ou 10 ou 333
float = real/ponto flutuante = -89.10 ou 12.99 ou 0.0
bool = booleano/lógico = True ou False => 10 == 10 => True
type = retorna o tipo do dado
"""
print("Leandro")
print(type("Leandro"))
print(123456)
print(type(123456))
print(23.99)
print(type(23.99))
print(10 == 10)
print(10 == 12)
print('L' == 'L')
print('L' == 'l')
print(bool(''))
print(bool([]))
print(bool(0))
print(bool('1'))
print(bool([1]))
print(bool(1))
print(type(True))
print('10', type('10'), type(int('10')))
print('10.99', type('10.99'), float('10.99'), type(float('10.99'))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.