code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
from App.Proxys import *
data = SimBiController(
name = 'Walking',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 20.0, kd = 5.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 10.0, kd = 0.5, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.7,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.0, 0.0 ) ],
forceY = [
( 0.228828884494, -481.092195147 ),
( 0.620017798112, 825.542462415 ),
( 0.876735522675, -793.791087555 ) ],
forceZ = [ ( 0.496870702609, 26.2427270763 ) ],
torqueX = [ ],
torqueY = [ ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.0, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1.0, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 1.57 ), ( 1.0, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1.0, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.280602, 0.015874 ), ( 0.99, 0.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.0 ), ( 0.508361, 0.05 ), ( 0.986622, 0.0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0048,
0.0048,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5072,
0.9904,
0,
0.66,
1,
929,
3,
3,
0,
0,
597,
10,
53
]
] | [
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Walking',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),\n ControlParams( joint = 'pelvis_torso', kp = 200.0, kd = 30.0, tauMax = 10000.0, scal... |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Running',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'TIME_UP',
stance = 'REVERSE',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [(0,0)],
forceY = [(0,0)],
forceZ = [(0,0)] )
],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [ ( 0.541806, -0.438308 ), ( 0.692308, -0.362199 ), ( 0.859532, -0.160317 ), ( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
)
| [
[
8,
0,
0.014,
0.0233,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0326,
0.0047,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5209,
0.9628,
0,
0.66,
... | [
"'''\nCreated on 2009-09-09\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Running',\n\n startingState = 0,\n \n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),"
] |
from App.Proxys import *
data = SimBiController(
name = 'Running',
controlParamsList = [
ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 200.0, kd = 20.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 10000.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.66, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 30.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'rAnkle', kp = 100.0, kd = 10.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 50.0, kd = 5.0, tauMax = 10000.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'Default state in the walking controller',
nextStateIndex = 0,
transitionOn = 'TIME_UP',
duration = 0.4,
externalForces = [
ExternalForce(
body = 'pelvis',
forceX = [ ( 0.463986797381, 88.822109274 ) ],
forceY = [ ( 0.0, 0.0 ) ],
forceZ = [ ( 0.543945213314, -43.3990089807 ) ],
torqueX = [ ],
torqueY = [ ( 0.532200954731, 7.14704129206 ) ],
torqueZ = [ ] ) ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.488294, 0.113631 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cd = -0.55, cv = -0.3 ),
baseTrajectory = [
( 0.511418617829, -0.473413246148 ),
( 0.692308, -0.362199 ),
( 0.859532, -0.160317 ),
( 0.996656, 0.200194 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1.0, 0.0, 0.0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.0, -0.06 ), ( 0.5, -0.06 ), ( 1.0, -0.06 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.528428, 1.658482 ), ( 0.80602, 1.006429 ), ( 0.983278, 0.354748 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.147157, 0.130628 ),
( 0.394649, 0.318731 ),
( 0.61204, 0.29114 ),
( 0.832776, 0.236208 ),
( 0.989967, 0.576787 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.020067, 0.809573 ),
( 0.197324, -0.510418 ),
( 0.488294, -0.518456 ),
( 0.75, -0.5 ),
( 0.751, -0.15 ),
( 1.0, -0.15 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.354515, -0.354772 ), ( 0.625418, 0.764028 ), ( 0.749164, 1.163781 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.327759, 1.733668 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0301, -0.005792 ), ( 0.41806, -0.277104 ), ( 0.973244, -0.017375 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.006689, -0.025126 ), ( 0.505017, -0.138526 ), ( 0.996656, -0.025126 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ( 0.0, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.110368, 1.884422 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.023411, 0.003989 ), ( 0.471572, 0.243329 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.013378, 0.005066 ), ( 0.448161, 0.321392 ), ( 0.993311, 0.025126 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ( 0.307692, 2.135678 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.307692, 2.573897 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ( 0.364548, 2.98995 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.013378, -2.665055 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
strength = [ ],
components = [
TrajectoryComponent( rotationAxis = ( 0.0, 1.0, 0.0 ), baseTrajectory = [ ( 0.211055276382, -0.226130653266 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ( 0.598662, 0.138959 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.685619, 0.026046 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
baseTrajectory = [ ( 0.010033, 0.076817 ), ( 0.150502, -0.29923 ), ( 0.993311, -0.248525 ) ] ),
TrajectoryComponent( rotationAxis = ( 1.0, 0.0, 0.0 ), baseTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.692308, 0.025126 ), ( 0.856187, -1.532663 ) ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.38796, 0.014868 ), ( 0.826087, -0.431185 ) ] ) ] )
]
)
]
) | [
[
1,
0,
0.0048,
0.0048,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5072,
0.9903,
0,
0.66,
1,
929,
3,
3,
0,
0,
597,
10,
57
]
] | [
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Running',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000.0, kd = 300.0, tauMax = 10000.0, scale = ( 1.0, 0.2, 1.0 ) ),\n ControlParams( joint = 'pelvis_torso', kp = 1000.0, kd = 100.0, tauMax = 10000.0, sc... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 300.0, kd = 100.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.003344, 0.204846 ), ( 0.959866, 0.070153 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.558653, 0.193845 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.3, 0.0 ), ( 0.75, 0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0035,
0.0035,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5053,
0.9929,
0,
0.66,
1,
929,
3,
3,
0,
0,
511,
10,
63
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 300.0, kd = 100.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0... |
'''
Created on 2009-09-09
@author: beaudoin
'''
from App.Proxys import *
data = SimBiController(
name = 'Walking',
startingState = 0,
controlParamsList = [
ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'pelvis_torso', kp = 200, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'rHip', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.66, 1 ) ),
ControlParams( joint = 'torso_neck', kp = 200, kd = 20, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.5, 1, 1 ) ),
ControlParams( joint = 'rShoulder', kp = 20, kd = 5, tauMax = 10000, scale = ( 0.3, 1, 1 ) ),
ControlParams( joint = 'lWrist', kp = 10, kd = 2.5, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rWrist', kp = 10, kd = 2.5, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'rKnee', kp = 300, kd = 30, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),
ControlParams( joint = 'lElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'rElbow', kp = 5, kd = 1, tauMax = 10000, scale = ( 0.2, 1, 1 ) ),
ControlParams( joint = 'lAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 75, kd = 10, tauMax = 10000, scale = ( 1, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) ),
ControlParams( joint = 'rToeJoint', kp = 10, kd = 0.5, tauMax = 10000, scale = ( 1, 1, 1 ) )
],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
transitionOn = 'FOOT_CONTACT',
stance = 'REVERSE',
duration = 0.7,
trajectories = [
Trajectory(
joint = 'root',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.020067, 0.0713 ), ( 0.538462, 0.0713 ), ( 0.966555, 0.0713 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.006689, 0.037422 ), ( 0.491639, -0.030618 ), ( 0.993311, 0.034506 ) ] ) ] ),
Trajectory(
joint = 'SWING_Hip',
strength = [ ( 0, 1 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.010033, -0.015813 ), ( 0.354515, 0.024849 ), ( 0.508361, 0.196533 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = -0.3, cv = -0.3 ),
baseTrajectory = [
( 0.023411, -0.091589 ),
( 0.230769, -0.476365 ),
( 0.521739, -0.218055 ),
( 0.70903, -0.035635 ),
( 0.842809, -0.002125 ),
( 0.986622, -0.000708 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
feedback = LinearBalanceFeedback( axis = ( 1, 0, 0 ), cd = 0.55, cv = 0.3 ),
baseTrajectory = [ ( 0.73913, -0.058739 ) ] ) ] ),
Trajectory(
joint = 'SWING_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.016722, 0.887089 ),
( 0.250836, 0.800963 ),
( 0.428094, 0.659216 ),
( 0.555184, 0.47829 ),
( 0.632107, 0.142159 ),
( 0.77592, -0.027983 ),
( 0.993311, -0.03162 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.046823, 0.39623 ), ( 0.207358, 0.134641 ), ( 0.662207, -0.011162 ), ( 1, 0 ) ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0, 1 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0, 1.5804 ),
( 0.22408, 0.862791 ),
( 0.431438, -0.048689 ),
( 0.688963, -0.71086 ),
( 0.986622, -0.782532 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
feedback = LinearBalanceFeedback( axis = ( 0, 0, 1 ), cd = 0.2, cv = 0.2 ),
baseTrajectory = [ ( 0.016722, -0.203606 ), ( 0.551839, -0.217268 ), ( 1, 0.030252 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [ ( 0.036789, 0.087916 ), ( 0.665552, -0.282452 ), ( 0.989967, -0.224412 ) ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 1.57 ), ( 1, 1.57 ) ] ),
TrajectoryComponent(
rotationAxis = ( 1, 0, 0 ),
baseTrajectory = [
( 0.003344, 0.03002 ),
( 0.180602, 0.002729 ),
( 0.494983, -0.011906 ),
( 0.802676, 0.068758 ),
( 0.986622, 0.078197 ) ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.033445, 0.310933 ), ( 0.521739, 0.419418 ), ( 0.939799, 0.310933 ) ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.003344, -0.036889 ), ( 0.608696, -0.391027 ), ( 1, -0.3 ) ] ) ] ),
Trajectory(
joint = 'pelvis_torso',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0.00034 ), ( 0.505017, -0.100323 ), ( 0.986622, -0.001158 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ), baseTrajectory = [ ( 0.117057, -0.001063 ), ( 0.511706, 0.024454 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0, 0, 1 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0, 0 ), ( 0.280602, 0.015874 ), ( 0.99, 0 ) ] ) ] ),
Trajectory(
joint = 'torso_neck',
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0, 1, 0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.010033, 0 ), ( 0.508361, 0.05 ), ( 0.986622, 0 ) ] ),
TrajectoryComponent( rotationAxis = ( 1, 0, 0 ) ) ] )
]
)
]
)
| [
[
8,
0,
0.0149,
0.0249,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0348,
0.005,
0,
0.66,
0.5,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5224,
0.9602,
0,
0.66,
... | [
"'''\nCreated on 2009-09-09\n\n@author: beaudoin\n'''",
"from App.Proxys import *",
"data = SimBiController( \n\n name = 'Walking',\n\n startingState = 0,\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 3000, kd = 300, tauMax = 10000, scale = ( 1, 0.2, 1 ) ),"
] |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.71,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.5675 ), ( 0.5, 0.7775 ), ( 1.0, 0.5675 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.5, 0.395005787037 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.5, 0.234994212963 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, 0.0352692469298 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.292441001978 ), ( 1.0, -1.90266501957 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.0352692469298 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -1.90266501957 ), ( 0.5, -0.306916761712 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 0.1 ), ( 1.0, 2.36557411429 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.36557411429 ), ( 0.5, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.25605985176 ), ( 0.5, 0.0 ), ( 1.0, 0.25605985176 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.0353280996748 ), ( 0.5, 0.20780840116 ), ( 1.0, -0.0353280996748 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.431240696418 ), ( 0.5, 0.0 ), ( 1.0, -0.431240696418 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0408453732455 ), ( 0.5, 0.407477192474 ), ( 1.0, 0.0408453732455 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.713153999991 ), ( 0.5, 0.0 ), ( 1.0, -0.713153999991 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.430555555556 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.01875 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = WalkController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 500.0, kd = 50.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.140703517588, 0.929648241206 ), ( 0.643216080402, 0.175879396985 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.366834170854, 0.326633165829 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.532663316583, -0.979899497487 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.185929648241, -0.376884422111 ), ( 0.743718592965, 0.778894472362 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5053,
0.9929,
0,
0.66,
1,
929,
3,
3,
0,
0,
293,
10,
63
]
] | [
"from App.Proxys import *",
"data = WalkController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 500.0, kd = 50.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, ... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.200 ), ( 1.0, 0.0700 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0037,
0.0037,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5055,
0.9927,
0,
0.66,
1,
929,
3,
3,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.14602051247 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -3.14 ), ( 0.5, -1.35766712772 ), ( 1.0, -3.14 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.06088629112 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -3.14 ), ( 0.5, -1.97544780802 ), ( 1.0, -3.14 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 1.82220932323 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -1.98237428543 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.506029102038 ), ( 0.5, 0.0 ), ( 1.0, -0.506029102038 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -1.14083040404 ), ( 0.5, 1.06099591765 ), ( 1.0, -1.14083040404 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.496075995362 ), ( 0.5, -1.38777878078e-17 ), ( 1.0, 0.496075995362 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.893777070901 ), ( 0.5, -0.863756831077 ), ( 1.0, 0.893777070901 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.200 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
referenceFrame = 'CHARACTER_RELATIVE',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0037,
0.0037,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5055,
0.9927,
0,
0.66,
1,
929,
3,
3,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.145 ), ( 0.5, 0.62 ), ( 1.0, 1.145 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.612760773201 ), ( 0.5, 0.4 ), ( 1.0, -0.60767396515 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.96228502799 ), ( 0.5, 1.17208006251 ), ( 1.0, -2.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.59144454428 ), ( 0.5, 1.96164897246 ), ( 1.0, 1.60692503929 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.60767396515 ), ( 0.5, 0.4 ), ( 1.0, -0.612760773201 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.0 ), ( 0.5, -1.16088017237 ), ( 1.0, 1.96228502799 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.60692503929 ), ( 0.5, 1.9892369757 ), ( 1.0, 1.59144454428 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.43705921824 ), ( 0.5, 2.04112770189 ), ( 1.0, 2.39675689772 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.39675689772 ), ( 0.5, -2.11858188981 ), ( 1.0, -2.43705921824 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.652537431571 ), ( 0.5, 0.362026574602 ), ( 1.0, 0.652537431571 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.679034314188 ), ( 0.5, 0.242455663357 ), ( 1.0, 0.679034314188 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.443539037361 ), ( 0.5, 0.0 ), ( 1.0, 0.443539037361 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.10625 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.09375 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.72,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.515 ), ( 0.5, 0.2 ), ( 1.0, 0.515 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.221383627068 ), ( 0.5, -0.117036102433 ), ( 1.0, -0.0126885777983 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.0 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0126885777983 ), ( 0.5, 0.117036102433 ), ( 1.0, 0.221383627068 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 0.5, 0.0 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.322732761288 ), ( 0.5, -6.93889390391e-18 ), ( 1.0, 0.322732761288 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.171880490998 ), ( 0.5, 0.0 ), ( 1.0, 0.171880490998 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.107003153544 ), ( 0.5, 0.0 ), ( 1.0, 0.107003153544 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.164284842328 ), ( 0.5, 0.0 ), ( 1.0, 0.164284842328 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.0625 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.04375 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.59,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.38875 ), ( 0.5, 0.91375 ), ( 1.0, 0.38875 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.833665018614 ), ( 0.5, -1.72418658712 ), ( 1.0, -1.25418278399 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.887063295345 ), ( 0.5, 1.12111014855 ), ( 1.0, 0.963554856376 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.25418278399 ), ( 0.5, 1.71966054144 ), ( 1.0, 0.833665018614 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.963554856376 ), ( 0.5, -0.882514042565 ), ( 1.0, -0.887063295345 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.407448864947 ), ( 0.5, 0.351509516585 ), ( 1.0, 1.56625370414 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.56625370414 ), ( 0.5, -0.405009398611 ), ( 1.0, -0.407448864947 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.0389657021399 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.563973711862 ), ( 0.5, 0.591760708973 ), ( 1.0, 0.563973711862 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.231730813046 ), ( 0.5, 0.0 ), ( 1.0, 0.231730813046 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.319155072529 ), ( 0.5, 0.254737775857 ), ( 1.0, 0.319155072529 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.282965672936 ), ( 0.5, 0.262222770702 ), ( 1.0, 0.282965672936 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.075 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.06875 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.62,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.09190687384 ), ( 1.0, 2.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -2.63817581809 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -2.0 ), ( 1.0, 1.09190687384 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 1.0, -2.63817581809 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.00402694999565 ), ( 1.0, 1.42770774061 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.42770774061 ), ( 1.0, -0.00402694999565 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.375744188714 ), ( 1.0, 0.375744188714 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.2 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.64363902446 ), ( 1.0, -0.64363902446 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.16725218285 ), ( 1.0, 1.16725218285 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -1.2 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.464482553944 ), ( 1.0, 0.464482553944 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.56,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.06625 ), ( 0.5, 2.01125 ), ( 1.0, 1.06625 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.5, 0.315 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.5, 0.315 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.41439098346 ), ( 1.0, -1.32878196693 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.476043280795 ), ( 0.5, -0.208794224374 ), ( 1.0, 0.488385048199 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.32878196693 ), ( 0.5, 1.41439098346 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.488385048199 ), ( 0.5, -0.560286000046 ), ( 1.0, 0.476043280795 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.953853151322 ), ( 0.5, 0.257563366311 ), ( 1.0, 0.704587743289 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.704587743289 ), ( 0.5, -0.157456703138 ), ( 1.0, -0.953853151322 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0820512424596 ), ( 0.5, -1.73472347598e-18 ), ( 1.0, -0.0820512424596 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.245782640643 ), ( 0.5, 0.245782640643 ), ( 1.0, 0.245782640643 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0806602092784 ), ( 0.5, 0.0 ), ( 1.0, -0.0806602092784 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.246192476802 ), ( 0.5, 0.246192476802 ), ( 1.0, 0.246192476802 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.0125723271947 ), ( 0.5, 0.0 ), ( 1.0, 0.0125723271947 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.1125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.09375 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.08125 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.78,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.725 ), ( 0.5, 0.725 ), ( 1.0, 0.725 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.96138465184 ), ( 0.5, -0.856486612376 ), ( 1.0, -0.809332292173 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.809332292173 ), ( 0.5, 0.913031361175 ), ( 1.0, -0.96138465184 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, 1.56222904526 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.5, -2.49302076492 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.190389583533 ), ( 0.5, 0.0 ), ( 1.0, 0.190389583533 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.00160097650778 ), ( 0.5, -0.53515635646 ), ( 1.0, -0.00160097650778 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.214836466015 ), ( 0.5, 0.0 ), ( 1.0, 0.214836466015 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0953519033856 ), ( 0.5, -0.741172382825 ), ( 1.0, 0.0953519033856 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.13125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.24375 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.61,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.145 ), ( 0.5, 0.96125 ), ( 1.0, 1.145 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.177270637465 ), ( 1.0, 0.604541274931 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.604541274931 ), ( 0.5, 0.177270637465 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.5, -0.529892784046 ), ( 1.0, -1.15978556809 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.15978556809 ), ( 0.5, 0.529892784046 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.11172679807 ), ( 0.5, -1.45783077227 ), ( 1.0, 1.11172679807 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.825721085275 ), ( 0.5, 0.453946311569 ), ( 1.0, -0.825721085275 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 10.0, kd = 3.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.5, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 15.0, kd = 5.0, tauMax = 200.0, scale = ( 0.3, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 5.0, kd = 1.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, tauMax = 1000.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.003344, 0.204846 ), ( 0.959866, 0.070153 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ( 0.2, 0.2 ), ( 0.4, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.3 ), ( 0.3, 0.3 ), ( 0.4, 0.0 ), ( 1.0, -0.3 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [
( -0.5, 2.0 ),
( -0.1, 1.0 ),
( 0.0, 0.0 ),
( 0.1, 1.0 ),
( 0.5, 2.5 ),
( 1.0, 6.0 ),
( 1.1, 7.0 ),
( 1.5, 3.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ( 0.3, 1.0 ) ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.3, 0.0 ), ( 0.8, 0.0 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.1, 0.5 ), ( 0.0, 0.0 ), ( 0.2, 0.2 ), ( 0.5, 0.2 ), ( 1.0, 2.5 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.57 ), ( 0.752508, -1.473995 ), ( 0.979933, -1.308908 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = 0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, 0.143195 ), ( 0.558653, 0.193845 ), ( 0.813333, 0.16319 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.57 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
feedback = LinearBalanceFeedback( axis = ( 0.0, 0.0, 1.0 ), cv = -0.1, vLimits = ( -0.6, 0.6 ) ),
baseTrajectory = [ ( 0.0, -0.2 ), ( 0.842809, -0.176382 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.006689, -0.1 ), ( 0.568562, -0.2 ), ( 0.989967, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 0.8, 0.15 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.508361, -0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.1 ), ( 0.5, 0.5 ), ( 1.0, 1.0 ) ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.3, 0.0 ), ( 0.75, 0.2 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ( -0.75, -0.5 ), ( 0.0, 0.0 ), ( 0.8, 1.0 ) ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5053,
0.9929,
0,
0.66,
1,
929,
3,
3,
0,
0,
511,
10,
63
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.9875 ), ( 0.5, 0.725 ), ( 1.0, 0.9875 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.507078011239 ), ( 0.5, -2.0 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.5, 0.0 ), ( 1.0, 0.103941218655 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.5, 2.0 ), ( 1.0, -0.507078011239 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.103941218655 ), ( 0.5, -1.01407070469 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 2.8 ), ( 0.5, 1.08110877003 ), ( 1.0, 1.96798697012 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.96798697012 ), ( 0.5, -0.1 ), ( 1.0, -2.8 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.958534192796 ), ( 0.5, 0.797093037412 ), ( 1.0, 0.958534192796 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -1.2 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.792321805397 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.2 ), ( 0.5, 0.0 ), ( 1.0, 1.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, -0.01875 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.2875 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.5, 0.21875 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0036,
0.0036,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5054,
0.9928,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.84,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.2 ), ( 0.25, 0.2 ), ( 0.5, 0.9875 ), ( 0.75, 0.2 ), ( 1.0, 0.2 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 0.25, 0.8071875 ), ( 0.5, 0.315 ), ( 0.75, -0.15326171875 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 0.25, -0.1771875 ), ( 0.5, 0.315 ), ( 0.75, 0.78326171875 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.25, -0.856849024564 ), ( 0.5, -1.5 ), ( 0.75, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.25 ), ( 0.25, -0.140625 ), ( 0.5, 0.0 ), ( 0.75, 0.1337890625 ), ( 1.0, 0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.25, 1.5 ), ( 0.5, 1.5 ), ( 0.75, 0.841261506347 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.25 ), ( 0.25, 0.140625 ), ( 0.5, 0.0 ), ( 0.75, -0.1337890625 ), ( 1.0, -0.25 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.1 ), ( 0.25, 0.1 ), ( 0.5, 0.1 ), ( 0.75, 0.1 ), ( 1.0, 0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -0.1 ), ( 0.25, -0.1 ), ( 0.5, -0.1 ), ( 0.75, -0.1 ), ( 1.0, -0.1 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.338245685756 ), ( 0.5, 0.0 ), ( 0.75, 0.392858393573 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.562673316863 ),
( 0.25, -0.0266145330645 ),
( 0.5, -0.387208283918 ),
( 0.75, 0.00346308709372 ),
( 1.0, 0.562673316863 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.339825553389 ), ( 0.5, 0.0 ), ( 0.75, 0.356935318054 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.61823324355 ),
( 0.25, -0.0516524962421 ),
( 0.5, -0.462717152977 ),
( 0.75, -0.0178491409028 ),
( 1.0, 0.61823324355 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0035,
0.0035,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5052,
0.9931,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.6,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.59625 ), ( 0.25, 0.12625 ), ( 0.5, 1.6684375 ), ( 0.75, 0.87875 ), ( 1.0, 1.59625 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.34490238197 ),
( 0.25, -1.37382525821 ),
( 0.5, -1.39238772339 ),
( 0.75, -1.3957393067 ),
( 1.0, -1.30297512805 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -1.20181038542 ),
( 0.25, -0.160088376855 ),
( 0.5, 0.376943118099 ),
( 0.75, 0.847681649056 ),
( 1.0, 1.35905994564 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 1.30297512805 ),
( 0.25, 1.3872971337 ),
( 0.5, 1.39369185442 ),
( 0.75, 1.38458588639 ),
( 1.0, 1.34490238197 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.35905994564 ),
( 0.25, 0.199536413777 ),
( 0.5, -0.28034056213 ),
( 0.75, -0.680447461984 ),
( 1.0, -1.20181038542 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.33527695073 ), ( 0.25, 0.1 ), ( 0.5, 1.37279519058 ), ( 0.75, 2.8 ), ( 1.0, 2.8 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -2.8 ),
( 0.25, -0.1 ),
( 0.5, -0.286758983578 ),
( 0.75, -0.869268965331 ),
( 1.0, -1.33527695073 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.210319987649 ),
( 0.25, 0.0 ),
( 0.5, 0.0525799969121 ),
( 0.75, 0.140213325099 ),
( 1.0, 0.210319987649 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.08125 ), ( 0.5, 0.0609375 ), ( 0.75, 0.0270833333333 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.175 ), ( 0.5, 0.13125 ), ( 0.75, 0.0583333333333 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0032,
0.0032,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5049,
0.9935,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.77,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.7775 ), ( 0.25, 0.80375 ), ( 0.5, 1.01375 ), ( 1.0, 0.7775 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 1.19 ), ( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.56 ), ( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.5 ), ( 0.25, -1.5 ), ( 0.5, -1.5 ), ( 1.0, -1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.936327835916 ),
( 0.25, -0.058116628439 ),
( 0.5, -0.00533624569115 ),
( 1.0, -0.865882528352 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.5 ), ( 0.25, 1.5 ), ( 0.5, 1.5 ), ( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.865882528352 ),
( 0.25, -0.799151333694 ),
( 0.5, -0.641187304081 ),
( 1.0, -0.936327835916 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 1.76437203967 ), ( 0.25, 1.84072933733 ), ( 0.5, 2.38782151456 ), ( 1.0, 1.40210704392 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, -1.40210704392 ), ( 0.25, -2.29167684138 ), ( 0.5, -2.09410431324 ), ( 1.0, -1.76437203967 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.159484126975 ), ( 0.25, -0.158674699251 ), ( 0.5, 0.0 ), ( 1.0, 0.159484126975 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.494230489065 ), ( 0.25, 0.57453066062 ), ( 0.5, 0.5693434543 ), ( 1.0, -0.494230489065 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, -0.167319769534 ), ( 0.25, -0.0971231314315 ), ( 0.5, 0.0 ), ( 1.0, 0.167319769534 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, -0.529286239128 ), ( 0.25, 1.11799105329 ), ( 0.5, 1.2 ), ( 1.0, -0.529286239128 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 1.0, -0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.112816611208 ), ( 0.5, 0.200562864369 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.08125 ), ( 0.5, 0.28125 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.04375 ), ( 0.5, 0.175 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0035,
0.0035,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5052,
0.993,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lowerback_torso', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'torso_head', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 0.2, 1.0 ) ),
ControlParams( joint = 'lShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rShoulder', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'rElbow', kp = 50.0, kd = 15.0, tauMax = 200.0, scale = ( 0.2, 1.0, 1.0 ) ),
ControlParams( joint = 'lHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rHip', kp = 300.0, kd = 35.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rKnee', kp = 300.0, kd = 35.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'lAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'rAnkle', kp = 50.0, kd = 15.0, tauMax = 100.0, scale = ( 1.0, 0.2, 0.2 ) ),
ControlParams( joint = 'lToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'rToeJoint', kp = 2.0, kd = 0.2, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ) ],
states = [
SimBiConState(
name = 'State 0',
nextStateIndex = 0,
duration = 0.59,
externalForces = [ ],
trajectories = [
Trajectory(
joint = 'root',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory( joint = 'SWING_Hip', strength = [ ], components = [ ] ),
Trajectory(
joint = 'SWING_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Knee',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.5675 ), ( 0.25, 0.5675 ), ( 0.5, 0.5675 ), ( 0.75, 0.5675 ), ( 1.0, 0.5675 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.19 ),
( 0.25, 0.83453125 ),
( 0.5, 0.340065104167 ),
( 0.75, -0.159971064815 ),
( 1.0, -0.56 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Ankle',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.56 ),
( 0.25, -0.20453125 ),
( 0.5, 0.289934895833 ),
( 0.75, 0.789971064815 ),
( 1.0, 1.19 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.5 ),
( 0.25, -1.37826048129 ),
( 0.5, -1.20891768923 ),
( 0.75, -1.03766729788 ),
( 1.0, -0.900666984803 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.651047012036 ),
( 0.25, -0.311105917294 ),
( 0.5, 0.16176086193 ),
( 0.75, 0.639954353465 ),
( 1.0, 1.02250914669 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Shoulder',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.4 ), ( 0.25, 0.4 ), ( 0.5, 0.4 ), ( 0.75, 0.4 ), ( 1.0, 0.4 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 0.900666984803 ),
( 0.25, 1.02240650351 ),
( 0.5, 1.19174929557 ),
( 0.75, 1.36299968692 ),
( 1.0, 1.5 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 1.02250914669 ),
( 0.25, 0.682568051951 ),
( 0.5, 0.209701272727 ),
( 0.75, -0.268492218808 ),
( 1.0, -0.651047012036 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, 1.47145472144 ),
( 0.25, 1.44865469994 ),
( 0.5, 1.41693928543 ),
( 0.75, 1.38486660562 ),
( 1.0, 1.35920846178 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_Elbow',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'LEFT',
baseTrajectory = [
( 0.0, -1.35920846178 ),
( 0.25, -1.38200848327 ),
( 0.5, -1.41372389778 ),
( 0.75, -1.44579657759 ),
( 1.0, -1.47145472144 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'pelvis_lowerback',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.155403232618 ),
( 0.25, -0.092270669367 ),
( 0.5, -0.00445165510104 ),
( 0.75, 0.0843566158541 ),
( 1.0, 0.155403232618 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, -0.0353280996748 ),
( 0.25, -0.0353280996748 ),
( 0.5, -0.0353280996748 ),
( 0.75, -0.0353280996748 ),
( 1.0, -0.0353280996748 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'lowerback_torso',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.220856401634 ),
( 0.25, -0.13113348847 ),
( 0.5, -0.00632661567182 ),
( 0.75, 0.119886171721 ),
( 1.0, 0.220856401634 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [
( 0.0, 0.0408453732455 ),
( 0.25, 0.0408453732455 ),
( 0.5, 0.0408453732455 ),
( 0.75, 0.0408453732455 ),
( 1.0, 0.0408453732455 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'torso_head',
strength = [ ],
referenceFrame = 'CHARACTER_RELATIVE',
components = [
TrajectoryComponent(
rotationAxis = ( 0.0, 1.0, 0.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 0.0, 0.0, 1.0 ),
reverseOnStance = 'RIGHT',
baseTrajectory = [
( 0.0, -0.133448913926 ),
( 0.25, -0.0792352926433 ),
( 0.5, -0.00382275534683 ),
( 0.75, 0.0724392831378 ),
( 1.0, 0.133448913926 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ),
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'SWING_ToeJoint',
strength = [ ( 0.3, 0.1 ), ( 0.5, 0.1 ), ( 0.6, 1.0 ) ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] ),
Trajectory(
joint = 'STANCE_ToeJoint',
strength = [ ],
components = [
TrajectoryComponent(
rotationAxis = ( 1.0, 0.0, 0.0 ),
baseTrajectory = [ ( 0.0, 0.0 ) ],
dScaledTrajectory = [ ],
vScaledTrajectory = [ ] ) ] )
]
)
],
sagittalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.1375 ), ( 0.5, -0.248046875 ), ( 0.75, 0.0854166666667 ), ( 1.0, 0.0 ) ],
coronalTrajectory = [ ( 0.0, 0.0 ), ( 0.25, 0.0 ), ( 0.5, 0.0 ), ( 0.75, 0.0 ), ( 1.0, 0.0 ) ],
heightTrajectory = [ ( 0.0, 0.0 ), ( 0.25, -0.03125 ), ( 0.5, 0.00078125 ), ( 0.75, 0.177083333333 ), ( 1.0, 0.0 ) ]
) | [
[
1,
0,
0.0029,
0.0029,
0,
0.66,
0,
536,
0,
1,
0,
0,
536,
0,
0
],
[
14,
0,
0.5044,
0.9942,
0,
0.66,
1,
929,
3,
6,
0,
0,
511,
10,
61
]
] | [
"from App.Proxys import *",
"data = IKVMCController( \n\n name = '',\n\n controlParamsList = [ \n ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),\n ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.... |
'''
Created on 2009-08-28
@author: beaudoin
'''
from os import path
meshDir = path.join( path.dirname(__file__), "Meshes" )
blue = ( 0.5, 0.6, 0.8, 1 )
green = ( 0.5, 0.8, 0.6, 1 )
red = ( 0.892, 0.716, 0.602, 1 )
gray = ( 0.5, 0.5, 0.5, 1 )
from App.Proxys import *
data = Character(
name = "BipV3",
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis.obj"), blue) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ CapsuleCDP((-0.05, -0.025, 0), (0.05, -0.025, 0), 0.07) ],
pos = (0, 1.035, 0),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "lowerBack",
meshes = [ (path.join(meshDir, "lowerBack.obj"), green) ],
mass = 7.0,
moi = (0.1, 0.08, 0.15),
cdps = [ CapsuleCDP((0,-0.05,0), (0, 0.015, 0), 0.08) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso.obj"), green) ],
mass = 15.5,
moi = (0.21, 0.14, 0.31),
cdps = [ CapsuleCDP((0, -0.05, 0.03), (0, 0.07, 0.03), 0.12) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head.obj"), red) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ CapsuleCDP((0,0.05,0), (0,0.1,0), 0.09) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), green) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.13,0,0), (0.08,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), red) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.2,0,0), (0.07,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), green) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((0.13,0,0), (-0.08,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), red) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.07,0,0), (0.2,0,0), 0.04) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), blue) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.15, 0), (0, -0.19, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), blue) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.17, 0), (0, -0.22, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), blue) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.15, 0), (0, -0.19, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), blue) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.17, 0), (0, -0.22, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), gray) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.05, -0.04, -0.09), (0.05, 0.005, 0.065)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), gray) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.05, -0.04, -0.09), (0.05, 0.005, 0.065)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), gray) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ BoxCDP((-0.03, 0.015, -0.035), (0.03, -0.017, 0.02)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), gray) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ BoxCDP((-0.03, 0.015, -0.035), (0.03, -0.017, 0.02)) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0005, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_lowerback",
parent = "pelvis",
child = "lowerBack",
posInParent = (0, 0.07, -0.015),
posInChild = (0, -0.09, -0.015),
swingAxis1 = (1, 0, 0),
twistAxis = (0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lowerback_torso",
parent = "lowerBack",
child = "torso",
posInParent = (0, 0.05, -0.015),
posInChild = (0, -0.138, 0.012),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.16, 0.00),
posInChild = (0, -0.08, -0.03),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.16, 0.095, 0.02),
posInChild = (-0.13, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.16, 0.095, 0.02),
posInChild = (0.13, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-100, 100, -1.5, 1.5, -100, 100) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.11, 0, 0),
posInChild = (-0.24, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.11, 0, 0),
posInChild = (0.24, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.08, -0.03, -0.01),
posInChild = (0, 0.17, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.08, -0.03, -0.01),
posInChild = (0, 0.17, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 0, 1),
limits = (-1.3, 1.9, -1, 1, -1, 1) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.23, 0),
posInChild = (0, 0.22, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.23, 0),
posInChild = (0, 0.22, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0.01, -0.24, 0.00),
posInChild = (0.0, 0.02, -0.03),
parentAxis = (0, 0, 1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (-0.01, -0.24, 0.00),
posInChild = (0.0, 0.02, -0.03),
parentAxis = (0, 0, -1),
childAxis = (1, 0, 0),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.055),
posInChild = (0, 0, -0.045),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.055),
posInChild = (0, 0, -0.045),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.1) )
]
)
| [
[
8,
0,
0.0093,
0.0155,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0217,
0.0031,
0,
0.66,
0.125,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.028,
0.0031,
0,
0.66,... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"from os import path",
"meshDir = path.join( path.dirname(__file__), \"Meshes\" )",
"blue = ( 0.5, 0.6, 0.8, 1 )",
"green = ( 0.5, 0.8, 0.6, 1 )",
"red = ( 0.892, 0.716, 0.602, 1 )",
"gray = ( 0.5, 0.5, 0.5, 1 )",
"from App.Proxys import *",
... |
'''
Created on 2009-08-28
@author: beaudoin
'''
import PyUtils
import Core, wx
File = "Jumping"
#File = "Running"
#File = "SideRunning"
#File = "JumpWalk"
#File = "Walking"
#File = "Turning"
#PyUtils.load( "RigidBodies.FlatGround" )
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.Bip" )
character.loadReducedStateFromFile( "Data/Characters/Bip/Controllers/%sState.rs" % File );
controller = PyUtils.load( "Characters.Bip.Controllers.%s" % File, character )
controller.setStance( Core.LEFT_STANCE );
| [
[
8,
0,
0.1304,
0.2174,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3043,
0.0435,
0,
0.66,
0.1111,
806,
0,
1,
0,
0,
806,
0,
0
],
[
1,
0,
0.3478,
0.0435,
0,
0.66... | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n'''",
"import PyUtils",
"import Core, wx",
"File = \"Jumping\"",
"PyUtils.load( \"RigidBodies.FiniteFlatGround\" )",
"PyUtils.loadMany( \"RigidBodies.DodgeBall\", 5 )",
"character = PyUtils.load( \"Characters.Bip\" )",
"character.loadReducedStateFromFi... |
'''
Created on 2009-11-26
@author: beaudoin
'''
import PyUtils
import Core, wx
import Controllers
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.BipV3" )
character.computeMass();
controller = Controllers.DanceController(character)
controller.loadFromFile("../data/controllers/bipV3/fWalk_4.sbc")
#controller.loadFromFile("../data/controllers/bipV3/fWalk_3.sbc")
Core.cvar.SimGlobals_stanceKnee = 0.00
Core.cvar.SimGlobals_rootSagittal = 0.3
Core.cvar.SimGlobals_stepHeight = 0.25
Core.cvar.SimGlobals_duckWalk = 0.2
Core.cvar.SimGlobals_VDelSagittal = 2.0
Core.cvar.SimGlobals_stepTime = 0.2
#Core.cvar.SimGlobals_upperBodyTwist = 0.2
controller.initialSetup()
| [
[
8,
0,
0.0968,
0.1613,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2258,
0.0323,
0,
0.66,
0.0625,
806,
0,
1,
0,
0,
806,
0,
0
],
[
1,
0,
0.2581,
0.0323,
0,
0.66... | [
"'''\nCreated on 2009-11-26\n\n@author: beaudoin\n'''",
"import PyUtils",
"import Core, wx",
"import Controllers",
"PyUtils.load( \"RigidBodies.FiniteFlatGround\" )",
"PyUtils.loadMany( \"RigidBodies.DodgeBall\", 5 )",
"character = PyUtils.load( \"Characters.BipV3\" )",
"character.computeMass();",
"... |
'''
Created on 2009-08-28
@author: beaudoin
This file is just a proxy to indicate which one is the desire framework for typical applications
'''
import BipFramework | [
[
8,
0,
0.4444,
0.7778,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
1,
0.1111,
0,
0.66,
1,
569,
0,
1,
0,
0,
569,
0,
0
]
] | [
"'''\nCreated on 2009-08-28\n\n@author: beaudoin\n\nThis file is just a proxy to indicate which one is the desire framework for typical applications\n'''",
"import BipFramework"
] |
'''
Created on 2009-11-23
@author: beaudoin
'''
import PyUtils
PyUtils.load( "RigidBodies.FiniteFlatGround" ) | [
[
8,
0,
0.3333,
0.5556,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.7778,
0.1111,
0,
0.66,
0.5,
806,
0,
1,
0,
0,
806,
0,
0
],
[
8,
0,
1,
0.1111,
0,
0.66,
1,... | [
"'''\nCreated on 2009-11-23\n\n@author: beaudoin\n'''",
"import PyUtils",
"PyUtils.load( \"RigidBodies.FiniteFlatGround\" )"
] |
'''
Created on 2009-11-26
@author: beaudoin
'''
import PyUtils
import Core, wx
import Controllers
PyUtils.load( "RigidBodies.FiniteFlatGround" )
PyUtils.loadMany( "RigidBodies.DodgeBall", 5 )
character = PyUtils.load( "Characters.BipV3" )
character.loadReducedStateFromFile( "Data/Characters/BipV3/Controllers/WalkingState.rs" );
character.computeMass();
#controller = PyUtils.load( "Characters.BipV3.Controllers.StylizedWalking", character )
controller = PyUtils.load( "Characters.BipV3.Controllers.EditableWalking", character )
controller.setStance( Core.LEFT_STANCE );
app = wx.GetApp()
worldOracle = app.getWorldOracle()
behaviour = Core.TurnController(character, controller, worldOracle)
behaviour.initializeDefaultParameters()
controller.setBehaviour(behaviour)
behaviour.requestHeading(0);
behaviour.conTransitionPlan();
| [
[
8,
0,
0.1111,
0.1852,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2593,
0.037,
0,
0.66,
0.0588,
806,
0,
1,
0,
0,
806,
0,
0
],
[
1,
0,
0.2963,
0.037,
0,
0.66,
... | [
"'''\nCreated on 2009-11-26\n\n@author: beaudoin\n'''",
"import PyUtils",
"import Core, wx",
"import Controllers",
"PyUtils.load( \"RigidBodies.FiniteFlatGround\" )",
"PyUtils.loadMany( \"RigidBodies.DodgeBall\", 5 )",
"character = PyUtils.load( \"Characters.BipV3\" )",
"character.loadReducedStateFrom... |
from App.UtilFuncs import fancify
print fancify(
"""Character(
root = ArticulatedRigidBody(
name = "pelvis",
meshes = [ (path.join(meshDir, "pelvis_2_b.obj"), colourDark),
(path.join(meshDir, "pelvis_2_s.obj"), colourLight) ],
mass = 12.9,
moi = (0.0705, 0.11, 0.13),
cdps = [ SphereCDP((0,-0.075,0), 0.12) ],
pos = (0, 1.035, 0.2),
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
arbs = [
ArticulatedRigidBody(
name = "torso",
meshes = [ (path.join(meshDir, "torso_2_b.obj"), colourDark),
(path.join(meshDir, "torso_2_s_v2.obj"), colourLight) ],
mass = 22.5,
moi = (0.34, 0.21, 0.46),
cdps = [ SphereCDP((0,0,0.01), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "head",
meshes = [ (path.join(meshDir, "head_b.obj"), colourDark),
(path.join(meshDir, "head_s.obj"), colourLight) ],
mass = 5.2,
moi = (0.04, 0.02, 0.042),
cdps = [ SphereCDP((0,0.04,0), 0.11) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperArm",
meshes = [ (path.join(meshDir, "lUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerArm",
meshes = [ (path.join(meshDir, "lLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperArm",
meshes = [ (path.join(meshDir, "rUpperArm.obj"), colourDark) ],
mass = 2.2,
moi = (0.005, 0.02, 0.02),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerArm",
meshes = [ (path.join(meshDir, "rLowerArm.obj"), colourDark) ],
mass = 1.7,
moi = (0.0024, 0.025, 0.025),
cdps = [ CapsuleCDP((-0.15,0,0), (0.15,0,0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lUpperLeg",
meshes = [ (path.join(meshDir, "lUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lLowerLeg",
meshes = [ (path.join(meshDir, "lLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rUpperLeg",
meshes = [ (path.join(meshDir, "rUpperLeg.obj"), colourDark) ],
mass = 6.6,
moi = (0.15, 0.022, 0.15),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.26, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "rLowerLeg",
meshes = [ (path.join(meshDir, "rLowerLeg.obj"), colourDark) ],
mass = 3.2,
moi = (0.055, 0.007, 0.055),
cdps = [ CapsuleCDP((0, 0.12, 0), (0, -0.2, 0), 0.05) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35 ),
ArticulatedRigidBody(
name = "lFoot",
meshes = [ (path.join(meshDir, "lFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rFoot",
meshes = [ (path.join(meshDir, "rFoot.obj"), colourDark) ],
mass = 1.0,
moi = (0.007, 0.008, 0.002),
cdps = [ BoxCDP((-0.025, -0.033, -0.09), (0.025, 0.005, 0.055)) ],
# CDP_Sphere 0.025 -0.025 -0.08 0.01
# CDP_Sphere -0.025 -0.025 -0.08 0.01
# CDP_Sphere 0.02 -0.025 0.045 0.01
# CDP_Sphere -0.02 -0.025 0.045 0.01
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "lToes",
meshes = [ (path.join(meshDir, "lToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) ),
ArticulatedRigidBody(
name = "rToes",
meshes = [ (path.join(meshDir, "rToes.obj"), colourDark) ],
mass = 0.2,
moi = (0.002, 0.002, 0.0005),
cdps = [ SphereCDP((0.0, -0.005, 0.025), 0.01) ],
frictionCoeff = 0.8,
restitutionCoeff = 0.35,
groundCoeffs = (0.0002, 0.2) )
],
joints = [
BallInSocketJoint(
name = "pelvis_torso",
parent = "pelvis",
child = "torso",
posInParent = (0, 0.17, -0.035),
posInChild = (0, -0.23, -0.01),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "torso_head",
parent = "torso",
child = "head",
posInParent = (0, 0.1, -0.00),
posInChild = (0, -0.16, -0.025),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-0.6, 0.6, -0.6, 0.6, -0.6, 0.6) ),
BallInSocketJoint(
name = "lShoulder",
parent = "torso",
child = "lUpperArm",
posInParent = (0.20, 0.07, 0.02),
posInChild = (-0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
BallInSocketJoint(
name = "rShoulder",
parent = "torso",
child = "rUpperArm",
posInParent = (-0.20, 0.07, 0.02),
posInChild = (0.17, 0, 0),
swingAxis1 = (0, 0, 1),
twistAxis = ( 1, 0, 0),
limits = (-1.7, 1.7, -1.5, 1.5, -1.5, 1.5) ),
HingeJoint(
name = "lElbow",
parent = "lUpperArm",
child = "lLowerArm",
posInParent = (0.175, 0, 0.006),
posInChild = (-0.215, 0, 0),
axis = ( 0, 1, 0 ),
limits = (-2.7, 0) ),
HingeJoint(
name = "rElbow",
parent = "rUpperArm",
child = "rLowerArm",
posInParent = (-0.175, 0, 0.006),
posInChild = (0.215, 0, 0),
axis = ( 0, -1, 0 ),
limits = (-2.7, 0) ),
BallInSocketJoint(
name = "lHip",
parent = "pelvis",
child = "lUpperLeg",
posInParent = (0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -0.25, 1) ),
BallInSocketJoint(
name = "rHip",
parent = "pelvis",
child = "rUpperLeg",
posInParent = (-0.1, -0.05, 0.0),
posInChild = (0, 0.21, 0),
swingAxis1 = (1, 0, 0),
twistAxis = ( 0, 1, 0),
limits = (-1.3, 1.9, -1, 1, -1, 0.25) ),
HingeJoint(
name = "lKnee",
parent = "lUpperLeg",
child = "lLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
HingeJoint(
name = "rKnee",
parent = "rUpperLeg",
child = "rLowerLeg",
posInParent = (0, -0.26, 0),
posInChild = (0, 0.21, 0),
axis = ( 1, 0, 0 ),
limits = (0, 2.5) ),
UniversalJoint(
name = "lAnkle",
parent = "lLowerLeg",
child = "lFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, 1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
UniversalJoint(
name = "rAnkle",
parent = "rLowerLeg",
child = "rFoot",
posInParent = (0, -0.25, 0.01),
posInChild = (0.0, 0.02, -0.04),
parentAxis = (1, 0, 0),
childAxis = (0, 0, -1),
limits = (-0.75, 0.75, -0.75, 0.75) ),
HingeJoint(
name = "lToeJoint",
parent = "lFoot",
child = "lToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) ),
HingeJoint(
name = "rToeJoint",
parent = "rFoot",
child = "rToes",
posInParent = (0, -0.02, 0.05),
posInChild = (0, 0, -0.025),
axis = ( 1, 0, 0 ),
limits = (-0.52, 0.02) )
]
)""")
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
725,
0,
1,
0,
0,
725,
0,
0
]
] | [
"from App.UtilFuncs import fancify"
] |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| [
[
1,
0,
0.1111,
0.037,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1481,
0.037,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.6... | [
"import os",
"import subprocess",
"import sys",
"BASEDIR = '../main/src/com/joelapenna/foursquare'",
"TYPESDIR = '../captures/types/v1'",
"captures = sys.argv[1:]",
"if not captures:\n captures = os.listdir(TYPESDIR)",
" captures = os.listdir(TYPESDIR)",
"for f in captures:\n basename = f.split('... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
| [
[
1,
0,
0.1818,
0.0909,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
14,
0,
0.2727,
0.0909,
0,
0.66,
0.1111,
15,
3,
0,
0,
0,
654,
10,
1
],
[
14,
0,
0.3636,
0.0909,
0,
... | [
"import time",
"t = time.time()",
"u = time.gmtime(t)",
"s = time.strftime('%a, %e %b %Y %T GMT', u)",
"print('Content-Type: text/javascript')",
"print('Cache-Control: no-cache')",
"print('Date: ' + s)",
"print('Expires: ' + s)",
"print('')",
"print('var timeskew = new Date().getTime() - ' + str(t... |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.2647,
0.1176,
0,
0.... | [
"import math",
"import sys",
"def skipdist(idx):\n return idx%int(TOTALPADS/REALPADS)",
" return idx%int(TOTALPADS/REALPADS)",
"def centerdistance(idx):\n local = idx % PADS_PER_SIDE\n return abs(local - PADS_PER_SIDE/2)",
" local = idx % PADS_PER_SIDE",
" return abs(local - PADS_PER_S... |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| [
[
6,
0,
0.7,
0.4,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.8,
0.2,
1,
0.32,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"for i in range(32):\n print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))",
" print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))"
] |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.2647,
0.1176,
0,
0.... | [
"import math",
"import sys",
"def skipdist(idx):\n return idx%int(TOTALPADS/REALPADS)",
" return idx%int(TOTALPADS/REALPADS)",
"def centerdistance(idx):\n local = idx % PADS_PER_SIDE\n return abs(local - PADS_PER_SIDE/2)",
" local = idx % PADS_PER_SIDE",
" return abs(local - PADS_PER_S... |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| [
[
6,
0,
0.7,
0.4,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.8,
0.2,
1,
0.67,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"for i in range(32):\n print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))",
" print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))"
] |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.2647,
0.1176,
0,
0.... | [
"import math",
"import sys",
"def skipdist(idx):\n return idx%int(TOTALPADS/REALPADS)",
" return idx%int(TOTALPADS/REALPADS)",
"def centerdistance(idx):\n local = idx % PADS_PER_SIDE\n return abs(local - PADS_PER_SIDE/2)",
" local = idx % PADS_PER_SIDE",
" return abs(local - PADS_PER_S... |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| [
[
6,
0,
0.7,
0.4,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.8,
0.2,
1,
0.37,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"for i in range(32):\n print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))",
" print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))"
] |
#!/usr/bin/env python
import math
import sys
try:
verilogfilename = sys.argv[1]
verilog = open(verilogfilename,'r')
PADS_PER_SIDE=int(sys.argv[2])
except:
print >> sys.stderr, "USAGE: %s mapped/design.v pads_per_side"%sys.argv[0]
sys.exit(2)
TOTALPADS=4*PADS_PER_SIDE
# Gather up all the pads to allocate
padtypes={}
names=[]
types = ['PADVDD','PADGND','PADOUT','PADINC','PADINOUT']
for l in verilog:
l = l.strip()
l = l.split(' ',2)
prefix=l[0]
if prefix in types:
typ,name,junk = l
if name in padtypes:
print >> stderr, 'Duplicate pad %s'%name
sys.exit(1)
names.append(name)
padtypes[name] = prefix
REALPADS=len(names)
# Build a map of padpoints
orients = ['N','S','E','W']
padorients=[]
for o in orients:
padorients += [o]*PADS_PER_SIDE
padspots=TOTALPADS*[None]
# Start assigning to pads
assignments={}
# Generate an ordering to try to equally space the pins around the edge
def skipdist(idx):
return idx%int(TOTALPADS/REALPADS)
skipbest = sorted(range(TOTALPADS),key=skipdist)
# Chop down to the number of actual pads so that we don't assign to any others
placeablepads = skipbest[:REALPADS]
# Start allocating VDD and GND by biasing towards the center
def centerdistance(idx):
local = idx % PADS_PER_SIDE
return abs(local - PADS_PER_SIDE/2)
# Locate all VDD and GND pins
pwrpins = [name for name,prefix in padtypes.iteritems() if prefix in ['PADVDD','PADGND']]
# Best spots, in order
centerbest = sorted(placeablepads,key=centerdistance)
for n in pwrpins:
# Find the best unoccupied spot
for i in centerbest:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> stderr, 'Failed to assign pad %s of type %s'%(n,padtypes[n])
# OK, now just start assigning pads to spots
# O(n^2) FTW!
err=False
for n in names:
# Don't try assigning if it's already assigned!
if n in assignments:
continue
for i in placeablepads:
if padspots[i] is None:
# Unoccupied? Assign it to this pad
padspots[i] = n
assignments[n] = i
break
if n not in assignments:
print >> sys.stderr, 'ERROR: Failed to assign pad %s of type %s. No pads available.'%(n,padtypes[n])
err = True
if err:
print >> sys.stderr
print >> sys.stderr, "Not all pads could be assigned."
print >> sys.stderr, "You probably didn't specify enough pads per side."
mpps = int(math.ceil(float(len(padtypes))/4))
print >> sys.stderr, "You should probably try at least %d pads per side."%mpps
sys.exit(3)
print """
# encounter.io file, autogenerated by scripts/pads
Version: 2
Orient: R0
Pad: c01 NW PADFC
Orient: R270
Pad: c02 NE PADFC
Orient: R180
Pad: c03 SE PADFC
Orient: R90
Pad: c04 SW PADFC
"""
# Generator for extra "trash" pads
def trashpadgen():
i=100
while True:
name='X%d'%i
while name in names:
i += 1
name='X%d'%i
names.append(name)
yield name
trashpads = trashpadgen()
# Print out in order of pads
for i in range(len(padspots)):
name = padspots[i]
orientation = padorients[i]
if name is None:
name = trashpads.next()
typ = 'PADNC'
else:
typ = ''
print 'Pad: %4s %s %s'%(name,orientation,typ)
if ((i+1)%PADS_PER_SIDE) == 0:
print
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.2647,
0.1176,
0,
0.... | [
"import math",
"import sys",
"def skipdist(idx):\n return idx%int(TOTALPADS/REALPADS)",
" return idx%int(TOTALPADS/REALPADS)",
"def centerdistance(idx):\n local = idx % PADS_PER_SIDE\n return abs(local - PADS_PER_SIDE/2)",
" local = idx % PADS_PER_SIDE",
" return abs(local - PADS_PER_S... |
#!/usr/bin/env python
for i in range(32):
print "PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );"%(i+3,i,i,i)
| [
[
6,
0,
0.7,
0.4,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.8,
0.2,
1,
0.23,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"for i in range(32):\n print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))",
" print(\"PADINOUT U%d ( .DO(nBUSOUT[%d]), .DI(nBUSOUT[%d]), .OEN(OE), .YPAD(BUSOUT[%d]) );\"%(i+3,i,i,i))"
] |
import pbkdf2
def hx(s):
return s.encode('hex').upper()
vectors=pbkdf2.PBKDF2_tests
for i in range(len(vectors)):
args, res = vectors[i]
print
print '******************************************************************'
print 'UNIT %d'%i
wu = list(pbkdf2.workunits(*args))
if len(wu) != 1:
print 'Skipping unit %d due to multiple work units'%i
continue
KO,U1,c = wu[0]
c = pbkdf2.i2bytes(c)
print 'KO =',hx(KO)
print 'U1 =',hx(U1)
print ' c =',hx(c)
wub = KO+U1+c
print 'Complete work unit:'
open('work%02d'%i,'wb').write(wub)
print hx(wub)
result = pbkdf2.PBKDF2(*args)
print 'Expected result:'
assert(result == res.decode('hex'))
print hx(result)
out = 'vector%02d.asm'%i
print 'Generating ASM file:',out
out = open(out,'w')
words = [hx(wub[i:i+4]) for i in range(0,len(wub),4)]
words.reverse()
out.write('org 0x0000\n')
for w in words:
out.write("cfw 0x%s\n" % w)
out.write('\n')
out.write('org 0x0160\n')
for i in range(7):
out.write('cfw 0x00000000\n')
out.write('\n')
out.write('org 0x0200\n')
for w in reversed([res[i:i+8] for i in range(0,len(res),8)]):
out.write('cfw 0x%s\n'%w)
| [
[
1,
0,
0.0175,
0.0175,
0,
0.66,
0,
872,
0,
1,
0,
0,
872,
0,
0
],
[
2,
0,
0.0614,
0.0351,
0,
0.66,
0.3333,
724,
0,
1,
1,
0,
0,
0,
2
],
[
13,
1,
0.0702,
0.0175,
1,
0... | [
"import pbkdf2",
"def hx(s):\n return s.encode('hex').upper()",
" return s.encode('hex').upper()",
"vectors=pbkdf2.PBKDF2_tests",
"for i in range(len(vectors)):\n args, res = vectors[i]\n\n print('UNIT %d'%i)\n wu = list(pbkdf2.workunits(*args))\n if len(wu) != 1:\n print('Skipping ... |
# Generate a couple of 672-bit test vectors to feed through the HashBlock
from hashlib import sha1
import random
random.seed(12345)
datalen_bits=672
datalen=datalen_bits/8
def mkhdata():
return ''.join([chr(random.randint(0,255)) for x in range(datalen)])
def hx(s):
return s.encode('hex')
def cenc(s):
accum=[]
for c in s:
accum.append('0x%s'%c.encode('hex'))
return '{'+','.join(accum)+'}'
vectors=[mkhdata() for x in range(10)]
print 'sha1test tests[%d] = {'%len(vectors)
for i in range(len(vectors)):
idd = i+1
v = vectors[i]
h = sha1(v).digest()
print '// Test case #%d'%idd
assert(len(v)*8 == 672)
assert(len(h) == 20)
prefix = v[:64]
postfix = v[64:]
assert(len(prefix) == 64)
assert(len(postfix) == 20)
print '{{%s},'%cenc(prefix)
print '{%s},'%cenc(postfix)
print '{%s}},'%cenc(h)
print
print '};'
| [
[
1,
0,
0.075,
0.025,
0,
0.66,
0,
154,
0,
1,
0,
0,
154,
0,
0
],
[
1,
0,
0.1,
0.025,
0,
0.66,
0.1,
715,
0,
1,
0,
0,
715,
0,
0
],
[
8,
0,
0.15,
0.025,
0,
0.66,
0.... | [
"from hashlib import sha1",
"import random",
"random.seed(12345)",
"datalen_bits=672",
"datalen=datalen_bits/8",
"def mkhdata():\n return ''.join([chr(random.randint(0,255)) for x in range(datalen)])",
" return ''.join([chr(random.randint(0,255)) for x in range(datalen)])",
"def hx(s):\n retu... |
'''
Created on 21-03-2011
@author: maciek
'''
def formatString(format, **kwargs):
'''
'''
if not format: return ''
for arg in kwargs.keys():
format = format.replace("{" + arg + "}", "##" + arg + "##")
format = format.replace ("{", "{{")
format = format.replace("}", "}}")
for arg in kwargs.keys():
format = format.replace("##" + arg + "##", "{" + arg + "}")
res = format.format(**kwargs)
res = res.replace("{{", "{")
res = res.replace("}}", "}")
return res | [
[
8,
0,
0.1304,
0.2174,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.6739,
0.6957,
0,
0.66,
1,
798,
0,
2,
1,
0,
0,
0,
9
],
[
8,
1,
0.413,
0.087,
1,
0.11,
0,
... | [
"'''\nCreated on 21-03-2011\n\n@author: maciek\n'''",
"def formatString(format, **kwargs):\n '''\n '''\n if not format: return ''\n \n for arg in kwargs.keys():\n format = format.replace(\"{\" + arg + \"}\", \"##\" + arg + \"##\")\n format = format.replace (\"{\", \"{{\")",
" '''\n ... |
'''
Created on 21-03-2011
@author: maciek
'''
from IndexGenerator import IndexGenerator
from optparse import OptionParser
import os
import tempfile
import shutil
import logging
logging.basicConfig(level = logging.DEBUG)
parser = OptionParser()
parser.add_option('-n', '--app-name', action='store', dest='appName', help='aplication name')
parser.add_option('-u', '--release-urls', action='store', dest='releaseUrls', help='URLs of download files - as coma separated list of entrires')
parser.add_option('-d', '--destination-directory', action='store', dest='otaAppDir', help='Directory where OTA files are created')
parser.add_option('-v', '--version', action='store', dest='version', help='Version of the application')
parser.add_option('-r', '--releases', action='store', dest='releases', help='Release names of the application')
parser.add_option('-R', '--release-notes', action='store', dest='releaseNotes', help='Release notes of the application (in txt2tags format)')
parser.add_option('-D', '--description', action='store', dest='description', help='Description of the application (in txt2tags format)')
(options, args) = parser.parse_args()
if options.appName == None:
parser.error("Please specify the appName.")
elif options.releaseUrls == None:
parser.error("Please specify releaseUrls")
elif options.otaAppDir == None:
parser.error("Please specify destination directory")
elif options.version == None:
parser.error("Please specify version")
elif options.releases == None:
parser.error("Please specify releases")
elif options.releaseNotes == None:
parser.error("Please specify releaseNotes")
elif options.description == None:
parser.error("Please specify description")
appName = options.appName
releaseUrls = options.releaseUrls
otaAppDir = options.otaAppDir
version = options.version
releases = options.releases
releaseNotes = options.releaseNotes
description = options.description
def findIconFilename():
iconPath = "res/drawable-hdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-mdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-ldpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable/icon.png"
logging.debug("IconPath: "+iconPath)
return iconPath
def createOTApackage():
'''
crates all needed files in tmp dir
'''
releaseNotesContent = open(releaseNotes).read()
descriptionContent = open(description).read()
indexGenerator = IndexGenerator(appName, releaseUrls, releaseNotesContent, descriptionContent, version, releases)
index = indexGenerator.get();
tempIndexFile = tempfile.TemporaryFile()
tempIndexFile.write(index)
tempIndexFile.flush()
tempIndexFile.seek(0)
return tempIndexFile
tempIndexFile = createOTApackage()
if not os.path.isdir(otaAppDir):
logging.debug("creating dir: "+otaAppDir)
os.mkdir(otaAppDir)
else:
logging.warning("dir: "+otaAppDir+" exists")
indexFile = open(os.path.join(otaAppDir,"index.html"),'w')
shutil.copyfileobj(tempIndexFile, indexFile)
srcIconFileName = findIconFilename()
disIconFileName = os.path.join(otaAppDir,"Icon.png")
shutil.copy(srcIconFileName,disIconFileName)
| [
[
8,
0,
0.0341,
0.0568,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0682,
0.0114,
0,
0.66,
0.0303,
933,
0,
1,
0,
0,
933,
0,
0
],
[
1,
0,
0.0795,
0.0114,
0,
0.66... | [
"'''\nCreated on 21-03-2011\n\n@author: maciek\n'''",
"from IndexGenerator import IndexGenerator",
"from optparse import OptionParser",
"import os",
"import tempfile",
"import shutil",
"import logging",
"logging.basicConfig(level = logging.DEBUG)",
"parser = OptionParser()",
"parser.add_option('-n... |
'''
Created on 21-03-2011
@author: maciek
'''
from formater import formatString
import os
class IndexGenerator(object):
'''
Generates Index.html for iOS app OTA distribution
'''
basePath = os.path.dirname(__file__)
templateFile = os.path.join(basePath,"templates/index.tmpl")
releaseUrls = ""
appName = ""
changeLog = ""
description = ""
version = ""
release = ""
def __init__(self,appName, releaseUrls, changeLog, description, version, releases):
'''
Constructor
'''
self.appName = appName
self.releaseUrls = releaseUrls
self.changeLog = changeLog
self.description = description
self.version = version
self.releases = releases
def get(self):
'''
returns index.html source code from template file
'''
urlList = self.releaseUrls.split(",")
releaseList = self.releases.split(",")
generatedHtml=""
count=0;
for release in releaseList:
generatedHtml += " <li>\n"
generatedHtml += " <h3><a href=\"javascript:load('" + urlList[count] + "')\">" + release + "</a></h3>\n"
generatedHtml += " </li>\n"
count += 1
template = open(self.templateFile).read()
index = formatString(template, downloads=generatedHtml,
changeLog=self.changeLog,
appName=self.appName,
description=self.description,
version = self.version);
return index | [
[
8,
0,
0.0526,
0.0877,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1053,
0.0175,
0,
0.66,
0.3333,
11,
0,
1,
0,
0,
11,
0,
0
],
[
1,
0,
0.1228,
0.0175,
0,
0.66,
... | [
"'''\nCreated on 21-03-2011\n\n@author: maciek\n'''",
"from formater import formatString",
"import os",
"class IndexGenerator(object):\n '''\n Generates Index.html for iOS app OTA distribution\n '''\n basePath = os.path.dirname(__file__)\n templateFile = os.path.join(basePath,\"templates/index.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.0'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 1.0
'''
try:
import json
except ImportError:
import simplejson as json
import time
import hmac
import uuid
import base64
import urllib
import urllib2
import hashlib
import logging
_OAUTH_SIGN_METHOD = 'HMAC-SHA1'
_OAUTH_VERSION = '1.0'
class OAuthToken(object):
def __init__(self, oauth_token, oauth_token_secret, oauth_verifier=None, **kw):
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self.oauth_verifier = oauth_verifier
for k, v in kw.iteritems():
setattr(self, k, v)
def __str__(self):
attrs = [s for s in dir(self) if not s.startswith('__')]
kvs = ['%s = %s' % (k, getattr(self, k)) for k in attrs]
return ', '.join(kvs)
__repr__ = __str__
class APIClient(object):
def __init__(self, app_key, app_secret, token=None, callback=None, domain='api.t.sina.com.cn'):
self.app_key = str(app_key)
self.app_secret = str(app_secret)
if token:
if isinstance(token, OAuthToken):
if token.oauth_token:
self.oauth_token = token.oauth_token
if token.oauth_token_secret:
self.oauth_token_secret = token.oauth_token_secret
if token.oauth_verifier:
self.oauth_verifier = token.oauth_verifier
else:
raise TypeError('token parameter must be instance of OAuthToken.')
self.callback = callback
self.api_url = 'http://%s' % domain
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
def _oauth_request(self, method, url, **kw):
params = dict( \
oauth_consumer_key=self.app_key, \
oauth_nonce=_generate_nonce(), \
oauth_signature_method=_OAUTH_SIGN_METHOD, \
oauth_timestamp=str(int(time.time())), \
oauth_version=_OAUTH_VERSION, \
oauth_token=self.oauth_token)
params.update(kw)
m = 'GET' if method==_HTTP_GET else 'POST'
bs = _generate_base_string(m, url, **params)
key = '%s&%s' % (self.app_secret, self.oauth_token_secret)
oauth_signature = _generate_signature(key, bs)
print 'params:', params
print 'base string:', bs
print 'key:', key, 'sign:', oauth_signature
print 'url:', url
r = _http_call(url, method, self.__build_oauth_header(params, oauth_signature=oauth_signature), **kw)
return r
def get_request_token(self):
'''
Step 1: request oauth token.
Returns:
OAuthToken object contains oauth_token and oauth_token_secret
'''
params = dict(oauth_callback=self.callback, \
oauth_consumer_key=self.app_key, \
oauth_nonce=_generate_nonce(), \
oauth_signature_method=_OAUTH_SIGN_METHOD, \
oauth_timestamp=str(int(time.time())), \
oauth_version=_OAUTH_VERSION)
url = '%s/oauth/request_token' % self.api_url
bs = _generate_base_string('GET', url, **params)
params['oauth_signature'] = base64.b64encode(hmac.new('%s&' % self.app_secret, bs, hashlib.sha1).digest())
r = _http_call(url, _HTTP_GET, return_json=False, **params)
kw = _parse_params(r, False)
return OAuthToken(**kw)
def get_authorize_url(self, oauth_token):
'''
Step 2: get authorize url and redirect to it.
Args:
oauth_token: oauth_token str that returned from request_token:
oauth_token = client.request_token().oauth_token
Returns:
redirect url, e.g. "http://api.t.sina.com.cn/oauth/authorize?oauth_token=ABCD1234XYZ"
'''
return '%s/oauth/authorize?oauth_token=%s' % (self.api_url, oauth_token)
def get_access_token(self):
'''
get access token from request token:
request_token = OAuthToken(oauth_token, oauth_secret, oauth_verifier)
client = APIClient(appkey, appsecret, request_token)
access_token = client.get_access_token()
'''
params = {
'oauth_consumer_key': self.app_key,
'oauth_timestamp': str(int(time.time())),
'oauth_nonce': _generate_nonce(),
'oauth_version': _OAUTH_VERSION,
'oauth_signature_method': _OAUTH_SIGN_METHOD,
'oauth_token': self.oauth_token,
'oauth_verifier': self.oauth_verifier,
}
url = '%s/oauth/access_token' % self.api_url
bs = _generate_base_string('GET', url, **params)
key = '%s&%s' % (self.app_secret, self.oauth_token_secret)
oauth_signature = _generate_signature(key, bs)
authorization = self.__build_oauth_header(params, oauth_signature=oauth_signature)
r = _http_call(url, _HTTP_GET, authorization, return_json=False)
kw = _parse_params(r, False)
return OAuthToken(**kw)
def __build_oauth_header(self, params, **kw):
'''
build oauth header like: Authorization: OAuth oauth_token="xxx", oauth_nonce="123"
Args:
params: parameter dict.
**kw: any additional key-value parameters.
'''
d = dict(**kw)
d.update(params)
L = [r'%s="%s"' % (k, v) for k, v in d.iteritems() if k.startswith('oauth_')]
return 'OAuth %s' % ', '.join(L)
def __getattr__(self, attr):
' a shortcut for client.get.funcall() to client.funcall() '
return getattr(self.get, attr)
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_call(url, method, authorization=None, return_json=True, **kw):
'''
send an http request and return headers and body if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET and params else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
print 'Authorization:', authorization
req.add_header('Authorization', authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
print method, http_url, 'BODY:', http_body
resp = urllib2.urlopen(req)
body = resp.read()
if return_json:
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
return body
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
return self.client._oauth_request(self.method, '%s/%s.json' % (self.client.api_url, attr.replace('__', '/')), **kw)
return wrap
################################################################################
# utility functions
################################################################################
def _parse_params(params_str, unicode_value=True):
'''
parse a query string as JsonObject (also a dict)
Args:
params_str: query string as str.
unicode_value: return unicode value if True, otherwise str value. default true.
Returns:
JsonObject (inherited from dict)
>>> s = _parse_params('a=123&b=X%26Y&c=%E4%B8%AD%E6%96%87')
>>> s.a
u'123'
>>> s.b
u'X&Y'
>>> s.c==u'\u4e2d\u6587'
True
>>> s = _parse_params('a=123&b=X%26Y&c=%E4%B8%AD%E6%96%87', False)
>>> s.a
'123'
>>> s.b
'X&Y'
>>> s.c=='\xe4\xb8\xad\xe6\x96\x87'
True
>>> s.d #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
KeyError:
'''
d = dict()
for s in params_str.split('&'):
n = s.find('=')
if n>0:
key = s[:n]
value = urllib.unquote(s[n+1:])
d[key] = value.decode('utf-8') if unicode_value else value
return JsonObject(**d)
def _encode_params(**kw):
'''
Encode parameters.
'''
if kw:
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, _quote(qv)))
return '&'.join(args)
return ''
def _quote(s):
'''
quote everything including /
>>> _quote(123)
'123'
>>> _quote(u'\u4e2d\u6587')
'%E4%B8%AD%E6%96%87'
>>> _quote('/?abc=def& _+%')
'%2F%3Fabc%3Ddef%26%20_%2B%25'
'''
if isinstance(s, unicode):
s = s.encode('utf-8')
return urllib.quote(str(s), safe='')
def _generate_nonce():
' generate random uuid as oauth_nonce '
return uuid.uuid4().hex
def _generate_signature(key, base_string):
'''
generate url-encoded oauth_signature with HMAC-SHA1
'''
return _quote(base64.b64encode(hmac.new(key, base_string, hashlib.sha1).digest()))
def _generate_base_string(method, url, **params):
'''
generate base string for signature
>>> method = 'GET'
>>> url = 'http://www.sina.com.cn/news'
>>> params = dict(a=1, b='A&B')
>>> _generate_base_string(method, url, **params)
'GET&http%3A%2F%2Fwww.sina.com.cn%2Fnews&a%3D1%26b%3DA%2526B'
'''
plist = [(_quote(k), _quote(v)) for k, v in params.iteritems()]
plist.sort()
return '%s&%s&%s' % (method, _quote(url), _quote('&'.join(['%s=%s' % (k, v) for k, v in plist])))
if __name__=='__main__':
import doctest
doctest.testmod()
| [
[
14,
0,
0.0113,
0.0028,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0142,
0.0028,
0,
0.66,
0.0303,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0227,
0.0085,
0,
0.... | [
"__version__ = '1.0'",
"__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'",
"'''\nPython client SDK for sina weibo API using OAuth 1.0\n'''",
"try:\n import json\nexcept ImportError:\n import simplejson as json",
" import json",
" import simplejson as json",
"import time",
"import hmac",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.04'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
import json
except ImportError:
import simplejson as json
import time
import urllib
import urllib2
import logging
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_params(**kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, urllib.quote(qv)))
return '&'.join(args)
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_get(url, authorization=None, **kw):
logging.info('GET %s' % url)
return _http_call(url, _HTTP_GET, authorization, **kw)
def _http_post(url, authorization=None, **kw):
logging.info('POST %s' % url)
return _http_call(url, _HTTP_POST, authorization, **kw)
def _http_upload(url, authorization=None, **kw):
logging.info('MULTIPART POST %s' % url)
return _http_call(url, _HTTP_UPLOAD, authorization, **kw)
def _http_call(url, method, authorization, **kw):
'''
send an http request and expect to return a json object if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
req.add_header('Authorization', 'OAuth2 %s' % authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
resp = urllib2.urlopen(req)
body = resp.read()
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
if self.client.is_expires():
raise APIError('21327', 'expired_token', attr)
return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw)
return wrap
class APIClient(object):
'''
API client using synchronized invocation.
'''
def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
self.client_id = app_key
self.client_secret = app_secret
self.redirect_uri = redirect_uri
self.response_type = response_type
self.auth_url = 'https://%s/oauth2/' % domain
self.api_url = 'https://%s/%s/' % (domain, version)
self.access_token = None
self.expires = 0.0
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
self.upload = HttpObject(self, _HTTP_UPLOAD)
def set_access_token(self, access_token, expires_in):
self.access_token = str(access_token)
self.expires = float(expires_in)
def get_authorize_url(self, redirect_uri=None, display='default'):
'''
return the authroize url that should be redirect.
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
return '%s%s?%s' % (self.auth_url, 'authorize', \
_encode_params(client_id = self.client_id, \
response_type = 'code', \
display = display, \
redirect_uri = redirect))
def request_access_token(self, code, redirect_uri=None):
'''
return access token as object: {"access_token":"your-access-token","expires_in":12345678}, expires_in is standard unix-epoch-time
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
r = _http_post('%s%s' % (self.auth_url, 'access_token'), \
client_id = self.client_id, \
client_secret = self.client_secret, \
redirect_uri = redirect, \
code = code, grant_type = 'authorization_code')
r.expires_in += int(time.time())
return r
def is_expires(self):
return not self.access_token or time.time() > self.expires
def __getattr__(self, attr):
return getattr(self.get, attr)
| [
[
14,
0,
0.0201,
0.005,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0251,
0.005,
0,
0.66,
0.0435,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0402,
0.0151,
0,
0.66... | [
"__version__ = '1.04'",
"__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'",
"'''\nPython client SDK for sina weibo API using OAuth 2.\n'''",
"try:\n import json\nexcept ImportError:\n import simplejson as json",
" import json",
" import simplejson as json",
"import time",
"import urllib"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.04'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
import json
except ImportError:
import simplejson as json
import time
import urllib
import urllib2
import logging
def _obj_hook(pairs):
'''
convert json object to python object.
'''
o = JsonObject()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
class APIError(StandardError):
'''
raise APIError if got failed json message.
'''
def __init__(self, error_code, error, request):
self.error_code = error_code
self.error = error
self.request = request
StandardError.__init__(self, error)
def __str__(self):
return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)
class JsonObject(dict):
'''
general json object that can bind any fields but also act as a dict.
'''
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
def _encode_params(**kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.iteritems():
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
args.append('%s=%s' % (k, urllib.quote(qv)))
return '&'.join(args)
def _encode_multipart(**kw):
'''
Build a multipart/form-data body with generated random boundary.
'''
boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
for k, v in kw.iteritems():
data.append('--%s' % boundary)
if hasattr(v, 'read'):
# file-like object:
ext = ''
filename = getattr(v, 'name', '')
n = filename.rfind('.')
if n != (-1):
ext = filename[n:].lower()
content = v.read()
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
data.append('Content-Length: %d' % len(content))
data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
data.append(content)
else:
data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
data.append('--%s--\r\n' % boundary)
return '\r\n'.join(data), boundary
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }
def _guess_content_type(ext):
return _CONTENT_TYPES.get(ext, 'application/octet-stream')
_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2
def _http_get(url, authorization=None, **kw):
logging.info('GET %s' % url)
return _http_call(url, _HTTP_GET, authorization, **kw)
def _http_post(url, authorization=None, **kw):
logging.info('POST %s' % url)
return _http_call(url, _HTTP_POST, authorization, **kw)
def _http_upload(url, authorization=None, **kw):
logging.info('MULTIPART POST %s' % url)
return _http_call(url, _HTTP_UPLOAD, authorization, **kw)
def _http_call(url, method, authorization, **kw):
'''
send an http request and expect to return a json object if no error.
'''
params = None
boundary = None
if method==_HTTP_UPLOAD:
params, boundary = _encode_multipart(**kw)
else:
params = _encode_params(**kw)
http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
http_body = None if method==_HTTP_GET else params
req = urllib2.Request(http_url, data=http_body)
if authorization:
req.add_header('Authorization', 'OAuth2 %s' % authorization)
if boundary:
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
resp = urllib2.urlopen(req)
body = resp.read()
r = json.loads(body, object_hook=_obj_hook)
if hasattr(r, 'error_code'):
raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
return r
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__(self, attr):
def wrap(**kw):
if self.client.is_expires():
raise APIError('21327', 'expired_token', attr)
return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw)
return wrap
class APIClient(object):
'''
API client using synchronized invocation.
'''
def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
self.client_id = app_key
self.client_secret = app_secret
self.redirect_uri = redirect_uri
self.response_type = response_type
self.auth_url = 'https://%s/oauth2/' % domain
self.api_url = 'https://%s/%s/' % (domain, version)
self.access_token = None
self.expires = 0.0
self.get = HttpObject(self, _HTTP_GET)
self.post = HttpObject(self, _HTTP_POST)
self.upload = HttpObject(self, _HTTP_UPLOAD)
def set_access_token(self, access_token, expires_in):
self.access_token = str(access_token)
self.expires = float(expires_in)
def get_authorize_url(self, redirect_uri=None, display='default'):
'''
return the authroize url that should be redirect.
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
return '%s%s?%s' % (self.auth_url, 'authorize', \
_encode_params(client_id = self.client_id, \
response_type = 'code', \
display = display, \
redirect_uri = redirect))
def request_access_token(self, code, redirect_uri=None):
'''
return access token as object: {"access_token":"your-access-token","expires_in":12345678}, expires_in is standard unix-epoch-time
'''
redirect = redirect_uri if redirect_uri else self.redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
r = _http_post('%s%s' % (self.auth_url, 'access_token'), \
client_id = self.client_id, \
client_secret = self.client_secret, \
redirect_uri = redirect, \
code = code, grant_type = 'authorization_code')
r.expires_in += int(time.time())
return r
def is_expires(self):
return not self.access_token or time.time() > self.expires
def __getattr__(self, attr):
return getattr(self.get, attr)
| [
[
14,
0,
0.0201,
0.005,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0251,
0.005,
0,
0.66,
0.0435,
777,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.0402,
0.0151,
0,
0.66... | [
"__version__ = '1.04'",
"__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'",
"'''\nPython client SDK for sina weibo API using OAuth 2.\n'''",
"try:\n import json\nexcept ImportError:\n import simplejson as json",
" import json",
" import simplejson as json",
"import time",
"import urllib"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
APP_KEY = 'hidden'
APP_SECRET = 'hidden'
| [
[
14,
0,
0.8,
0.2,
0,
0.66,
0,
912,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
0.2,
0,
0.66,
1,
675,
1,
0,
0,
0,
0,
3,
0
]
] | [
"APP_KEY = 'hidden'",
"APP_SECRET = 'hidden'"
] |
# mako/pygen.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for generating and formatting literal Python code."""
import re, string
from StringIO import StringIO
from mako import exceptions
class PythonPrinter(object):
def __init__(self, stream):
# indentation counter
self.indent = 0
# a stack storing information about why we incremented
# the indentation counter, to help us determine if we
# should decrement it
self.indent_detail = []
# the string of whitespace multiplied by the indent
# counter to produce a line
self.indentstring = " "
# the stream we are writing to
self.stream = stream
# a list of lines that represents a buffered "block" of code,
# which can be later printed relative to an indent level
self.line_buffer = []
self.in_indent_lines = False
self._reset_multi_line_flags()
def write(self, text):
self.stream.write(text)
def write_indented_block(self, block):
"""print a line or lines of python which already contain indentation.
The indentation of the total block of lines will be adjusted to that of
the current indent level."""
self.in_indent_lines = False
for l in re.split(r'\r?\n', block):
self.line_buffer.append(l)
def writelines(self, *lines):
"""print a series of lines of python."""
for line in lines:
self.writeline(line)
def writeline(self, line):
"""print a line of python, indenting it according to the current
indent level.
this also adjusts the indentation counter according to the
content of the line.
"""
if not self.in_indent_lines:
self._flush_adjusted_lines()
self.in_indent_lines = True
decreased_indent = False
if (line is None or
re.match(r"^\s*#",line) or
re.match(r"^\s*$", line)
):
hastext = False
else:
hastext = True
is_comment = line and len(line) and line[0] == '#'
# see if this line should decrease the indentation level
if (not decreased_indent and
not is_comment and
(not hastext or self._is_unindentor(line))
):
if self.indent > 0:
self.indent -=1
# if the indent_detail stack is empty, the user
# probably put extra closures - the resulting
# module wont compile.
if len(self.indent_detail) == 0:
raise exceptions.SyntaxException(
"Too many whitespace closures")
self.indent_detail.pop()
if line is None:
return
# write the line
self.stream.write(self._indent_line(line) + "\n")
# see if this line should increase the indentation level.
# note that a line can both decrase (before printing) and
# then increase (after printing) the indentation level.
if re.search(r":[ \t]*(?:#.*)?$", line):
# increment indentation count, and also
# keep track of what the keyword was that indented us,
# if it is a python compound statement keyword
# where we might have to look for an "unindent" keyword
match = re.match(r"^\s*(if|try|elif|while|for)", line)
if match:
# its a "compound" keyword, so we will check for "unindentors"
indentor = match.group(1)
self.indent +=1
self.indent_detail.append(indentor)
else:
indentor = None
# its not a "compound" keyword. but lets also
# test for valid Python keywords that might be indenting us,
# else assume its a non-indenting line
m2 = re.match(r"^\s*(def|class|else|elif|except|finally)", line)
if m2:
self.indent += 1
self.indent_detail.append(indentor)
def close(self):
"""close this printer, flushing any remaining lines."""
self._flush_adjusted_lines()
def _is_unindentor(self, line):
"""return true if the given line is an 'unindentor',
relative to the last 'indent' event received.
"""
# no indentation detail has been pushed on; return False
if len(self.indent_detail) == 0:
return False
indentor = self.indent_detail[-1]
# the last indent keyword we grabbed is not a
# compound statement keyword; return False
if indentor is None:
return False
# if the current line doesnt have one of the "unindentor" keywords,
# return False
match = re.match(r"^\s*(else|elif|except|finally).*\:", line)
if not match:
return False
# whitespace matches up, we have a compound indentor,
# and this line has an unindentor, this
# is probably good enough
return True
# should we decide that its not good enough, heres
# more stuff to check.
#keyword = match.group(1)
# match the original indent keyword
#for crit in [
# (r'if|elif', r'else|elif'),
# (r'try', r'except|finally|else'),
# (r'while|for', r'else'),
#]:
# if re.match(crit[0], indentor) and re.match(crit[1], keyword):
# return True
#return False
def _indent_line(self, line, stripspace=''):
"""indent the given line according to the current indent level.
stripspace is a string of space that will be truncated from the
start of the line before indenting."""
return re.sub(r"^%s" % stripspace, self.indentstring
* self.indent, line)
def _reset_multi_line_flags(self):
"""reset the flags which would indicate we are in a backslashed
or triple-quoted section."""
self.backslashed, self.triplequoted = False, False
def _in_multi_line(self, line):
"""return true if the given line is part of a multi-line block,
via backslash or triple-quote."""
# we are only looking for explicitly joined lines here, not
# implicit ones (i.e. brackets, braces etc.). this is just to
# guard against the possibility of modifying the space inside of
# a literal multiline string with unfortunately placed
# whitespace
current_state = (self.backslashed or self.triplequoted)
if re.search(r"\\$", line):
self.backslashed = True
else:
self.backslashed = False
triples = len(re.findall(r"\"\"\"|\'\'\'", line))
if triples == 1 or triples % 2 != 0:
self.triplequoted = not self.triplequoted
return current_state
def _flush_adjusted_lines(self):
stripspace = None
self._reset_multi_line_flags()
for entry in self.line_buffer:
if self._in_multi_line(entry):
self.stream.write(entry + "\n")
else:
entry = entry.expandtabs()
if stripspace is None and re.search(r"^[ \t]*[^# \t]", entry):
stripspace = re.match(r"^([ \t]*)", entry).group(1)
self.stream.write(self._indent_line(entry, stripspace) + "\n")
self.line_buffer = []
self._reset_multi_line_flags()
def adjust_whitespace(text):
"""remove the left-whitespace margin of a block of Python code."""
state = [False, False]
(backslashed, triplequoted) = (0, 1)
def in_multi_line(line):
start_state = (state[backslashed] or state[triplequoted])
if re.search(r"\\$", line):
state[backslashed] = True
else:
state[backslashed] = False
def match(reg, t):
m = re.match(reg, t)
if m:
return m, t[len(m.group(0)):]
else:
return None, t
while line:
if state[triplequoted]:
m, line = match(r"%s" % state[triplequoted], line)
if m:
state[triplequoted] = False
else:
m, line = match(r".*?(?=%s|$)" % state[triplequoted], line)
else:
m, line = match(r'#', line)
if m:
return start_state
m, line = match(r"\"\"\"|\'\'\'", line)
if m:
state[triplequoted] = m.group(0)
continue
m, line = match(r".*?(?=\"\"\"|\'\'\'|#|$)", line)
return start_state
def _indent_line(line, stripspace = ''):
return re.sub(r"^%s" % stripspace, '', line)
lines = []
stripspace = None
for line in re.split(r'\r?\n', text):
if in_multi_line(line):
lines.append(line)
else:
line = line.expandtabs()
if stripspace is None and re.search(r"^[ \t]*[^# \t]", line):
stripspace = re.match(r"^([ \t]*)", line).group(1)
lines.append(_indent_line(line, stripspace))
return "\n".join(lines)
| [
[
8,
0,
0.0246,
0.0035,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0316,
0.0035,
0,
0.66,
0.2,
540,
0,
2,
0,
0,
540,
0,
0
],
[
1,
0,
0.0351,
0.0035,
0,
0.66,
... | [
"\"\"\"utilities for generating and formatting literal Python code.\"\"\"",
"import re, string",
"from StringIO import StringIO",
"from mako import exceptions",
"class PythonPrinter(object):\n def __init__(self, stream):\n # indentation counter\n self.indent = 0\n \n # a stack storin... |
# mako/lookup.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import os, stat, posixpath, re
from mako import exceptions, util
from mako.template import Template
try:
import threading
except:
import dummy_threading as threading
class TemplateCollection(object):
"""Represent a collection of :class:`.Template` objects,
identifiable via uri.
A :class:`.TemplateCollection` is linked to the usage of
all template tags that address other templates, such
as ``<%include>``, ``<%namespace>``, and ``<%inherit>``.
The ``file`` attribute of each of those tags refers
to a string URI that is passed to that :class:`.Template`
object's :class:`.TemplateCollection` for resolution.
:class:`.TemplateCollection` is an abstract class,
with the usual default implementation being :class:`.TemplateLookup`.
"""
def has_template(self, uri):
"""Return ``True`` if this :class:`.TemplateLookup` is
capable of returning a :class:`.Template` object for the
given URL.
:param uri: String uri of the template to be resolved.
"""
try:
self.get_template(uri)
return True
except exceptions.TemplateLookupException:
return False
def get_template(self, uri, relativeto=None):
"""Return a :class:`.Template` object corresponding to the given
URL.
The default implementation raises
:class:`.NotImplementedError`. Implementations should
raise :class:`.TemplateLookupException` if the given uri
cannot be resolved.
:param uri: String uri of the template to be resolved.
:param relativeto: if present, the given URI is assumed to
be relative to this uri.
"""
raise NotImplementedError()
def filename_to_uri(self, uri, filename):
"""Convert the given filename to a uri relative to
this TemplateCollection."""
return uri
def adjust_uri(self, uri, filename):
"""Adjust the given uri based on the calling filename.
When this method is called from the runtime, the
'filename' parameter is taken directly to the 'filename'
attribute of the calling template. Therefore a custom
TemplateCollection subclass can place any string
identifier desired in the "filename" parameter of the
Template objects it constructs and have them come back
here.
"""
return uri
class TemplateLookup(TemplateCollection):
"""Represent a collection of templates that locates template source files
from the local filesystem.
The primary argument is the ``directories`` argument, the list of
directories to search::
lookup = TemplateLookup(["/path/to/templates"])
some_template = lookup.get_template("/index.html")
The :class:`.TemplateLookup` can also be given :class:`.Template` objects
programatically using :meth:`.put_string` or :meth:`.put_template`::
lookup = TemplateLookup()
lookup.put_string("base.html", '''
<html><body>${self.next()}</body></html>
''')
lookup.put_string("hello.html", '''
<%include file='base.html'/>
Hello, world !
''')
:param directories: A list of directory names which will be
searched for a particular template URI. The URI is appended
to each directory and the filesystem checked.
:param collection_size: Approximate size of the collection used
to store templates. If left at its default of -1, the size
is unbounded, and a plain Python dictionary is used to
relate URI strings to :class:`.Template` instances.
Otherwise, a least-recently-used cache object is used which
will maintain the size of the collection approximately to
the number given.
:param filesystem_checks: When at its default value of ``True``,
each call to :meth:`TemplateLookup.get_template()` will
compare the filesystem last modified time to the time in
which an existing :class:`.Template` object was created.
This allows the :class:`.TemplateLookup` to regenerate a
new :class:`.Template` whenever the original source has
been updated. Set this to ``False`` for a very minor
performance increase.
:param modulename_callable: A callable which, when present,
is passed the path of the source file as well as the
requested URI, and then returns the full path of the
generated Python module file. This is used to inject
alternate schemes for Pyhton module location. If left at
its default of ``None``, the built in system of generation
based on ``module_directory`` plus ``uri`` is used.
All other keyword parameters available for
:class:`.Template` are mirrored here. When new
:class:`.Template` objects are created, the keywords
established with this :class:`.TemplateLookup` are passed on
to each new :class:`.Template`.
"""
def __init__(self,
directories=None,
module_directory=None,
filesystem_checks=True,
collection_size=-1,
format_exceptions=False,
error_handler=None,
disable_unicode=False,
bytestring_passthrough=False,
output_encoding=None,
encoding_errors='strict',
cache_type=None,
cache_dir=None, cache_url=None,
cache_enabled=True,
modulename_callable=None,
default_filters=None,
buffer_filters=(),
strict_undefined=False,
imports=None,
input_encoding=None,
preprocessor=None):
self.directories = [posixpath.normpath(d) for d in
util.to_list(directories, ())
]
self.module_directory = module_directory
self.modulename_callable = modulename_callable
self.filesystem_checks = filesystem_checks
self.collection_size = collection_size
self.template_args = {
'format_exceptions':format_exceptions,
'error_handler':error_handler,
'disable_unicode':disable_unicode,
'bytestring_passthrough':bytestring_passthrough,
'output_encoding':output_encoding,
'encoding_errors':encoding_errors,
'input_encoding':input_encoding,
'module_directory':module_directory,
'cache_type':cache_type,
'cache_dir':cache_dir or module_directory,
'cache_url':cache_url,
'cache_enabled':cache_enabled,
'default_filters':default_filters,
'buffer_filters':buffer_filters,
'strict_undefined':strict_undefined,
'imports':imports,
'preprocessor':preprocessor}
if collection_size == -1:
self._collection = {}
self._uri_cache = {}
else:
self._collection = util.LRUCache(collection_size)
self._uri_cache = util.LRUCache(collection_size)
self._mutex = threading.Lock()
def get_template(self, uri):
"""Return a :class:`.Template` object corresponding to the given
URL.
Note the "relativeto" argument is not supported here at the moment.
"""
try:
if self.filesystem_checks:
return self._check(uri, self._collection[uri])
else:
return self._collection[uri]
except KeyError:
u = re.sub(r'^\/+', '', uri)
for dir in self.directories:
srcfile = posixpath.normpath(posixpath.join(dir, u))
if os.path.isfile(srcfile):
return self._load(srcfile, uri)
else:
raise exceptions.TopLevelLookupException(
"Cant locate template for uri %r" % uri)
def adjust_uri(self, uri, relativeto):
"""adjust the given uri based on the given relative uri."""
key = (uri, relativeto)
if key in self._uri_cache:
return self._uri_cache[key]
if uri[0] != '/':
if relativeto is not None:
v = self._uri_cache[key] = posixpath.join(posixpath.dirname(relativeto), uri)
else:
v = self._uri_cache[key] = '/' + uri
else:
v = self._uri_cache[key] = uri
return v
def filename_to_uri(self, filename):
"""Convert the given filename to a uri relative to
this TemplateCollection."""
try:
return self._uri_cache[filename]
except KeyError:
value = self._relativeize(filename)
self._uri_cache[filename] = value
return value
def _relativeize(self, filename):
"""Return the portion of a filename that is 'relative'
to the directories in this lookup.
"""
filename = posixpath.normpath(filename)
for dir in self.directories:
if filename[0:len(dir)] == dir:
return filename[len(dir):]
else:
return None
def _load(self, filename, uri):
self._mutex.acquire()
try:
try:
# try returning from collection one
# more time in case concurrent thread already loaded
return self._collection[uri]
except KeyError:
pass
try:
if self.modulename_callable is not None:
module_filename = self.modulename_callable(filename, uri)
else:
module_filename = None
self._collection[uri] = template = Template(
uri=uri,
filename=posixpath.normpath(filename),
lookup=self,
module_filename=module_filename,
**self.template_args)
return template
except:
# if compilation fails etc, ensure
# template is removed from collection,
# re-raise
self._collection.pop(uri, None)
raise
finally:
self._mutex.release()
def _check(self, uri, template):
if template.filename is None:
return template
try:
template_stat = os.stat(template.filename)
if template.module._modified_time < \
template_stat[stat.ST_MTIME]:
self._collection.pop(uri, None)
return self._load(template.filename, uri)
else:
return template
except OSError:
self._collection.pop(uri, None)
raise exceptions.TemplateLookupException(
"Cant locate template for uri %r" % uri)
def put_string(self, uri, text):
"""Place a new :class:`.Template` object into this
:class:`.TemplateLookup`, based on the given string of
text.
"""
self._collection[uri] = Template(
text,
lookup=self,
uri=uri,
**self.template_args)
def put_template(self, uri, template):
"""Place a new :class:`.Template` object into this
:class:`.TemplateLookup`, based on the given
:class:`.Template` object.
"""
self._collection[uri] = template
| [
[
1,
0,
0.0211,
0.003,
0,
0.66,
0,
688,
0,
4,
0,
0,
688,
0,
0
],
[
1,
0,
0.0242,
0.003,
0,
0.66,
0.2,
682,
0,
2,
0,
0,
682,
0,
0
],
[
1,
0,
0.0272,
0.003,
0,
0.66,
... | [
"import os, stat, posixpath, re",
"from mako import exceptions, util",
"from mako.template import Template",
"try:\n import threading\nexcept:\n import dummy_threading as threading",
" import threading",
" import dummy_threading as threading",
"class TemplateCollection(object):\n \"\"\"Re... |
# mako/parsetree.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""defines the parse tree components for Mako templates."""
from mako import exceptions, ast, util, filters
import re
class Node(object):
"""base class for a Node in the parse tree."""
def __init__(self, source, lineno, pos, filename):
self.source = source
self.lineno = lineno
self.pos = pos
self.filename = filename
@property
def exception_kwargs(self):
return {'source':self.source, 'lineno':self.lineno,
'pos':self.pos, 'filename':self.filename}
def get_children(self):
return []
def accept_visitor(self, visitor):
def traverse(node):
for n in node.get_children():
n.accept_visitor(visitor)
method = getattr(visitor, "visit" + self.__class__.__name__, traverse)
method(self)
class TemplateNode(Node):
"""a 'container' node that stores the overall collection of nodes."""
def __init__(self, filename):
super(TemplateNode, self).__init__('', 0, 0, filename)
self.nodes = []
self.page_attributes = {}
def get_children(self):
return self.nodes
def __repr__(self):
return "TemplateNode(%s, %r)" % (
util.sorted_dict_repr(self.page_attributes),
self.nodes)
class ControlLine(Node):
"""defines a control line, a line-oriented python line or end tag.
e.g.::
% if foo:
(markup)
% endif
"""
def __init__(self, keyword, isend, text, **kwargs):
super(ControlLine, self).__init__(**kwargs)
self.text = text
self.keyword = keyword
self.isend = isend
self.is_primary = keyword in ['for','if', 'while', 'try']
if self.isend:
self._declared_identifiers = []
self._undeclared_identifiers = []
else:
code = ast.PythonFragment(text, **self.exception_kwargs)
self._declared_identifiers = code.declared_identifiers
self._undeclared_identifiers = code.undeclared_identifiers
def declared_identifiers(self):
return self._declared_identifiers
def undeclared_identifiers(self):
return self._undeclared_identifiers
def is_ternary(self, keyword):
"""return true if the given keyword is a ternary keyword
for this ControlLine"""
return keyword in {
'if':set(['else', 'elif']),
'try':set(['except', 'finally']),
'for':set(['else'])
}.get(self.keyword, [])
def __repr__(self):
return "ControlLine(%r, %r, %r, %r)" % (
self.keyword,
self.text,
self.isend,
(self.lineno, self.pos)
)
class Text(Node):
"""defines plain text in the template."""
def __init__(self, content, **kwargs):
super(Text, self).__init__(**kwargs)
self.content = content
def __repr__(self):
return "Text(%r, %r)" % (self.content, (self.lineno, self.pos))
class Code(Node):
"""defines a Python code block, either inline or module level.
e.g.::
inline:
<%
x = 12
%>
module level:
<%!
import logger
%>
"""
def __init__(self, text, ismodule, **kwargs):
super(Code, self).__init__(**kwargs)
self.text = text
self.ismodule = ismodule
self.code = ast.PythonCode(text, **self.exception_kwargs)
def declared_identifiers(self):
return self.code.declared_identifiers
def undeclared_identifiers(self):
return self.code.undeclared_identifiers
def __repr__(self):
return "Code(%r, %r, %r)" % (
self.text,
self.ismodule,
(self.lineno, self.pos)
)
class Comment(Node):
"""defines a comment line.
# this is a comment
"""
def __init__(self, text, **kwargs):
super(Comment, self).__init__(**kwargs)
self.text = text
def __repr__(self):
return "Comment(%r, %r)" % (self.text, (self.lineno, self.pos))
class Expression(Node):
"""defines an inline expression.
${x+y}
"""
def __init__(self, text, escapes, **kwargs):
super(Expression, self).__init__(**kwargs)
self.text = text
self.escapes = escapes
self.escapes_code = ast.ArgumentList(escapes, **self.exception_kwargs)
self.code = ast.PythonCode(text, **self.exception_kwargs)
def declared_identifiers(self):
return []
def undeclared_identifiers(self):
# TODO: make the "filter" shortcut list configurable at parse/gen time
return self.code.undeclared_identifiers.union(
self.escapes_code.undeclared_identifiers.difference(
set(filters.DEFAULT_ESCAPES.keys())
)
).difference(self.code.declared_identifiers)
def __repr__(self):
return "Expression(%r, %r, %r)" % (
self.text,
self.escapes_code.args,
(self.lineno, self.pos)
)
class _TagMeta(type):
"""metaclass to allow Tag to produce a subclass according to
its keyword"""
_classmap = {}
def __init__(cls, clsname, bases, dict):
if cls.__keyword__ is not None:
cls._classmap[cls.__keyword__] = cls
super(_TagMeta, cls).__init__(clsname, bases, dict)
def __call__(cls, keyword, attributes, **kwargs):
if ":" in keyword:
ns, defname = keyword.split(':')
return type.__call__(CallNamespaceTag, ns, defname,
attributes, **kwargs)
try:
cls = _TagMeta._classmap[keyword]
except KeyError:
raise exceptions.CompileException(
"No such tag: '%s'" % keyword,
source=kwargs['source'],
lineno=kwargs['lineno'],
pos=kwargs['pos'],
filename=kwargs['filename']
)
return type.__call__(cls, keyword, attributes, **kwargs)
class Tag(Node):
"""abstract base class for tags.
<%sometag/>
<%someothertag>
stuff
</%someothertag>
"""
__metaclass__ = _TagMeta
__keyword__ = None
def __init__(self, keyword, attributes, expressions,
nonexpressions, required, **kwargs):
"""construct a new Tag instance.
this constructor not called directly, and is only called
by subclasses.
:param keyword: the tag keyword
:param attributes: raw dictionary of attribute key/value pairs
:param expressions: a set of identifiers that are legal attributes,
which can also contain embedded expressions
:param nonexpressions: a set of identifiers that are legal
attributes, which cannot contain embedded expressions
:param \**kwargs:
other arguments passed to the Node superclass (lineno, pos)
"""
super(Tag, self).__init__(**kwargs)
self.keyword = keyword
self.attributes = attributes
self._parse_attributes(expressions, nonexpressions)
missing = [r for r in required if r not in self.parsed_attributes]
if len(missing):
raise exceptions.CompileException(
"Missing attribute(s): %s" %
",".join([repr(m) for m in missing]),
**self.exception_kwargs)
self.parent = None
self.nodes = []
def is_root(self):
return self.parent is None
def get_children(self):
return self.nodes
def _parse_attributes(self, expressions, nonexpressions):
undeclared_identifiers = set()
self.parsed_attributes = {}
for key in self.attributes:
if key in expressions:
expr = []
for x in re.compile(r'(\${.+?})',
re.S).split(self.attributes[key]):
m = re.compile(r'^\${(.+?)}$', re.S).match(x)
if m:
code = ast.PythonCode(m.group(1).rstrip(),
**self.exception_kwargs)
# we aren't discarding "declared_identifiers" here,
# which we do so that list comprehension-declared
# variables aren't counted. As yet can't find a
# condition that requires it here.
undeclared_identifiers = \
undeclared_identifiers.union(
code.undeclared_identifiers)
expr.append('(%s)' % m.group(1))
else:
if x:
expr.append(repr(x))
self.parsed_attributes[key] = " + ".join(expr) or repr('')
elif key in nonexpressions:
if re.search(r'\${.+?}', self.attributes[key]):
raise exceptions.CompileException(
"Attibute '%s' in tag '%s' does not allow embedded "
"expressions" % (key, self.keyword),
**self.exception_kwargs)
self.parsed_attributes[key] = repr(self.attributes[key])
else:
raise exceptions.CompileException(
"Invalid attribute for tag '%s': '%s'" %
(self.keyword, key),
**self.exception_kwargs)
self.expression_undeclared_identifiers = undeclared_identifiers
def declared_identifiers(self):
return []
def undeclared_identifiers(self):
return self.expression_undeclared_identifiers
def __repr__(self):
return "%s(%r, %s, %r, %r)" % (self.__class__.__name__,
self.keyword,
util.sorted_dict_repr(self.attributes),
(self.lineno, self.pos),
self.nodes
)
class IncludeTag(Tag):
__keyword__ = 'include'
def __init__(self, keyword, attributes, **kwargs):
super(IncludeTag, self).__init__(
keyword,
attributes,
('file', 'import', 'args'),
(), ('file',), **kwargs)
self.page_args = ast.PythonCode(
"__DUMMY(%s)" % attributes.get('args', ''),
**self.exception_kwargs)
def declared_identifiers(self):
return []
def undeclared_identifiers(self):
identifiers = self.page_args.undeclared_identifiers.\
difference(set(["__DUMMY"])).\
difference(self.page_args.declared_identifiers)
return identifiers.union(super(IncludeTag, self).
undeclared_identifiers())
class NamespaceTag(Tag):
__keyword__ = 'namespace'
def __init__(self, keyword, attributes, **kwargs):
super(NamespaceTag, self).__init__(
keyword, attributes,
('file',),
('name','inheritable',
'import','module'),
(), **kwargs)
self.name = attributes.get('name', '__anon_%s' % hex(abs(id(self))))
if not 'name' in attributes and not 'import' in attributes:
raise exceptions.CompileException(
"'name' and/or 'import' attributes are required "
"for <%namespace>",
**self.exception_kwargs)
if 'file' in attributes and 'module' in attributes:
raise exceptions.CompileException(
"<%namespace> may only have one of 'file' or 'module'",
**self.exception_kwargs
)
def declared_identifiers(self):
return []
class TextTag(Tag):
__keyword__ = 'text'
def __init__(self, keyword, attributes, **kwargs):
super(TextTag, self).__init__(
keyword,
attributes, (),
('filter'), (), **kwargs)
self.filter_args = ast.ArgumentList(
attributes.get('filter', ''),
**self.exception_kwargs)
class DefTag(Tag):
__keyword__ = 'def'
def __init__(self, keyword, attributes, **kwargs):
super(DefTag, self).__init__(
keyword,
attributes,
('buffered', 'cached', 'cache_key', 'cache_timeout',
'cache_type', 'cache_dir', 'cache_url'),
('name','filter', 'decorator'),
('name',),
**kwargs)
name = attributes['name']
if re.match(r'^[\w_]+$',name):
raise exceptions.CompileException(
"Missing parenthesis in %def",
**self.exception_kwargs)
self.function_decl = ast.FunctionDecl("def " + name + ":pass",
**self.exception_kwargs)
self.name = self.function_decl.funcname
self.decorator = attributes.get('decorator', '')
self.filter_args = ast.ArgumentList(
attributes.get('filter', ''),
**self.exception_kwargs)
is_anonymous = False
is_block = False
@property
def funcname(self):
return self.function_decl.funcname
def get_argument_expressions(self, **kw):
return self.function_decl.get_argument_expressions(**kw)
def declared_identifiers(self):
return self.function_decl.argnames
def undeclared_identifiers(self):
res = []
for c in self.function_decl.defaults:
res += list(ast.PythonCode(c, **self.exception_kwargs).
undeclared_identifiers)
return res + list(self.filter_args.\
undeclared_identifiers.\
difference(filters.DEFAULT_ESCAPES.keys())
)
class BlockTag(Tag):
__keyword__ = 'block'
def __init__(self, keyword, attributes, **kwargs):
super(BlockTag, self).__init__(
keyword,
attributes,
('buffered', 'cached', 'cache_key', 'cache_timeout',
'cache_type', 'cache_dir', 'cache_url', 'args'),
('name','filter', 'decorator'),
(),
**kwargs)
name = attributes.get('name')
if name and not re.match(r'^[\w_]+$',name):
raise exceptions.CompileException(
"%block may not specify an argument signature",
**self.exception_kwargs)
if not name and attributes.get('args', None):
raise exceptions.CompileException(
"Only named %blocks may specify args",
**self.exception_kwargs
)
self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
**self.exception_kwargs)
self.name = name
self.decorator = attributes.get('decorator', '')
self.filter_args = ast.ArgumentList(
attributes.get('filter', ''),
**self.exception_kwargs)
is_block = True
@property
def is_anonymous(self):
return self.name is None
@property
def funcname(self):
return self.name or "__M_anon_%d" % (self.lineno, )
def get_argument_expressions(self, **kw):
return self.body_decl.get_argument_expressions(**kw)
def declared_identifiers(self):
return self.body_decl.argnames
def undeclared_identifiers(self):
return []
class CallTag(Tag):
__keyword__ = 'call'
def __init__(self, keyword, attributes, **kwargs):
super(CallTag, self).__init__(keyword, attributes,
('args'), ('expr',), ('expr',), **kwargs)
self.expression = attributes['expr']
self.code = ast.PythonCode(self.expression, **self.exception_kwargs)
self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
**self.exception_kwargs)
def declared_identifiers(self):
return self.code.declared_identifiers.union(self.body_decl.argnames)
def undeclared_identifiers(self):
return self.code.undeclared_identifiers.\
difference(self.code.declared_identifiers)
class CallNamespaceTag(Tag):
def __init__(self, namespace, defname, attributes, **kwargs):
super(CallNamespaceTag, self).__init__(
namespace + ":" + defname,
attributes,
tuple(attributes.keys()) + ('args', ),
(),
(),
**kwargs)
self.expression = "%s.%s(%s)" % (
namespace,
defname,
",".join(["%s=%s" % (k, v) for k, v in
self.parsed_attributes.iteritems()
if k != 'args'])
)
self.code = ast.PythonCode(self.expression, **self.exception_kwargs)
self.body_decl = ast.FunctionArgs(
attributes.get('args', ''),
**self.exception_kwargs)
def declared_identifiers(self):
return self.code.declared_identifiers.union(self.body_decl.argnames)
def undeclared_identifiers(self):
return self.code.undeclared_identifiers.\
difference(self.code.declared_identifiers)
class InheritTag(Tag):
__keyword__ = 'inherit'
def __init__(self, keyword, attributes, **kwargs):
super(InheritTag, self).__init__(
keyword, attributes,
('file',), (), ('file',), **kwargs)
class PageTag(Tag):
__keyword__ = 'page'
def __init__(self, keyword, attributes, **kwargs):
super(PageTag, self).__init__(
keyword,
attributes,
('cached', 'cache_key', 'cache_timeout',
'cache_type', 'cache_dir', 'cache_url',
'args', 'expression_filter'),
(),
(),
**kwargs)
self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
**self.exception_kwargs)
self.filter_args = ast.ArgumentList(
attributes.get('expression_filter', ''),
**self.exception_kwargs)
def declared_identifiers(self):
return self.body_decl.argnames
| [
[
8,
0,
0.0124,
0.0018,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0159,
0.0018,
0,
0.66,
0.05,
682,
0,
4,
0,
0,
682,
0,
0
],
[
1,
0,
0.0177,
0.0018,
0,
0.66,
... | [
"\"\"\"defines the parse tree components for Mako templates.\"\"\"",
"from mako import exceptions, ast, util, filters",
"import re",
"class Node(object):\n \"\"\"base class for a Node in the parse tree.\"\"\"\n def __init__(self, source, lineno, pos, filename):\n self.source = source\n sel... |
# ext/autohandler.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""adds autohandler functionality to Mako templates.
requires that the TemplateLookup class is used with templates.
usage:
<%!
from mako.ext.autohandler import autohandler
%>
<%inherit file="${autohandler(template, context)}"/>
or with custom autohandler filename:
<%!
from mako.ext.autohandler import autohandler
%>
<%inherit file="${autohandler(template, context, name='somefilename')}"/>
"""
import posixpath, os, re
def autohandler(template, context, name='autohandler'):
lookup = context.lookup
_template_uri = template.module._template_uri
if not lookup.filesystem_checks:
try:
return lookup._uri_cache[(autohandler, _template_uri, name)]
except KeyError:
pass
tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name]
while len(tokens):
path = '/' + '/'.join(tokens)
if path != _template_uri and _file_exists(lookup, path):
if not lookup.filesystem_checks:
return lookup._uri_cache.setdefault(
(autohandler, _template_uri, name), path)
else:
return path
if len(tokens) == 1:
break
tokens[-2:] = [name]
if not lookup.filesystem_checks:
return lookup._uri_cache.setdefault(
(autohandler, _template_uri, name), None)
else:
return None
def _file_exists(lookup, path):
psub = re.sub(r'^/', '',path)
for d in lookup.directories:
if os.path.exists(d + '/' + psub):
return True
else:
return False
| [
[
8,
0,
0.2538,
0.3077,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4308,
0.0154,
0,
0.66,
0.3333,
204,
0,
3,
0,
0,
204,
0,
0
],
[
2,
0,
0.6615,
0.4154,
0,
0.66... | [
"\"\"\"adds autohandler functionality to Mako templates.\n\nrequires that the TemplateLookup class is used with templates.\n\nusage:\n\n<%!\n from mako.ext.autohandler import autohandler",
"import posixpath, os, re",
"def autohandler(template, context, name='autohandler'):\n lookup = context.lookup\n _... |
# ext/preprocessors.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""preprocessing functions, used with the 'preprocessor'
argument on Template, TemplateLookup"""
import re
def convert_comments(text):
"""preprocess old style comments.
example:
from mako.ext.preprocessors import convert_comments
t = Template(..., preprocessor=preprocess_comments)"""
return re.sub(r'(?<=\n)\s*#[^#]', "##", text)
| [
[
8,
0,
0.375,
0.1,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.05,
0,
0.66,
0.5,
540,
0,
1,
0,
0,
540,
0,
0
],
[
2,
0,
0.775,
0.4,
0,
0.66,
1,
722... | [
"\"\"\"preprocessing functions, used with the 'preprocessor' \nargument on Template, TemplateLookup\"\"\"",
"import re",
"def convert_comments(text):\n \"\"\"preprocess old style comments.\n \n example:\n \n from mako.ext.preprocessors import convert_comments\n t = Template(..., preprocessor=preproc... |
# ext/babelplugin.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""gettext message extraction via Babel: http://babel.edgewall.org/"""
from StringIO import StringIO
from babel.messages.extract import extract_python
from mako import lexer, parsetree
def extract(fileobj, keywords, comment_tags, options):
"""Extract messages from Mako templates.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples
:rtype: ``iterator``
"""
encoding = options.get('input_encoding', options.get('encoding', None))
template_node = lexer.Lexer(fileobj.read(),
input_encoding=encoding).parse()
for extracted in extract_nodes(template_node.get_children(),
keywords, comment_tags, options):
yield extracted
def extract_nodes(nodes, keywords, comment_tags, options):
"""Extract messages from Mako's lexer node objects
:param nodes: an iterable of Mako parsetree.Node objects to extract from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples
:rtype: ``iterator``
"""
translator_comments = []
in_translator_comments = False
for node in nodes:
child_nodes = None
if in_translator_comments and isinstance(node, parsetree.Text) and \
not node.content.strip():
# Ignore whitespace within translator comments
continue
if isinstance(node, parsetree.Comment):
value = node.text.strip()
if in_translator_comments:
translator_comments.extend(_split_comment(node.lineno, value))
continue
for comment_tag in comment_tags:
if value.startswith(comment_tag):
in_translator_comments = True
translator_comments.extend(_split_comment(node.lineno,
value))
continue
if isinstance(node, parsetree.DefTag):
code = node.function_decl.code
child_nodes = node.nodes
elif isinstance(node, parsetree.BlockTag):
code = node.body_decl.code
child_nodes = node.nodes
elif isinstance(node, parsetree.CallTag):
code = node.code.code
child_nodes = node.nodes
elif isinstance(node, parsetree.PageTag):
code = node.body_decl.code
elif isinstance(node, parsetree.CallNamespaceTag):
attribs = ', '.join(['%s=%s' % (key, val)
for key, val in node.attributes.iteritems()])
code = '{%s}' % attribs
child_nodes = node.nodes
elif isinstance(node, parsetree.ControlLine):
if node.isend:
translator_comments = []
in_translator_comments = False
continue
code = node.text
elif isinstance(node, parsetree.Code):
# <% and <%! blocks would provide their own translator comments
translator_comments = []
in_translator_comments = False
code = node.code.code
elif isinstance(node, parsetree.Expression):
code = node.code.code
else:
translator_comments = []
in_translator_comments = False
continue
# Comments don't apply unless they immediately preceed the message
if translator_comments and \
translator_comments[-1][0] < node.lineno - 1:
translator_comments = []
else:
translator_comments = \
[comment[1] for comment in translator_comments]
if isinstance(code, unicode):
code = code.encode('ascii', 'backslashreplace')
code = StringIO(code)
for lineno, funcname, messages, python_translator_comments \
in extract_python(code, keywords, comment_tags, options):
yield (node.lineno + (lineno - 1), funcname, messages,
translator_comments + python_translator_comments)
translator_comments = []
in_translator_comments = False
if child_nodes:
for extracted in extract_nodes(child_nodes, keywords, comment_tags,
options):
yield extracted
def _split_comment(lineno, comment):
"""Return the multiline comment at lineno split into a list of comment line
numbers and the accompanying comment line"""
return [(lineno + index, line) for index, line in
enumerate(comment.splitlines())]
| [
[
8,
0,
0.053,
0.0076,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0606,
0.0076,
0,
0.66,
0.1667,
609,
0,
1,
0,
0,
609,
0,
0
],
[
1,
0,
0.0758,
0.0076,
0,
0.66,... | [
"\"\"\"gettext message extraction via Babel: http://babel.edgewall.org/\"\"\"",
"from StringIO import StringIO",
"from babel.messages.extract import extract_python",
"from mako import lexer, parsetree",
"def extract(fileobj, keywords, comment_tags, options):\n \"\"\"Extract messages from Mako templates.\... |
# ext/pygmentplugin.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
try:
set
except NameError:
from sets import Set as set
from pygments.lexers.web import \
HtmlLexer, XmlLexer, JavascriptLexer, CssLexer
from pygments.lexers.agile import PythonLexer
from pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \
include, using, this
from pygments.token import Error, Punctuation, \
Text, Comment, Operator, Keyword, Name, String, Number, Other, Literal
from pygments.util import html_doctype_matches, looks_like_xml
class MakoLexer(RegexLexer):
name = 'Mako'
aliases = ['mako']
filenames = ['*.mao']
tokens = {
'root': [
(r'(\s*)(\%)(\s*end(?:\w+))(\n|\Z)',
bygroups(Text, Comment.Preproc, Keyword, Other)),
(r'(\s*)(\%(?!%))([^\n]*)(\n|\Z)',
bygroups(Text, Comment.Preproc, using(PythonLexer), Other)),
(r'(\s*)(##[^\n]*)(\n|\Z)',
bygroups(Text, Comment.Preproc, Other)),
(r'''(?s)<%doc>.*?</%doc>''', Comment.Preproc),
(r'(<%)([\w\.\:]+)', bygroups(Comment.Preproc, Name.Builtin), 'tag'),
(r'(</%)([\w\.\:]+)(>)', bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)),
(r'<%(?=([\w\.\:]+))', Comment.Preproc, 'ondeftags'),
(r'(<%(?:!?))(.*?)(%>)(?s)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'(\$\{)(.*?)(\})',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'''(?sx)
(.+?) # anything, followed by:
(?:
(?<=\n)(?=%(?!%)|\#\#) | # an eval or comment line
(?=\#\*) | # multiline comment
(?=</?%) | # a python block
# call start or end
(?=\$\{) | # a substitution
(?<=\n)(?=\s*%) |
# - don't consume
(\\\n) | # an escaped newline
\Z # end of string
)
''', bygroups(Other, Operator)),
(r'\s+', Text),
],
'ondeftags': [
(r'<%', Comment.Preproc),
(r'(?<=<%)(include|inherit|namespace|page)', Name.Builtin),
include('tag'),
],
'tag': [
(r'((?:\w+)\s*=)\s*(".*?")',
bygroups(Name.Attribute, String)),
(r'/?\s*>', Comment.Preproc, '#pop'),
(r'\s+', Text),
],
'attr': [
('".*?"', String, '#pop'),
("'.*?'", String, '#pop'),
(r'[^\s>]+', String, '#pop'),
],
}
class MakoHtmlLexer(DelegatingLexer):
name = 'HTML+Mako'
aliases = ['html+mako']
def __init__(self, **options):
super(MakoHtmlLexer, self).__init__(HtmlLexer, MakoLexer,
**options)
class MakoXmlLexer(DelegatingLexer):
name = 'XML+Mako'
aliases = ['xml+mako']
def __init__(self, **options):
super(MakoXmlLexer, self).__init__(XmlLexer, MakoLexer,
**options)
class MakoJavascriptLexer(DelegatingLexer):
name = 'JavaScript+Mako'
aliases = ['js+mako', 'javascript+mako']
def __init__(self, **options):
super(MakoJavascriptLexer, self).__init__(JavascriptLexer,
MakoLexer, **options)
class MakoCssLexer(DelegatingLexer):
name = 'CSS+Mako'
aliases = ['css+mako']
def __init__(self, **options):
super(MakoCssLexer, self).__init__(CssLexer, MakoLexer,
**options)
| [
[
1,
0,
0.0654,
0.0093,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
7,
0,
0.0888,
0.0374,
0,
0.66,
0.0909,
0,
0,
1,
0,
0,
0,
0,
0
],
[
8,
1,
0.0841,
0.0093,
1,
0.41... | [
"import re",
"try:\n set\nexcept NameError:\n from sets import Set as set",
" set",
" from sets import Set as set",
"from pygments.lexers.web import \\\n HtmlLexer, XmlLexer, JavascriptLexer, CssLexer",
"from pygments.lexers.agile import PythonLexer",
"from pygments.lexer import Lexer, D... |
# ext/turbogears.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re, inspect
from mako.lookup import TemplateLookup
from mako.template import Template
class TGPlugin(object):
"""TurboGears compatible Template Plugin."""
def __init__(self, extra_vars_func=None, options=None, extension='mak'):
self.extra_vars_func = extra_vars_func
self.extension = extension
if not options:
options = {}
# Pull the options out and initialize the lookup
lookup_options = {}
for k, v in options.iteritems():
if k.startswith('mako.'):
lookup_options[k[5:]] = v
elif k in ['directories', 'filesystem_checks', 'module_directory']:
lookup_options[k] = v
self.lookup = TemplateLookup(**lookup_options)
self.tmpl_options = {}
# transfer lookup args to template args, based on those available
# in getargspec
for kw in inspect.getargspec(Template.__init__)[0]:
if kw in lookup_options:
self.tmpl_options[kw] = lookup_options[kw]
def load_template(self, templatename, template_string=None):
"""Loads a template from a file or a string"""
if template_string is not None:
return Template(template_string, **self.tmpl_options)
# Translate TG dot notation to normal / template path
if '/' not in templatename:
templatename = '/' + templatename.replace('.', '/') + '.' + self.extension
# Lookup template
return self.lookup.get_template(templatename)
def render(self, info, format="html", fragment=False, template=None):
if isinstance(template, basestring):
template = self.load_template(template)
# Load extra vars func if provided
if self.extra_vars_func:
info.update(self.extra_vars_func())
return template.render(**info)
| [
[
1,
0,
0.125,
0.0179,
0,
0.66,
0,
540,
0,
2,
0,
0,
540,
0,
0
],
[
1,
0,
0.1429,
0.0179,
0,
0.66,
0.3333,
258,
0,
1,
0,
0,
258,
0,
0
],
[
1,
0,
0.1607,
0.0179,
0,
0... | [
"import re, inspect",
"from mako.lookup import TemplateLookup",
"from mako.template import Template",
"class TGPlugin(object):\n \"\"\"TurboGears compatible Template Plugin.\"\"\"\n\n def __init__(self, extra_vars_func=None, options=None, extension='mak'):\n self.extra_vars_func = extra_vars_func... |
# mako/codegen.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""provides functionality for rendering a parsetree constructing into module source code."""
import time
import re
from mako.pygen import PythonPrinter
from mako import util, ast, parsetree, filters, exceptions
MAGIC_NUMBER = 6
def compile(node,
uri,
filename=None,
default_filters=None,
buffer_filters=None,
imports=None,
source_encoding=None,
generate_magic_comment=True,
disable_unicode=False,
strict_undefined=False):
"""Generate module source code given a parsetree node,
uri, and optional source filename"""
# if on Py2K, push the "source_encoding" string to be
# a bytestring itself, as we will be embedding it into
# the generated source and we don't want to coerce the
# result into a unicode object, in "disable_unicode" mode
if not util.py3k and isinstance(source_encoding, unicode):
source_encoding = source_encoding.encode(source_encoding)
buf = util.FastEncodingBuffer()
printer = PythonPrinter(buf)
_GenerateRenderMethod(printer,
_CompileContext(uri,
filename,
default_filters,
buffer_filters,
imports,
source_encoding,
generate_magic_comment,
disable_unicode,
strict_undefined),
node)
return buf.getvalue()
class _CompileContext(object):
def __init__(self,
uri,
filename,
default_filters,
buffer_filters,
imports,
source_encoding,
generate_magic_comment,
disable_unicode,
strict_undefined):
self.uri = uri
self.filename = filename
self.default_filters = default_filters
self.buffer_filters = buffer_filters
self.imports = imports
self.source_encoding = source_encoding
self.generate_magic_comment = generate_magic_comment
self.disable_unicode = disable_unicode
self.strict_undefined = strict_undefined
class _GenerateRenderMethod(object):
"""A template visitor object which generates the
full module source for a template.
"""
def __init__(self, printer, compiler, node):
self.printer = printer
self.last_source_line = -1
self.compiler = compiler
self.node = node
self.identifier_stack = [None]
self.in_def = isinstance(node, (parsetree.DefTag, parsetree.BlockTag))
if self.in_def:
name = "render_%s" % node.funcname
args = node.get_argument_expressions()
filtered = len(node.filter_args.args) > 0
buffered = eval(node.attributes.get('buffered', 'False'))
cached = eval(node.attributes.get('cached', 'False'))
defs = None
pagetag = None
if node.is_block and not node.is_anonymous:
args += ['**pageargs']
else:
defs = self.write_toplevel()
pagetag = self.compiler.pagetag
name = "render_body"
if pagetag is not None:
args = pagetag.body_decl.get_argument_expressions()
if not pagetag.body_decl.kwargs:
args += ['**pageargs']
cached = eval(pagetag.attributes.get('cached', 'False'))
else:
args = ['**pageargs']
cached = False
buffered = filtered = False
if args is None:
args = ['context']
else:
args = [a for a in ['context'] + args]
self.write_render_callable(
pagetag or node,
name, args,
buffered, filtered, cached)
if defs is not None:
for node in defs:
_GenerateRenderMethod(printer, compiler, node)
@property
def identifiers(self):
return self.identifier_stack[-1]
def write_toplevel(self):
"""Traverse a template structure for module-level directives and
generate the start of module-level code.
"""
inherit = []
namespaces = {}
module_code = []
encoding =[None]
self.compiler.pagetag = None
class FindTopLevel(object):
def visitInheritTag(s, node):
inherit.append(node)
def visitNamespaceTag(s, node):
namespaces[node.name] = node
def visitPageTag(s, node):
self.compiler.pagetag = node
def visitCode(s, node):
if node.ismodule:
module_code.append(node)
f = FindTopLevel()
for n in self.node.nodes:
n.accept_visitor(f)
self.compiler.namespaces = namespaces
module_ident = set()
for n in module_code:
module_ident = module_ident.union(n.declared_identifiers())
module_identifiers = _Identifiers()
module_identifiers.declared = module_ident
# module-level names, python code
if self.compiler.generate_magic_comment and \
self.compiler.source_encoding:
self.printer.writeline("# -*- encoding:%s -*-" %
self.compiler.source_encoding)
self.printer.writeline("from mako import runtime, filters, cache")
self.printer.writeline("UNDEFINED = runtime.UNDEFINED")
self.printer.writeline("__M_dict_builtin = dict")
self.printer.writeline("__M_locals_builtin = locals")
self.printer.writeline("_magic_number = %r" % MAGIC_NUMBER)
self.printer.writeline("_modified_time = %r" % time.time())
self.printer.writeline(
"_template_filename=%r" % self.compiler.filename)
self.printer.writeline("_template_uri=%r" % self.compiler.uri)
self.printer.writeline(
"_template_cache=cache.Cache(__name__, _modified_time)")
self.printer.writeline(
"_source_encoding=%r" % self.compiler.source_encoding)
if self.compiler.imports:
buf = ''
for imp in self.compiler.imports:
buf += imp + "\n"
self.printer.writeline(imp)
impcode = ast.PythonCode(
buf,
source='', lineno=0,
pos=0,
filename='template defined imports')
else:
impcode = None
main_identifiers = module_identifiers.branch(self.node)
module_identifiers.topleveldefs = \
module_identifiers.topleveldefs.\
union(main_identifiers.topleveldefs)
module_identifiers.declared.add("UNDEFINED")
if impcode:
module_identifiers.declared.update(impcode.declared_identifiers)
self.compiler.identifiers = module_identifiers
self.printer.writeline("_exports = %r" %
[n.name for n in
main_identifiers.topleveldefs.values()]
)
self.printer.write("\n\n")
if len(module_code):
self.write_module_code(module_code)
if len(inherit):
self.write_namespaces(namespaces)
self.write_inherit(inherit[-1])
elif len(namespaces):
self.write_namespaces(namespaces)
return main_identifiers.topleveldefs.values()
def write_render_callable(self, node, name, args, buffered, filtered, cached):
"""write a top-level render callable.
this could be the main render() method or that of a top-level def."""
if self.in_def:
decorator = node.decorator
if decorator:
self.printer.writeline("@runtime._decorate_toplevel(%s)" % decorator)
self.printer.writelines(
"def %s(%s):" % (name, ','.join(args)),
"context.caller_stack._push_frame()",
"try:"
)
if buffered or filtered or cached:
self.printer.writeline("context._push_buffer()")
self.identifier_stack.append(self.compiler.identifiers.branch(self.node))
if (not self.in_def or self.node.is_block) and '**pageargs' in args:
self.identifier_stack[-1].argument_declared.add('pageargs')
if not self.in_def and (
len(self.identifiers.locally_assigned) > 0 or
len(self.identifiers.argument_declared) > 0
):
self.printer.writeline("__M_locals = __M_dict_builtin(%s)" %
','.join([
"%s=%s" % (x, x) for x in
self.identifiers.argument_declared
]))
self.write_variable_declares(self.identifiers, toplevel=True)
for n in self.node.nodes:
n.accept_visitor(self)
self.write_def_finish(self.node, buffered, filtered, cached)
self.printer.writeline(None)
self.printer.write("\n\n")
if cached:
self.write_cache_decorator(
node, name,
args, buffered,
self.identifiers, toplevel=True)
def write_module_code(self, module_code):
"""write module-level template code, i.e. that which
is enclosed in <%! %> tags in the template."""
for n in module_code:
self.write_source_comment(n)
self.printer.write_indented_block(n.text)
def write_inherit(self, node):
"""write the module-level inheritance-determination callable."""
self.printer.writelines(
"def _mako_inherit(template, context):",
"_mako_generate_namespaces(context)",
"return runtime._inherit_from(context, %s, _template_uri)" %
(node.parsed_attributes['file']),
None
)
def write_namespaces(self, namespaces):
"""write the module-level namespace-generating callable."""
self.printer.writelines(
"def _mako_get_namespace(context, name):",
"try:",
"return context.namespaces[(__name__, name)]",
"except KeyError:",
"_mako_generate_namespaces(context)",
"return context.namespaces[(__name__, name)]",
None,None
)
self.printer.writeline("def _mako_generate_namespaces(context):")
for node in namespaces.values():
if node.attributes.has_key('import'):
self.compiler.has_ns_imports = True
self.write_source_comment(node)
if len(node.nodes):
self.printer.writeline("def make_namespace():")
export = []
identifiers = self.compiler.identifiers.branch(node)
self.in_def = True
class NSDefVisitor(object):
def visitDefTag(s, node):
s.visitDefOrBase(node)
def visitBlockTag(s, node):
s.visitDefOrBase(node)
def visitDefOrBase(s, node):
if node.is_anonymous:
raise exceptions.CompileException(
"Can't put anonymous blocks inside <%namespace>",
**node.exception_kwargs
)
self.write_inline_def(node, identifiers, nested=False)
export.append(node.funcname)
vis = NSDefVisitor()
for n in node.nodes:
n.accept_visitor(vis)
self.printer.writeline("return [%s]" % (','.join(export)))
self.printer.writeline(None)
self.in_def = False
callable_name = "make_namespace()"
else:
callable_name = "None"
if 'file' in node.parsed_attributes:
self.printer.writeline(
"ns = runtime.TemplateNamespace(%r, context._clean_inheritance_tokens(),"
" templateuri=%s, callables=%s, calling_uri=_template_uri)" %
(
node.name,
node.parsed_attributes.get('file', 'None'),
callable_name,
)
)
elif 'module' in node.parsed_attributes:
self.printer.writeline(
"ns = runtime.ModuleNamespace(%r, context._clean_inheritance_tokens(),"
" callables=%s, calling_uri=_template_uri, module=%s)" %
(
node.name,
callable_name,
node.parsed_attributes.get('module', 'None')
)
)
else:
self.printer.writeline(
"ns = runtime.Namespace(%r, context._clean_inheritance_tokens(),"
" callables=%s, calling_uri=_template_uri)" %
(
node.name,
callable_name,
)
)
if eval(node.attributes.get('inheritable', "False")):
self.printer.writeline("context['self'].%s = ns" % (node.name))
self.printer.writeline("context.namespaces[(__name__, %s)] = ns" % repr(node.name))
self.printer.write("\n")
if not len(namespaces):
self.printer.writeline("pass")
self.printer.writeline(None)
def write_variable_declares(self, identifiers, toplevel=False, limit=None):
"""write variable declarations at the top of a function.
the variable declarations are in the form of callable
definitions for defs and/or name lookup within the
function's context argument. the names declared are based
on the names that are referenced in the function body,
which don't otherwise have any explicit assignment
operation. names that are assigned within the body are
assumed to be locally-scoped variables and are not
separately declared.
for def callable definitions, if the def is a top-level
callable then a 'stub' callable is generated which wraps
the current Context into a closure. if the def is not
top-level, it is fully rendered as a local closure.
"""
# collection of all defs available to us in this scope
comp_idents = dict([(c.funcname, c) for c in identifiers.defs])
to_write = set()
# write "context.get()" for all variables we are going to
# need that arent in the namespace yet
to_write = to_write.union(identifiers.undeclared)
# write closure functions for closures that we define
# right here
to_write = to_write.union([c.funcname for c in identifiers.closuredefs.values()])
# remove identifiers that are declared in the argument
# signature of the callable
to_write = to_write.difference(identifiers.argument_declared)
# remove identifiers that we are going to assign to.
# in this way we mimic Python's behavior,
# i.e. assignment to a variable within a block
# means that variable is now a "locally declared" var,
# which cannot be referenced beforehand.
to_write = to_write.difference(identifiers.locally_declared)
# if a limiting set was sent, constraint to those items in that list
# (this is used for the caching decorator)
if limit is not None:
to_write = to_write.intersection(limit)
if toplevel and getattr(self.compiler, 'has_ns_imports', False):
self.printer.writeline("_import_ns = {}")
self.compiler.has_imports = True
for ident, ns in self.compiler.namespaces.iteritems():
if ns.attributes.has_key('import'):
self.printer.writeline(
"_mako_get_namespace(context, %r)._populate(_import_ns, %r)" %
(
ident,
re.split(r'\s*,\s*', ns.attributes['import'])
))
for ident in to_write:
if ident in comp_idents:
comp = comp_idents[ident]
if comp.is_block:
if not comp.is_anonymous:
self.write_def_decl(comp, identifiers)
else:
self.write_inline_def(comp, identifiers, nested=True)
else:
if comp.is_root():
self.write_def_decl(comp, identifiers)
else:
self.write_inline_def(comp, identifiers, nested=True)
elif ident in self.compiler.namespaces:
self.printer.writeline(
"%s = _mako_get_namespace(context, %r)" %
(ident, ident)
)
else:
if getattr(self.compiler, 'has_ns_imports', False):
if self.compiler.strict_undefined:
self.printer.writelines(
"%s = _import_ns.get(%r, UNDEFINED)" %
(ident, ident),
"if %s is UNDEFINED:" % ident,
"try:",
"%s = context[%r]" % (ident, ident),
"except KeyError:",
"raise NameError(\"'%s' is not defined\")" %
ident,
None, None
)
else:
self.printer.writeline(
"%s = _import_ns.get(%r, context.get(%r, UNDEFINED))" %
(ident, ident, ident))
else:
if self.compiler.strict_undefined:
self.printer.writelines(
"try:",
"%s = context[%r]" % (ident, ident),
"except KeyError:",
"raise NameError(\"'%s' is not defined\")" %
ident,
None
)
else:
self.printer.writeline(
"%s = context.get(%r, UNDEFINED)" % (ident, ident)
)
self.printer.writeline("__M_writer = context.writer()")
def write_source_comment(self, node):
"""write a source comment containing the line number of the corresponding template line."""
if self.last_source_line != node.lineno:
self.printer.writeline("# SOURCE LINE %d" % node.lineno)
self.last_source_line = node.lineno
def write_def_decl(self, node, identifiers):
"""write a locally-available callable referencing a top-level def"""
funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(include_defaults=False)
if not self.in_def and (
len(self.identifiers.locally_assigned) > 0 or
len(self.identifiers.argument_declared) > 0):
nameargs.insert(0, 'context.locals_(__M_locals)')
else:
nameargs.insert(0, 'context')
self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls)))
self.printer.writeline("return render_%s(%s)" % (funcname, ",".join(nameargs)))
self.printer.writeline(None)
def write_inline_def(self, node, identifiers, nested):
"""write a locally-available def callable inside an enclosing def."""
namedecls = node.get_argument_expressions()
decorator = node.decorator
if decorator:
self.printer.writeline("@runtime._decorate_inline(context, %s)" % decorator)
self.printer.writeline("def %s(%s):" % (node.funcname, ",".join(namedecls)))
filtered = len(node.filter_args.args) > 0
buffered = eval(node.attributes.get('buffered', 'False'))
cached = eval(node.attributes.get('cached', 'False'))
self.printer.writelines(
"context.caller_stack._push_frame()",
"try:"
)
if buffered or filtered or cached:
self.printer.writelines(
"context._push_buffer()",
)
identifiers = identifiers.branch(node, nested=nested)
self.write_variable_declares(identifiers)
self.identifier_stack.append(identifiers)
for n in node.nodes:
n.accept_visitor(self)
self.identifier_stack.pop()
self.write_def_finish(node, buffered, filtered, cached)
self.printer.writeline(None)
if cached:
self.write_cache_decorator(node, node.funcname,
namedecls, False, identifiers,
inline=True, toplevel=False)
def write_def_finish(self, node, buffered, filtered, cached, callstack=True):
"""write the end section of a rendering function, either outermost or inline.
this takes into account if the rendering function was filtered, buffered, etc.
and closes the corresponding try: block if any, and writes code to retrieve
captured content, apply filters, send proper return value."""
if not buffered and not cached and not filtered:
self.printer.writeline("return ''")
if callstack:
self.printer.writelines(
"finally:",
"context.caller_stack._pop_frame()",
None
)
if buffered or filtered or cached:
if buffered or cached:
# in a caching scenario, don't try to get a writer
# from the context after popping; assume the caching
# implemenation might be using a context with no
# extra buffers
self.printer.writelines(
"finally:",
"__M_buf = context._pop_buffer()"
)
else:
self.printer.writelines(
"finally:",
"__M_buf, __M_writer = context._pop_buffer_and_writer()"
)
if callstack:
self.printer.writeline("context.caller_stack._pop_frame()")
s = "__M_buf.getvalue()"
if filtered:
s = self.create_filter_callable(node.filter_args.args, s, False)
self.printer.writeline(None)
if buffered and not cached:
s = self.create_filter_callable(self.compiler.buffer_filters, s, False)
if buffered or cached:
self.printer.writeline("return %s" % s)
else:
self.printer.writelines(
"__M_writer(%s)" % s,
"return ''"
)
def write_cache_decorator(self, node_or_pagetag, name,
args, buffered, identifiers,
inline=False, toplevel=False):
"""write a post-function decorator to replace a rendering
callable with a cached version of itself."""
self.printer.writeline("__M_%s = %s" % (name, name))
cachekey = node_or_pagetag.parsed_attributes.get('cache_key', repr(name))
cacheargs = {}
for arg in (
('cache_type', 'type'), ('cache_dir', 'data_dir'),
('cache_timeout', 'expiretime'), ('cache_url', 'url')):
val = node_or_pagetag.parsed_attributes.get(arg[0], None)
if val is not None:
if arg[1] == 'expiretime':
cacheargs[arg[1]] = int(eval(val))
else:
cacheargs[arg[1]] = val
else:
if self.compiler.pagetag is not None:
val = self.compiler.pagetag.parsed_attributes.get(arg[0], None)
if val is not None:
if arg[1] == 'expiretime':
cacheargs[arg[1]] == int(eval(val))
else:
cacheargs[arg[1]] = val
self.printer.writeline("def %s(%s):" % (name, ','.join(args)))
# form "arg1, arg2, arg3=arg3, arg4=arg4", etc.
pass_args = [
'=' in a and "%s=%s" % ((a.split('=')[0],)*2) or a
for a in args
]
self.write_variable_declares(
identifiers,
toplevel=toplevel,
limit=node_or_pagetag.undeclared_identifiers()
)
if buffered:
s = "context.get('local')."\
"get_cached(%s, defname=%r, %screatefunc=lambda:__M_%s(%s))" % \
(cachekey, name,
''.join(["%s=%s, " % (k,v) for k, v in cacheargs.iteritems()]),
name, ','.join(pass_args))
# apply buffer_filters
s = self.create_filter_callable(self.compiler.buffer_filters, s, False)
self.printer.writelines("return " + s,None)
else:
self.printer.writelines(
"__M_writer(context.get('local')."
"get_cached(%s, defname=%r, %screatefunc=lambda:__M_%s(%s)))" %
(cachekey, name,
''.join(["%s=%s, " % (k,v) for k, v in cacheargs.iteritems()]),
name, ','.join(pass_args)),
"return ''",
None
)
def create_filter_callable(self, args, target, is_expression):
"""write a filter-applying expression based on the filters
present in the given filter names, adjusting for the global
'default' filter aliases as needed."""
def locate_encode(name):
if re.match(r'decode\..+', name):
return "filters." + name
elif self.compiler.disable_unicode:
return filters.NON_UNICODE_ESCAPES.get(name, name)
else:
return filters.DEFAULT_ESCAPES.get(name, name)
if 'n' not in args:
if is_expression:
if self.compiler.pagetag:
args = self.compiler.pagetag.filter_args.args + args
if self.compiler.default_filters:
args = self.compiler.default_filters + args
for e in args:
# if filter given as a function, get just the identifier portion
if e == 'n':
continue
m = re.match(r'(.+?)(\(.*\))', e)
if m:
(ident, fargs) = m.group(1,2)
f = locate_encode(ident)
e = f + fargs
else:
x = e
e = locate_encode(e)
assert e is not None
target = "%s(%s)" % (e, target)
return target
def visitExpression(self, node):
self.write_source_comment(node)
if len(node.escapes) or \
(
self.compiler.pagetag is not None and
len(self.compiler.pagetag.filter_args.args)
) or \
len(self.compiler.default_filters):
s = self.create_filter_callable(node.escapes_code.args, "%s" % node.text, True)
self.printer.writeline("__M_writer(%s)" % s)
else:
self.printer.writeline("__M_writer(%s)" % node.text)
def visitControlLine(self, node):
if node.isend:
if not node.get_children():
self.printer.writeline("pass")
self.printer.writeline(None)
else:
self.write_source_comment(node)
self.printer.writeline(node.text)
def visitText(self, node):
self.write_source_comment(node)
self.printer.writeline("__M_writer(%s)" % repr(node.content))
def visitTextTag(self, node):
filtered = len(node.filter_args.args) > 0
if filtered:
self.printer.writelines(
"__M_writer = context._push_writer()",
"try:",
)
for n in node.nodes:
n.accept_visitor(self)
if filtered:
self.printer.writelines(
"finally:",
"__M_buf, __M_writer = context._pop_buffer_and_writer()",
"__M_writer(%s)" %
self.create_filter_callable(
node.filter_args.args,
"__M_buf.getvalue()",
False),
None
)
def visitCode(self, node):
if not node.ismodule:
self.write_source_comment(node)
self.printer.write_indented_block(node.text)
if not self.in_def and len(self.identifiers.locally_assigned) > 0:
# if we are the "template" def, fudge locally
# declared/modified variables into the "__M_locals" dictionary,
# which is used for def calls within the same template,
# to simulate "enclosing scope"
self.printer.writeline('__M_locals_builtin_stored = __M_locals_builtin()')
self.printer.writeline(
'__M_locals.update(__M_dict_builtin([(__M_key,'
' __M_locals_builtin_stored[__M_key]) for '
'__M_key in [%s] if __M_key in __M_locals_builtin_stored]))' %
','.join([repr(x) for x in node.declared_identifiers()]))
def visitIncludeTag(self, node):
self.write_source_comment(node)
args = node.attributes.get('args')
if args:
self.printer.writeline(
"runtime._include_file(context, %s, _template_uri, %s)" %
(node.parsed_attributes['file'], args))
else:
self.printer.writeline(
"runtime._include_file(context, %s, _template_uri)" %
(node.parsed_attributes['file']))
def visitNamespaceTag(self, node):
pass
def visitDefTag(self, node):
pass
def visitBlockTag(self, node):
if node.is_anonymous:
self.printer.writeline("%s()" % node.funcname)
else:
nameargs = node.get_argument_expressions(include_defaults=False)
nameargs += ['**pageargs']
self.printer.writeline("if 'parent' not in context._data or "
"not hasattr(context._data['parent'], '%s'):"
% node.funcname)
self.printer.writeline("context['self'].%s(%s)" % (node.funcname, ",".join(nameargs)))
self.printer.writeline("\n")
def visitCallNamespaceTag(self, node):
# TODO: we can put namespace-specific checks here, such
# as ensure the given namespace will be imported,
# pre-import the namespace, etc.
self.visitCallTag(node)
def visitCallTag(self, node):
self.printer.writeline("def ccall(caller):")
export = ['body']
callable_identifiers = self.identifiers.branch(node, nested=True)
body_identifiers = callable_identifiers.branch(node, nested=False)
# we want the 'caller' passed to ccall to be used
# for the body() function, but for other non-body()
# <%def>s within <%call> we want the current caller
# off the call stack (if any)
body_identifiers.add_declared('caller')
self.identifier_stack.append(body_identifiers)
class DefVisitor(object):
def visitDefTag(s, node):
s.visitDefOrBase(node)
def visitBlockTag(s, node):
s.visitDefOrBase(node)
def visitDefOrBase(s, node):
self.write_inline_def(node, callable_identifiers, nested=False)
if not node.is_anonymous:
export.append(node.funcname)
# remove defs that are within the <%call> from the "closuredefs" defined
# in the body, so they dont render twice
if node.funcname in body_identifiers.closuredefs:
del body_identifiers.closuredefs[node.funcname]
vis = DefVisitor()
for n in node.nodes:
n.accept_visitor(vis)
self.identifier_stack.pop()
bodyargs = node.body_decl.get_argument_expressions()
self.printer.writeline("def body(%s):" % ','.join(bodyargs))
# TODO: figure out best way to specify
# buffering/nonbuffering (at call time would be better)
buffered = False
if buffered:
self.printer.writelines(
"context._push_buffer()",
"try:"
)
self.write_variable_declares(body_identifiers)
self.identifier_stack.append(body_identifiers)
for n in node.nodes:
n.accept_visitor(self)
self.identifier_stack.pop()
self.write_def_finish(node, buffered, False, False, callstack=False)
self.printer.writelines(
None,
"return [%s]" % (','.join(export)),
None
)
self.printer.writelines(
# get local reference to current caller, if any
"__M_caller = context.caller_stack._get_caller()",
# push on caller for nested call
"context.caller_stack.nextcaller = "
"runtime.Namespace('caller', context, callables=ccall(__M_caller))",
"try:")
self.write_source_comment(node)
self.printer.writelines(
"__M_writer(%s)" % self.create_filter_callable([], node.expression, True),
"finally:",
"context.caller_stack.nextcaller = None",
None
)
class _Identifiers(object):
"""tracks the status of identifier names as template code is rendered."""
def __init__(self, node=None, parent=None, nested=False):
if parent is not None:
# if we are the branch created in write_namespaces(),
# we don't share any context from the main body().
if isinstance(node, parsetree.NamespaceTag):
self.declared = set()
self.topleveldefs = util.SetLikeDict()
else:
# things that have already been declared
# in an enclosing namespace (i.e. names we can just use)
self.declared = set(parent.declared).\
union([c.name for c in parent.closuredefs.values()]).\
union(parent.locally_declared).\
union(parent.argument_declared)
# if these identifiers correspond to a "nested"
# scope, it means whatever the parent identifiers
# had as undeclared will have been declared by that parent,
# and therefore we have them in our scope.
if nested:
self.declared = self.declared.union(parent.undeclared)
# top level defs that are available
self.topleveldefs = util.SetLikeDict(**parent.topleveldefs)
else:
self.declared = set()
self.topleveldefs = util.SetLikeDict()
# things within this level that are referenced before they
# are declared (e.g. assigned to)
self.undeclared = set()
# things that are declared locally. some of these things
# could be in the "undeclared" list as well if they are
# referenced before declared
self.locally_declared = set()
# assignments made in explicit python blocks.
# these will be propagated to
# the context of local def calls.
self.locally_assigned = set()
# things that are declared in the argument
# signature of the def callable
self.argument_declared = set()
# closure defs that are defined in this level
self.closuredefs = util.SetLikeDict()
self.node = node
if node is not None:
node.accept_visitor(self)
def branch(self, node, **kwargs):
"""create a new Identifiers for a new Node, with
this Identifiers as the parent."""
return _Identifiers(node, self, **kwargs)
@property
def defs(self):
return set(self.topleveldefs.union(self.closuredefs).values())
def __repr__(self):
return "Identifiers(declared=%r, locally_declared=%r, "\
"undeclared=%r, topleveldefs=%r, closuredefs=%r, argumentdeclared=%r)" %\
(
list(self.declared),
list(self.locally_declared),
list(self.undeclared),
[c.name for c in self.topleveldefs.values()],
[c.name for c in self.closuredefs.values()],
self.argument_declared)
def check_declared(self, node):
"""update the state of this Identifiers with the undeclared
and declared identifiers of the given node."""
for ident in node.undeclared_identifiers():
if ident != 'context' and ident not in self.declared.union(self.locally_declared):
self.undeclared.add(ident)
for ident in node.declared_identifiers():
self.locally_declared.add(ident)
def add_declared(self, ident):
self.declared.add(ident)
if ident in self.undeclared:
self.undeclared.remove(ident)
def visitExpression(self, node):
self.check_declared(node)
def visitControlLine(self, node):
self.check_declared(node)
def visitCode(self, node):
if not node.ismodule:
self.check_declared(node)
self.locally_assigned = self.locally_assigned.union(node.declared_identifiers())
def visitNamespaceTag(self, node):
# only traverse into the sub-elements of a
# <%namespace> tag if we are the branch created in
# write_namespaces()
if self.node is node:
for n in node.nodes:
n.accept_visitor(self)
def _check_name_exists(self, collection, node):
existing = collection.get(node.funcname)
collection[node.funcname] = node
if existing is not None and \
existing is not node and \
(node.is_block or existing.is_block):
raise exceptions.CompileException(
"%%def or %%block named '%s' already "
"exists in this template." %
node.funcname, **node.exception_kwargs)
def visitDefTag(self, node):
if node.is_root() and not node.is_anonymous:
self._check_name_exists(self.topleveldefs, node)
elif node is not self.node:
self._check_name_exists(self.closuredefs, node)
for ident in node.undeclared_identifiers():
if ident != 'context' and ident not in self.declared.union(self.locally_declared):
self.undeclared.add(ident)
# visit defs only one level deep
if node is self.node:
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
def visitBlockTag(self, node):
if node is not self.node and \
not node.is_anonymous:
if isinstance(self.node, parsetree.DefTag):
raise exceptions.CompileException(
"Named block '%s' not allowed inside of def '%s'"
% (node.name, self.node.name), **node.exception_kwargs)
elif isinstance(self.node, (parsetree.CallTag, parsetree.CallNamespaceTag)):
raise exceptions.CompileException(
"Named block '%s' not allowed inside of <%%call> tag"
% (node.name, ), **node.exception_kwargs)
if not node.is_anonymous:
self._check_name_exists(self.topleveldefs, node)
self.undeclared.add(node.funcname)
elif node is not self.node:
self._check_name_exists(self.closuredefs, node)
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
def visitIncludeTag(self, node):
self.check_declared(node)
def visitPageTag(self, node):
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
self.check_declared(node)
def visitCallNamespaceTag(self, node):
self.visitCallTag(node)
def visitCallTag(self, node):
if node is self.node:
for ident in node.undeclared_identifiers():
if ident != 'context' and ident not in self.declared.union(self.locally_declared):
self.undeclared.add(ident)
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
else:
for ident in node.undeclared_identifiers():
if ident != 'context' and ident not in self.declared.union(self.locally_declared):
self.undeclared.add(ident)
| [
[
8,
0,
0.0067,
0.001,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0086,
0.001,
0,
0.66,
0.1111,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0095,
0.001,
0,
0.66,
... | [
"\"\"\"provides functionality for rendering a parsetree constructing into module source code.\"\"\"",
"import time",
"import re",
"from mako.pygen import PythonPrinter",
"from mako import util, ast, parsetree, filters, exceptions",
"MAGIC_NUMBER = 6",
"def compile(node, \n uri, \n ... |
# mako/ast.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST nodes"""
from mako import exceptions, pyparser, util
import re
class PythonCode(object):
"""represents information about a string containing Python code"""
def __init__(self, code, **exception_kwargs):
self.code = code
# represents all identifiers which are assigned to at some point in the code
self.declared_identifiers = set()
# represents all identifiers which are referenced before their assignment, if any
self.undeclared_identifiers = set()
# note that an identifier can be in both the undeclared and declared lists.
# using AST to parse instead of using code.co_varnames,
# code.co_names has several advantages:
# - we can locate an identifier as "undeclared" even if
# its declared later in the same block of code
# - AST is less likely to break with version changes
# (for example, the behavior of co_names changed a little bit
# in python version 2.5)
if isinstance(code, basestring):
expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
else:
expr = code
f = pyparser.FindIdentifiers(self, **exception_kwargs)
f.visit(expr)
class ArgumentList(object):
"""parses a fragment of code as a comma-separated list of expressions"""
def __init__(self, code, **exception_kwargs):
self.codeargs = []
self.args = []
self.declared_identifiers = set()
self.undeclared_identifiers = set()
if isinstance(code, basestring):
if re.match(r"\S", code) and not re.match(r",\s*$", code):
# if theres text and no trailing comma, insure its parsed
# as a tuple by adding a trailing comma
code += ","
expr = pyparser.parse(code, "exec", **exception_kwargs)
else:
expr = code
f = pyparser.FindTuple(self, PythonCode, **exception_kwargs)
f.visit(expr)
class PythonFragment(PythonCode):
"""extends PythonCode to provide identifier lookups in partial control statements
e.g.
for x in 5:
elif y==9:
except (MyException, e):
etc.
"""
def __init__(self, code, **exception_kwargs):
m = re.match(r'^(\w+)(?:\s+(.*?))?:\s*(#|$)', code.strip(), re.S)
if not m:
raise exceptions.CompileException(
"Fragment '%s' is not a partial control statement" %
code, **exception_kwargs)
if m.group(3):
code = code[:m.start(3)]
(keyword, expr) = m.group(1,2)
if keyword in ['for','if', 'while']:
code = code + "pass"
elif keyword == 'try':
code = code + "pass\nexcept:pass"
elif keyword == 'elif' or keyword == 'else':
code = "if False:pass\n" + code + "pass"
elif keyword == 'except':
code = "try:pass\n" + code + "pass"
else:
raise exceptions.CompileException(
"Unsupported control keyword: '%s'" %
keyword, **exception_kwargs)
super(PythonFragment, self).__init__(code, **exception_kwargs)
class FunctionDecl(object):
"""function declaration"""
def __init__(self, code, allow_kwargs=True, **exception_kwargs):
self.code = code
expr = pyparser.parse(code, "exec", **exception_kwargs)
f = pyparser.ParseFunc(self, **exception_kwargs)
f.visit(expr)
if not hasattr(self, 'funcname'):
raise exceptions.CompileException(
"Code '%s' is not a function declaration" % code,
**exception_kwargs)
if not allow_kwargs and self.kwargs:
raise exceptions.CompileException(
"'**%s' keyword argument not allowed here" %
self.argnames[-1], **exception_kwargs)
def get_argument_expressions(self, include_defaults=True):
"""return the argument declarations of this FunctionDecl as a printable list."""
namedecls = []
defaults = [d for d in self.defaults]
kwargs = self.kwargs
varargs = self.varargs
argnames = [f for f in self.argnames]
argnames.reverse()
for arg in argnames:
default = None
if kwargs:
arg = "**" + arg
kwargs = False
elif varargs:
arg = "*" + arg
varargs = False
else:
default = len(defaults) and defaults.pop() or None
if include_defaults and default:
namedecls.insert(0, "%s=%s" %
(arg,
pyparser.ExpressionGenerator(default).value()
)
)
else:
namedecls.insert(0, arg)
return namedecls
class FunctionArgs(FunctionDecl):
"""the argument portion of a function declaration"""
def __init__(self, code, **kwargs):
super(FunctionArgs, self).__init__("def ANON(%s):pass" % code, **kwargs)
| [
[
8,
0,
0.0524,
0.014,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0699,
0.007,
0,
0.66,
0.1429,
682,
0,
3,
0,
0,
682,
0,
0
],
[
1,
0,
0.0769,
0.007,
0,
0.66,
... | [
"\"\"\"utilities for analyzing expressions and blocks of Python \ncode, as well as generating Python from AST nodes\"\"\"",
"from mako import exceptions, pyparser, util",
"import re",
"class PythonCode(object):\n \"\"\"represents information about a string containing Python code\"\"\"\n def __init__(sel... |
# mako/exceptions.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""exception classes"""
import traceback, sys, re
from mako import util
class MakoException(Exception):
pass
class RuntimeException(MakoException):
pass
def _format_filepos(lineno, pos, filename):
if filename is None:
return " at line: %d char: %d" % (lineno, pos)
else:
return " in file '%s' at line: %d char: %d" % (filename, lineno, pos)
class CompileException(MakoException):
def __init__(self, message, source, lineno, pos, filename):
MakoException.__init__(self, message + _format_filepos(lineno, pos, filename))
self.lineno =lineno
self.pos = pos
self.filename = filename
self.source = source
class SyntaxException(MakoException):
def __init__(self, message, source, lineno, pos, filename):
MakoException.__init__(self, message + _format_filepos(lineno, pos, filename))
self.lineno =lineno
self.pos = pos
self.filename = filename
self.source = source
class UnsupportedError(MakoException):
"""raised when a retired feature is used."""
class TemplateLookupException(MakoException):
pass
class TopLevelLookupException(TemplateLookupException):
pass
class RichTraceback(object):
"""Pulls the current exception from the sys traceback and extracts
Mako-specific template information.
See the usage examples in :ref:`handling_exceptions`.
"""
def __init__(self, error=None, traceback=None):
self.source, self.lineno = "", 0
if error is None or traceback is None:
t, value, tback = sys.exc_info()
if error is None:
error = value or t
if traceback is None:
traceback = tback
self.error = error
self.records = self._init(traceback)
if isinstance(self.error, (CompileException, SyntaxException)):
import mako.template
self.source = self.error.source
self.lineno = self.error.lineno
self._has_source = True
self._init_message()
@property
def errorname(self):
return util.exception_name(self.error)
def _init_message(self):
"""Find a unicode representation of self.error"""
try:
self.message = unicode(self.error)
except UnicodeError:
try:
self.message = str(self.error)
except UnicodeEncodeError:
# Fallback to args as neither unicode nor
# str(Exception(u'\xe6')) work in Python < 2.6
self.message = self.error.args[0]
if not isinstance(self.message, unicode):
self.message = unicode(self.message, 'ascii', 'replace')
def _get_reformatted_records(self, records):
for rec in records:
if rec[6] is not None:
yield (rec[4], rec[5], rec[2], rec[6])
else:
yield tuple(rec[0:4])
@property
def traceback(self):
"""return a list of 4-tuple traceback records (i.e. normal python
format) with template-corresponding lines remapped to the originating
template.
"""
return list(self._get_reformatted_records(self.records))
@property
def reverse_records(self):
return reversed(self.records)
@property
def reverse_traceback(self):
"""return the same data as traceback, except in reverse order.
"""
return list(self._get_reformatted_records(self.reverse_records))
def _init(self, trcback):
"""format a traceback from sys.exc_info() into 7-item tuples,
containing the regular four traceback tuple items, plus the original
template filename, the line number adjusted relative to the template
source, and code line from that line number of the template."""
import mako.template
mods = {}
rawrecords = traceback.extract_tb(trcback)
new_trcback = []
for filename, lineno, function, line in rawrecords:
if not line:
line = ''
try:
(line_map, template_lines) = mods[filename]
except KeyError:
try:
info = mako.template._get_module_info(filename)
module_source = info.code
template_source = info.source
template_filename = info.template_filename or filename
except KeyError:
# A normal .py file (not a Template)
if not util.py3k:
try:
fp = open(filename, 'rb')
encoding = util.parse_encoding(fp)
fp.close()
except IOError:
encoding = None
if encoding:
line = line.decode(encoding)
else:
line = line.decode('ascii', 'replace')
new_trcback.append((filename, lineno, function, line,
None, None, None, None))
continue
template_ln = module_ln = 1
line_map = {}
for line in module_source.split("\n"):
match = re.match(r'\s*# SOURCE LINE (\d+)', line)
if match:
template_ln = int(match.group(1))
module_ln += 1
line_map[module_ln] = template_ln
template_lines = [line for line in
template_source.split("\n")]
mods[filename] = (line_map, template_lines)
template_ln = line_map[lineno]
if template_ln <= len(template_lines):
template_line = template_lines[template_ln - 1]
else:
template_line = None
new_trcback.append((filename, lineno, function,
line, template_filename, template_ln,
template_line, template_source))
if not self.source:
for l in range(len(new_trcback)-1, 0, -1):
if new_trcback[l][5]:
self.source = new_trcback[l][7]
self.lineno = new_trcback[l][5]
break
else:
if new_trcback:
try:
# A normal .py file (not a Template)
fp = open(new_trcback[-1][0], 'rb')
encoding = util.parse_encoding(fp)
fp.seek(0)
self.source = fp.read()
fp.close()
if encoding:
self.source = self.source.decode(encoding)
except IOError:
self.source = ''
self.lineno = new_trcback[-1][1]
return new_trcback
def text_error_template(lookup=None):
"""Provides a template that renders a stack trace in a similar format to
the Python interpreter, substituting source template filenames, line
numbers and code for that of the originating source template, as
applicable.
"""
import mako.template
return mako.template.Template(r"""
<%page args="error=None, traceback=None"/>
<%!
from mako.exceptions import RichTraceback
%>\
<%
tback = RichTraceback(error=error, traceback=traceback)
%>\
Traceback (most recent call last):
% for (filename, lineno, function, line) in tback.traceback:
File "${filename}", line ${lineno}, in ${function or '?'}
${line | trim}
% endfor
${tback.errorname}: ${tback.message}
""")
def html_error_template():
"""Provides a template that renders a stack trace in an HTML format,
providing an excerpt of code as well as substituting source template
filenames, line numbers and code for that of the originating source
template, as applicable.
The template's default encoding_errors value is 'htmlentityreplace'. the
template has two options. With the full option disabled, only a section of
an HTML document is returned. with the css option disabled, the default
stylesheet won't be included.
"""
import mako.template
return mako.template.Template(r"""
<%!
from mako.exceptions import RichTraceback
%>
<%page args="full=True, css=True, error=None, traceback=None"/>
% if full:
<html>
<head>
<title>Mako Runtime Error</title>
% endif
% if css:
<style>
body { font-family:verdana; margin:10px 30px 10px 30px;}
.stacktrace { margin:5px 5px 5px 5px; }
.highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
.nonhighlight { padding:0px; background-color:#DFDFDF; }
.sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; }
.sampleline { padding:0px 10px 0px 10px; }
.sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
.location { font-size:80%; }
</style>
% endif
% if full:
</head>
<body>
% endif
<h2>Error !</h2>
<%
tback = RichTraceback(error=error, traceback=traceback)
src = tback.source
line = tback.lineno
if src:
lines = src.split('\n')
else:
lines = None
%>
<h3>${tback.errorname}: ${tback.message}</h3>
% if lines:
<div class="sample">
<div class="nonhighlight">
% for index in range(max(0, line-4),min(len(lines), line+5)):
% if index + 1 == line:
<div class="highlight">${index + 1} ${lines[index] | h}</div>
% else:
<div class="sampleline">${index + 1} ${lines[index] | h}</div>
% endif
% endfor
</div>
</div>
% endif
<div class="stacktrace">
% for (filename, lineno, function, line) in tback.reverse_traceback:
<div class="location">${filename}, line ${lineno}:</div>
<div class="sourceline">${line | h}</div>
% endfor
</div>
% if full:
</body>
</html>
% endif
""", output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace')
| [
[
8,
0,
0.0228,
0.0033,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0293,
0.0033,
0,
0.66,
0.0769,
423,
0,
3,
0,
0,
423,
0,
0
],
[
1,
0,
0.0326,
0.0033,
0,
0.66... | [
"\"\"\"exception classes\"\"\"",
"import traceback, sys, re",
"from mako import util",
"class MakoException(Exception):\n pass",
"class RuntimeException(MakoException):\n pass",
"def _format_filepos(lineno, pos, filename):\n if filename is None:\n return \" at line: %d char: %d\" % (lineno... |
# mako/__init__.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '0.5.0'
| [
[
14,
0,
0.8889,
0.1111,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
]
] | [
"__version__ = '0.5.0'"
] |
# mako/template.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provides the Template class, a facade for parsing, generating and executing
template strings, as well as template runtime operations."""
from mako.lexer import Lexer
from mako import runtime, util, exceptions, codegen
import imp, os, re, shutil, stat, sys, tempfile, time, types, weakref
class Template(object):
"""Represents a compiled template.
:class:`.Template` includes a reference to the original
template source (via the ``.source`` attribute)
as well as the source code of the
generated Python module (i.e. the ``.code`` attribute),
as well as a reference to an actual Python module.
:class:`.Template` is constructed using either a literal string
representing the template text, or a filename representing a filesystem
path to a source file.
:param text: textual template source. This argument is mutually
exclusive versus the "filename" parameter.
:param filename: filename of the source template. This argument is
mutually exclusive versus the "text" parameter.
:param buffer_filters: string list of filters to be applied
to the output of %defs which are buffered, cached, or otherwise
filtered, after all filters
defined with the %def itself have been applied. Allows the
creation of default expression filters that let the output
of return-valued %defs "opt out" of that filtering via
passing special attributes or objects.
:param bytestring_passthrough: When True, and output_encoding is
set to None, and :meth:`.Template.render` is used to render,
the StringIO or cStringIO buffer will be used instead of the
default "fast" buffer. This allows raw bytestrings in the
output stream, such as in expressions, to pass straight
through to the buffer. New in 0.4 to provide the same
behavior as that of the previous series. This flag is forced
to True if disable_unicode is also configured.
:param cache_dir: Filesystem directory where cache files will be
placed. See :ref:`caching_toplevel`.
:param cache_enabled: Boolean flag which enables caching of this
template. See :ref:`caching_toplevel`.
:param cache_type: Type of Beaker caching to be applied to the
template. See :ref:`caching_toplevel`.
:param cache_url: URL of a memcached server with which to use
for caching. See :ref:`caching_toplevel`.
:param default_filters: List of string filter names that will
be applied to all expressions. See :ref:`filtering_default_filters`.
:param disable_unicode: Disables all awareness of Python Unicode
objects. See :ref:`unicode_disabled`.
:param encoding_errors: Error parameter passed to ``encode()`` when
string encoding is performed. See :ref:`usage_unicode`.
:param error_handler: Python callable which is called whenever
compile or runtime exceptions occur. The callable is passed
the current context as well as the exception. If the
callable returns ``True``, the exception is considered to
be handled, else it is re-raised after the function
completes. Is used to provide custom error-rendering
functions.
:param format_exceptions: if ``True``, exceptions which occur during
the render phase of this template will be caught and
formatted into an HTML error page, which then becomes the
rendered result of the :meth:`render` call. Otherwise,
runtime exceptions are propagated outwards.
:param imports: String list of Python statements, typically individual
"import" lines, which will be placed into the module level
preamble of all generated Python modules. See the example
in :ref:`filtering_default_filters`.
:param input_encoding: Encoding of the template's source code. Can
be used in lieu of the coding comment. See
:ref:`usage_unicode` as well as :ref:`unicode_toplevel` for
details on source encoding.
:param lookup: a :class:`.TemplateLookup` instance that will be used
for all file lookups via the ``<%namespace>``,
``<%include>``, and ``<%inherit>`` tags. See
:ref:`usage_templatelookup`.
:param module_directory: Filesystem location where generated
Python module files will be placed.
:param module_filename: Overrides the filename of the generated
Python module file. For advanced usage only.
:param output_encoding: The encoding to use when :meth:`.render`
is called.
See :ref:`usage_unicode` as well as :ref:`unicode_toplevel`.
:param preprocessor: Python callable which will be passed
the full template source before it is parsed. The return
result of the callable will be used as the template source
code.
:param strict_undefined: Replaces the automatic usage of
``UNDEFINED`` for any undeclared variables not located in
the :class:`.Context` with an immediate raise of
``NameError``. The advantage is immediate reporting of
missing variables which include the name. New in 0.3.6.
:param uri: string uri or other identifier for this template.
If not provided, the uri is generated from the filesystem
path, or from the in-memory identity of a non-file-based
template. The primary usage of the uri is to provide a key
within :class:`.TemplateLookup`, as well as to generate the
file path of the generated Python module file, if
``module_directory`` is specified.
"""
def __init__(self,
text=None,
filename=None,
uri=None,
format_exceptions=False,
error_handler=None,
lookup=None,
output_encoding=None,
encoding_errors='strict',
module_directory=None,
cache_type=None,
cache_dir=None,
cache_url=None,
module_filename=None,
input_encoding=None,
disable_unicode=False,
bytestring_passthrough=False,
default_filters=None,
buffer_filters=(),
strict_undefined=False,
imports=None,
preprocessor=None,
cache_enabled=True):
if uri:
self.module_id = re.sub(r'\W', "_", uri)
self.uri = uri
elif filename:
self.module_id = re.sub(r'\W', "_", filename)
drive, path = os.path.splitdrive(filename)
path = os.path.normpath(path).replace(os.path.sep, "/")
self.uri = path
else:
self.module_id = "memory:" + hex(id(self))
self.uri = self.module_id
u_norm = self.uri
if u_norm.startswith("/"):
u_norm = u_norm[1:]
u_norm = os.path.normpath(u_norm)
if u_norm.startswith(".."):
raise exceptions.TemplateLookupException(
"Template uri \"%s\" is invalid - "
"it cannot be relative outside "
"of the root path." % self.uri)
self.input_encoding = input_encoding
self.output_encoding = output_encoding
self.encoding_errors = encoding_errors
self.disable_unicode = disable_unicode
self.bytestring_passthrough = bytestring_passthrough or disable_unicode
self.strict_undefined = strict_undefined
if util.py3k and disable_unicode:
raise exceptions.UnsupportedError(
"Mako for Python 3 does not "
"support disabling Unicode")
elif output_encoding and disable_unicode:
raise exceptions.UnsupportedError(
"output_encoding must be set to "
"None when disable_unicode is used.")
if default_filters is None:
if util.py3k or self.disable_unicode:
self.default_filters = ['str']
else:
self.default_filters = ['unicode']
else:
self.default_filters = default_filters
self.buffer_filters = buffer_filters
self.imports = imports
self.preprocessor = preprocessor
# if plain text, compile code in memory only
if text is not None:
(code, module) = _compile_text(self, text, filename)
self._code = code
self._source = text
ModuleInfo(module, None, self, filename, code, text)
elif filename is not None:
# if template filename and a module directory, load
# a filesystem-based module file, generating if needed
if module_filename is not None:
path = module_filename
elif module_directory is not None:
path = os.path.abspath(
os.path.join(
os.path.normpath(module_directory),
u_norm + ".py"
)
)
else:
path = None
module = self._compile_from_file(path, filename)
else:
raise exceptions.RuntimeException(
"Template requires text or filename")
self.module = module
self.filename = filename
self.callable_ = self.module.render_body
self.format_exceptions = format_exceptions
self.error_handler = error_handler
self.lookup = lookup
self.cache_type = cache_type
self.cache_dir = cache_dir
self.cache_url = cache_url
self.cache_enabled = cache_enabled
def _compile_from_file(self, path, filename):
if path is not None:
util.verify_directory(os.path.dirname(path))
filemtime = os.stat(filename)[stat.ST_MTIME]
if not os.path.exists(path) or \
os.stat(path)[stat.ST_MTIME] < filemtime:
_compile_module_file(
self,
open(filename, 'rb').read(),
filename,
path)
module = imp.load_source(self.module_id, path, open(path, 'rb'))
del sys.modules[self.module_id]
if module._magic_number != codegen.MAGIC_NUMBER:
_compile_module_file(
self,
open(filename, 'rb').read(),
filename,
path)
module = imp.load_source(self.module_id, path, open(path, 'rb'))
del sys.modules[self.module_id]
ModuleInfo(module, path, self, filename, None, None)
else:
# template filename and no module directory, compile code
# in memory
code, module = _compile_text(
self,
open(filename, 'rb').read(),
filename)
self._source = None
self._code = code
ModuleInfo(module, None, self, filename, code, None)
return module
@property
def source(self):
"""return the template source code for this Template."""
return _get_module_info_from_callable(self.callable_).source
@property
def code(self):
"""return the module source code for this Template"""
return _get_module_info_from_callable(self.callable_).code
@property
def cache(self):
return self.module._template_cache
def render(self, *args, **data):
"""Render the output of this template as a string.
if the template specifies an output encoding, the string
will be encoded accordingly, else the output is raw (raw
output uses cStringIO and can't handle multibyte
characters). a Context object is created corresponding
to the given data. Arguments that are explictly declared
by this template's internal rendering method are also
pulled from the given \*args, \**data members.
"""
return runtime._render(self, self.callable_, args, data)
def render_unicode(self, *args, **data):
"""render the output of this template as a unicode object."""
return runtime._render(self,
self.callable_,
args,
data,
as_unicode=True)
def render_context(self, context, *args, **kwargs):
"""Render this Template with the given context.
the data is written to the context's buffer.
"""
if getattr(context, '_with_template', None) is None:
context._with_template = self
runtime._render_context(self,
self.callable_,
context,
*args,
**kwargs)
def has_def(self, name):
return hasattr(self.module, "render_%s" % name)
def get_def(self, name):
"""Return a def of this template as a :class:`.DefTemplate`."""
return DefTemplate(self, getattr(self.module, "render_%s" % name))
def _get_def_callable(self, name):
return getattr(self.module, "render_%s" % name)
@property
def last_modified(self):
return self.module._modified_time
class ModuleTemplate(Template):
"""A Template which is constructed given an existing Python module.
e.g.::
t = Template("this is a template")
f = file("mymodule.py", "w")
f.write(t.code)
f.close()
import mymodule
t = ModuleTemplate(mymodule)
print t.render()
"""
def __init__(self, module,
module_filename=None,
template=None,
template_filename=None,
module_source=None,
template_source=None,
output_encoding=None,
encoding_errors='strict',
disable_unicode=False,
bytestring_passthrough=False,
format_exceptions=False,
error_handler=None,
lookup=None,
cache_type=None,
cache_dir=None,
cache_url=None,
cache_enabled=True
):
self.module_id = re.sub(r'\W', "_", module._template_uri)
self.uri = module._template_uri
self.input_encoding = module._source_encoding
self.output_encoding = output_encoding
self.encoding_errors = encoding_errors
self.disable_unicode = disable_unicode
self.bytestring_passthrough = bytestring_passthrough or disable_unicode
if util.py3k and disable_unicode:
raise exceptions.UnsupportedError(
"Mako for Python 3 does not "
"support disabling Unicode")
elif output_encoding and disable_unicode:
raise exceptions.UnsupportedError(
"output_encoding must be set to "
"None when disable_unicode is used.")
self.module = module
self.filename = template_filename
ModuleInfo(module,
module_filename,
self,
template_filename,
module_source,
template_source)
self.callable_ = self.module.render_body
self.format_exceptions = format_exceptions
self.error_handler = error_handler
self.lookup = lookup
self.cache_type = cache_type
self.cache_dir = cache_dir
self.cache_url = cache_url
self.cache_enabled = cache_enabled
class DefTemplate(Template):
"""a Template which represents a callable def in a parent
template."""
def __init__(self, parent, callable_):
self.parent = parent
self.callable_ = callable_
self.output_encoding = parent.output_encoding
self.module = parent.module
self.encoding_errors = parent.encoding_errors
self.format_exceptions = parent.format_exceptions
self.error_handler = parent.error_handler
self.lookup = parent.lookup
self.bytestring_passthrough = parent.bytestring_passthrough
def get_def(self, name):
return self.parent.get_def(name)
class ModuleInfo(object):
"""Stores information about a module currently loaded into
memory, provides reverse lookups of template source, module
source code based on a module's identifier.
"""
_modules = weakref.WeakValueDictionary()
def __init__(self,
module,
module_filename,
template,
template_filename,
module_source,
template_source):
self.module = module
self.module_filename = module_filename
self.template_filename = template_filename
self.module_source = module_source
self.template_source = template_source
self._modules[module.__name__] = template._mmarker = self
if module_filename:
self._modules[module_filename] = self
@property
def code(self):
if self.module_source is not None:
return self.module_source
else:
return open(self.module_filename).read()
@property
def source(self):
if self.template_source is not None:
if self.module._source_encoding and \
not isinstance(self.template_source, unicode):
return self.template_source.decode(
self.module._source_encoding)
else:
return self.template_source
else:
if self.module._source_encoding:
return open(self.template_filename, 'rb').read().\
decode(self.module._source_encoding)
else:
return open(self.template_filename).read()
def _compile_text(template, text, filename):
identifier = template.module_id
lexer = Lexer(text,
filename,
disable_unicode=template.disable_unicode,
input_encoding=template.input_encoding,
preprocessor=template.preprocessor)
node = lexer.parse()
source = codegen.compile(node,
template.uri,
filename,
default_filters=template.default_filters,
buffer_filters=template.buffer_filters,
imports=template.imports,
source_encoding=lexer.encoding,
generate_magic_comment=template.disable_unicode,
disable_unicode=template.disable_unicode,
strict_undefined=template.strict_undefined)
cid = identifier
if not util.py3k and isinstance(cid, unicode):
cid = cid.encode()
module = types.ModuleType(cid)
code = compile(source, cid, 'exec')
exec code in module.__dict__, module.__dict__
return (source, module)
def _compile_module_file(template, text, filename, outputpath):
identifier = template.module_id
lexer = Lexer(text,
filename,
disable_unicode=template.disable_unicode,
input_encoding=template.input_encoding,
preprocessor=template.preprocessor)
node = lexer.parse()
source = codegen.compile(node,
template.uri,
filename,
default_filters=template.default_filters,
buffer_filters=template.buffer_filters,
imports=template.imports,
source_encoding=lexer.encoding,
generate_magic_comment=True,
disable_unicode=template.disable_unicode,
strict_undefined=template.strict_undefined)
# make tempfiles in the same location as the ultimate
# location. this ensures they're on the same filesystem,
# avoiding synchronization issues.
(dest, name) = tempfile.mkstemp(dir=os.path.dirname(outputpath))
if isinstance(source, unicode):
source = source.encode(lexer.encoding or 'ascii')
os.write(dest, source)
os.close(dest)
shutil.move(name, outputpath)
def _get_module_info_from_callable(callable_):
return _get_module_info(callable_.func_globals['__name__'])
def _get_module_info(filename):
return ModuleInfo._modules[filename]
| [
[
8,
0,
0.0138,
0.0037,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0185,
0.0018,
0,
0.66,
0.0909,
824,
0,
1,
0,
0,
824,
0,
0
],
[
1,
0,
0.0203,
0.0018,
0,
0.66... | [
"\"\"\"Provides the Template class, a facade for parsing, generating and executing\ntemplate strings, as well as template runtime operations.\"\"\"",
"from mako.lexer import Lexer",
"from mako import runtime, util, exceptions, codegen",
"import imp, os, re, shutil, stat, sys, tempfile, time, types, weakref",
... |
# mako/filters.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re, urllib, htmlentitydefs, codecs
from StringIO import StringIO
from mako import util
xml_escapes = {
'&' : '&',
'>' : '>',
'<' : '<',
'"' : '"', # also " in html-only
"'" : ''' # also ' in html-only
}
# XXX: " is valid in HTML and XML
# ' is not valid HTML, but is valid XML
def legacy_html_escape(string):
"""legacy HTML escape for non-unicode mode."""
return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string)
try:
import markupsafe
html_escape = markupsafe.escape
except ImportError:
html_escape = legacy_html_escape
def xml_escape(string):
return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string)
def url_escape(string):
# convert into a list of octets
string = string.encode("utf8")
return urllib.quote_plus(string)
def url_unescape(string):
text = urllib.unquote_plus(string)
if not is_ascii_str(text):
text = text.decode("utf8")
return text
def trim(string):
return string.strip()
class Decode(object):
def __getattr__(self, key):
def decode(x):
if isinstance(x, unicode):
return x
elif not isinstance(x, str):
return unicode(str(x), encoding=key)
else:
return unicode(x, encoding=key)
return decode
decode = Decode()
_ASCII_re = re.compile(r'\A[\x00-\x7f]*\Z')
def is_ascii_str(text):
return isinstance(text, str) and _ASCII_re.match(text)
################################################################
class XMLEntityEscaper(object):
def __init__(self, codepoint2name, name2codepoint):
self.codepoint2entity = dict([(c, u'&%s;' % n)
for c,n in codepoint2name.iteritems()])
self.name2codepoint = name2codepoint
def escape_entities(self, text):
"""Replace characters with their character entity references.
Only characters corresponding to a named entity are replaced.
"""
return unicode(text).translate(self.codepoint2entity)
def __escape(self, m):
codepoint = ord(m.group())
try:
return self.codepoint2entity[codepoint]
except (KeyError, IndexError):
return '&#x%X;' % codepoint
__escapable = re.compile(r'["&<>]|[^\x00-\x7f]')
def escape(self, text):
"""Replace characters with their character references.
Replace characters by their named entity references.
Non-ASCII characters, if they do not have a named entity reference,
are replaced by numerical character references.
The return value is guaranteed to be ASCII.
"""
return self.__escapable.sub(self.__escape, unicode(text)
).encode('ascii')
# XXX: This regexp will not match all valid XML entity names__.
# (It punts on details involving involving CombiningChars and Extenders.)
#
# .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef
__characterrefs = re.compile(r'''& (?:
\#(\d+)
| \#x([\da-f]+)
| ( (?!\d) [:\w] [-.:\w]+ )
) ;''',
re.X | re.UNICODE)
def __unescape(self, m):
dval, hval, name = m.groups()
if dval:
codepoint = int(dval)
elif hval:
codepoint = int(hval, 16)
else:
codepoint = self.name2codepoint.get(name, 0xfffd)
# U+FFFD = "REPLACEMENT CHARACTER"
if codepoint < 128:
return chr(codepoint)
return unichr(codepoint)
def unescape(self, text):
"""Unescape character references.
All character references (both entity references and numerical
character references) are unescaped.
"""
return self.__characterrefs.sub(self.__unescape, text)
_html_entities_escaper = XMLEntityEscaper(htmlentitydefs.codepoint2name,
htmlentitydefs.name2codepoint)
html_entities_escape = _html_entities_escaper.escape_entities
html_entities_unescape = _html_entities_escaper.unescape
def htmlentityreplace_errors(ex):
"""An encoding error handler.
This python `codecs`_ error handler replaces unencodable
characters with HTML entities, or, if no HTML entity exists for
the character, XML character references.
>>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace')
'The cost was €12.'
"""
if isinstance(ex, UnicodeEncodeError):
# Handle encoding errors
bad_text = ex.object[ex.start:ex.end]
text = _html_entities_escaper.escape(bad_text)
return (unicode(text), ex.end)
raise ex
codecs.register_error('htmlentityreplace', htmlentityreplace_errors)
# TODO: options to make this dynamic per-compilation will be added in a later release
DEFAULT_ESCAPES = {
'x':'filters.xml_escape',
'h':'filters.html_escape',
'u':'filters.url_escape',
'trim':'filters.trim',
'entity':'filters.html_entities_escape',
'unicode':'unicode',
'decode':'decode',
'str':'str',
'n':'n'
}
if util.py3k:
DEFAULT_ESCAPES.update({
'unicode':'str'
})
NON_UNICODE_ESCAPES = DEFAULT_ESCAPES.copy()
NON_UNICODE_ESCAPES['h'] = 'filters.legacy_html_escape'
| [
[
1,
0,
0.0426,
0.0053,
0,
0.66,
0,
540,
0,
4,
0,
0,
540,
0,
0
],
[
1,
0,
0.0479,
0.0053,
0,
0.66,
0.0435,
609,
0,
1,
0,
0,
609,
0,
0
],
[
1,
0,
0.0532,
0.0053,
0,
... | [
"import re, urllib, htmlentitydefs, codecs",
"from StringIO import StringIO",
"from mako import util",
"xml_escapes = {\n '&' : '&',\n '>' : '>', \n '<' : '<', \n '\"' : '"', # also " in html-only\n \"'\" : ''' # also ' in html-only \n}",
"def legacy_html_esca... |
# mako/_ast_util.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
ast
~~~
The `ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with
each Python release; this module helps to find out programmatically what
the current grammar looks like and allows modifications of it.
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
a flag to the `compile()` builtin function or by using the `parse()`
function from this module. The result will be a tree of objects whose
classes all inherit from `ast.AST`.
A modified abstract syntax tree can be compiled into a Python code object
using the built-in `compile()` function.
Additionally various helper functions are provided that make working with
the trees simpler. The main intention of the helper functions and this
module in general is to provide an easy to use interface for libraries
that work tightly with the python syntax (template engines for example).
:copyright: Copyright 2008 by Armin Ronacher.
:license: Python License.
"""
from _ast import *
BOOLOP_SYMBOLS = {
And: 'and',
Or: 'or'
}
BINOP_SYMBOLS = {
Add: '+',
Sub: '-',
Mult: '*',
Div: '/',
FloorDiv: '//',
Mod: '%',
LShift: '<<',
RShift: '>>',
BitOr: '|',
BitAnd: '&',
BitXor: '^'
}
CMPOP_SYMBOLS = {
Eq: '==',
Gt: '>',
GtE: '>=',
In: 'in',
Is: 'is',
IsNot: 'is not',
Lt: '<',
LtE: '<=',
NotEq: '!=',
NotIn: 'not in'
}
UNARYOP_SYMBOLS = {
Invert: '~',
Not: 'not',
UAdd: '+',
USub: '-'
}
ALL_SYMBOLS = {}
ALL_SYMBOLS.update(BOOLOP_SYMBOLS)
ALL_SYMBOLS.update(BINOP_SYMBOLS)
ALL_SYMBOLS.update(CMPOP_SYMBOLS)
ALL_SYMBOLS.update(UNARYOP_SYMBOLS)
def parse(expr, filename='<unknown>', mode='exec'):
"""Parse an expression into an AST node."""
return compile(expr, filename, mode, PyCF_ONLY_AST)
def to_source(node, indent_with=' ' * 4):
"""
This function can convert a node tree back into python sourcecode. This
is useful for debugging purposes, especially if you're dealing with custom
asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is not
compilable / evaluable. The reason for this is that the AST contains some
more data than regular sourcecode does, which is dropped during
conversion.
Each level of indentation is replaced with `indent_with`. Per default this
parameter is equal to four spaces as suggested by PEP 8, but it might be
adjusted to match the application's styleguide.
"""
generator = SourceGenerator(indent_with)
generator.visit(node)
return ''.join(generator.result)
def dump(node):
"""
A very verbose representation of the node passed. This is useful for
debugging purposes.
"""
def _format(node):
if isinstance(node, AST):
return '%s(%s)' % (node.__class__.__name__,
', '.join('%s=%s' % (a, _format(b))
for a, b in iter_fields(node)))
elif isinstance(node, list):
return '[%s]' % ', '.join(_format(x) for x in node)
return repr(node)
if not isinstance(node, AST):
raise TypeError('expected AST, got %r' % node.__class__.__name__)
return _format(node)
def copy_location(new_node, old_node):
"""
Copy the source location hint (`lineno` and `col_offset`) from the
old to the new node if possible and return the new one.
"""
for attr in 'lineno', 'col_offset':
if attr in old_node._attributes and attr in new_node._attributes \
and hasattr(old_node, attr):
setattr(new_node, attr, getattr(old_node, attr))
return new_node
def fix_missing_locations(node):
"""
Some nodes require a line number and the column offset. Without that
information the compiler will abort the compilation. Because it can be
a dull task to add appropriate line numbers and column offsets when
adding new nodes this function can help. It copies the line number and
column offset of the parent node to the child nodes without this
information.
Unlike `copy_location` this works recursive and won't touch nodes that
already have a location information.
"""
def _fix(node, lineno, col_offset):
if 'lineno' in node._attributes:
if not hasattr(node, 'lineno'):
node.lineno = lineno
else:
lineno = node.lineno
if 'col_offset' in node._attributes:
if not hasattr(node, 'col_offset'):
node.col_offset = col_offset
else:
col_offset = node.col_offset
for child in iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, 1, 0)
return node
def increment_lineno(node, n=1):
"""
Increment the line numbers of all nodes by `n` if they have line number
attributes. This is useful to "move code" to a different location in a
file.
"""
for node in zip((node,), walk(node)):
if 'lineno' in node._attributes:
node.lineno = getattr(node, 'lineno', 0) + n
def iter_fields(node):
"""Iterate over all fields of a node, only yielding existing fields."""
# CPython 2.5 compat
if not hasattr(node, '_fields') or not node._fields:
return
for field in node._fields:
try:
yield field, getattr(node, field)
except AttributeError:
pass
def get_fields(node):
"""Like `iter_fiels` but returns a dict."""
return dict(iter_fields(node))
def iter_child_nodes(node):
"""Iterate over all child nodes or a node."""
for name, field in iter_fields(node):
if isinstance(field, AST):
yield field
elif isinstance(field, list):
for item in field:
if isinstance(item, AST):
yield item
def get_child_nodes(node):
"""Like `iter_child_nodes` but returns a list."""
return list(iter_child_nodes(node))
def get_compile_mode(node):
"""
Get the mode for `compile` of a given node. If the node is not a `mod`
node (`Expression`, `Module` etc.) a `TypeError` is thrown.
"""
if not isinstance(node, mod):
raise TypeError('expected mod node, got %r' % node.__class__.__name__)
return {
Expression: 'eval',
Interactive: 'single'
}.get(node.__class__, 'expr')
def get_docstring(node):
"""
Return the docstring for the given node or `None` if no docstring can be
found. If the node provided does not accept docstrings a `TypeError`
will be raised.
"""
if not isinstance(node, (FunctionDef, ClassDef, Module)):
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
if node.body and isinstance(node.body[0], Str):
return node.body[0].s
def walk(node):
"""
Iterate over all nodes. This is useful if you only want to modify nodes in
place and don't care about the context or the order the nodes are returned.
"""
from collections import deque
todo = deque([node])
while todo:
node = todo.popleft()
todo.extend(iter_child_nodes(node))
yield node
class NodeVisitor(object):
"""
Walks the abstract syntax tree and call visitor functions for every node
found. The visitor functions may return values which will be forwarded
by the `visit` method.
Per default the visitor functions for the nodes are ``'visit_'`` +
class name of the node. So a `TryFinally` node visit function would
be `visit_TryFinally`. This behavior can be changed by overriding
the `get_visitor` function. If no visitor function exists for a node
(return value `None`) the `generic_visit` visitor is used instead.
Don't use the `NodeVisitor` if you want to apply changes to nodes during
traversing. For this a special visitor exists (`NodeTransformer`) that
allows modifications.
"""
def get_visitor(self, node):
"""
Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None)
def visit(self, node):
"""Visit a node."""
f = self.get_visitor(node)
if f is not None:
return f(node)
return self.generic_visit(node)
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for field, value in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
class NodeTransformer(NodeVisitor):
"""
Walks the abstract syntax tree and allows modifications of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor functions to replace or remove the old node. If the return
value of the visitor function is `None` the node will be removed
from the previous location otherwise it's replaced with the return
value. The return value may be the original node in which case no
replacement takes place.
Here an example transformer that rewrites all `foo` to `data['foo']`::
class RewriteName(NodeTransformer):
def visit_Name(self, node):
return copy_location(Subscript(
value=Name(id='data', ctx=Load()),
slice=Index(value=Str(s=node.id)),
ctx=node.ctx
), node)
Keep in mind that if the node you're operating on has child nodes
you must either transform the child nodes yourself or call the generic
visit function for the node first.
Nodes that were part of a collection of statements (that applies to
all statement nodes) may also return a list of nodes rather than just
a single node.
Usually you use the transformer like this::
node = YourTransformer().visit(node)
"""
def generic_visit(self, node):
for field, old_value in iter_fields(node):
old_value = getattr(node, field, None)
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, AST):
value = self.visit(value)
if value is None:
continue
elif not isinstance(value, AST):
new_values.extend(value)
continue
new_values.append(value)
old_value[:] = new_values
elif isinstance(old_value, AST):
new_node = self.visit(old_value)
if new_node is None:
delattr(node, field)
else:
setattr(node, field, new_node)
return node
class SourceGenerator(NodeVisitor):
"""
This visitor is able to transform a well formed syntax tree into python
sourcecode. For more details have a look at the docstring of the
`node_to_source` function.
"""
def __init__(self, indent_with):
self.result = []
self.indent_with = indent_with
self.indentation = 0
self.new_lines = 0
def write(self, x):
if self.new_lines:
if self.result:
self.result.append('\n' * self.new_lines)
self.result.append(self.indent_with * self.indentation)
self.new_lines = 0
self.result.append(x)
def newline(self, n=1):
self.new_lines = max(self.new_lines, n)
def body(self, statements):
self.new_line = True
self.indentation += 1
for stmt in statements:
self.visit(stmt)
self.indentation -= 1
def body_or_else(self, node):
self.body(node.body)
if node.orelse:
self.newline()
self.write('else:')
self.body(node.orelse)
def signature(self, node):
want_comma = []
def write_comma():
if want_comma:
self.write(', ')
else:
want_comma.append(True)
padding = [None] * (len(node.args) - len(node.defaults))
for arg, default in zip(node.args, padding + node.defaults):
write_comma()
self.visit(arg)
if default is not None:
self.write('=')
self.visit(default)
if node.vararg is not None:
write_comma()
self.write('*' + node.vararg)
if node.kwarg is not None:
write_comma()
self.write('**' + node.kwarg)
def decorators(self, node):
for decorator in node.decorator_list:
self.newline()
self.write('@')
self.visit(decorator)
# Statements
def visit_Assign(self, node):
self.newline()
for idx, target in enumerate(node.targets):
if idx:
self.write(', ')
self.visit(target)
self.write(' = ')
self.visit(node.value)
def visit_AugAssign(self, node):
self.newline()
self.visit(node.target)
self.write(BINOP_SYMBOLS[type(node.op)] + '=')
self.visit(node.value)
def visit_ImportFrom(self, node):
self.newline()
self.write('from %s%s import ' % ('.' * node.level, node.module))
for idx, item in enumerate(node.names):
if idx:
self.write(', ')
self.write(item)
def visit_Import(self, node):
self.newline()
for item in node.names:
self.write('import ')
self.visit(item)
def visit_Expr(self, node):
self.newline()
self.generic_visit(node)
def visit_FunctionDef(self, node):
self.newline(n=2)
self.decorators(node)
self.newline()
self.write('def %s(' % node.name)
self.signature(node.args)
self.write('):')
self.body(node.body)
def visit_ClassDef(self, node):
have_args = []
def paren_or_comma():
if have_args:
self.write(', ')
else:
have_args.append(True)
self.write('(')
self.newline(n=3)
self.decorators(node)
self.newline()
self.write('class %s' % node.name)
for base in node.bases:
paren_or_comma()
self.visit(base)
# XXX: the if here is used to keep this module compatible
# with python 2.6.
if hasattr(node, 'keywords'):
for keyword in node.keywords:
paren_or_comma()
self.write(keyword.arg + '=')
self.visit(keyword.value)
if node.starargs is not None:
paren_or_comma()
self.write('*')
self.visit(node.starargs)
if node.kwargs is not None:
paren_or_comma()
self.write('**')
self.visit(node.kwargs)
self.write(have_args and '):' or ':')
self.body(node.body)
def visit_If(self, node):
self.newline()
self.write('if ')
self.visit(node.test)
self.write(':')
self.body(node.body)
while True:
else_ = node.orelse
if len(else_) == 1 and isinstance(else_[0], If):
node = else_[0]
self.newline()
self.write('elif ')
self.visit(node.test)
self.write(':')
self.body(node.body)
else:
self.newline()
self.write('else:')
self.body(else_)
break
def visit_For(self, node):
self.newline()
self.write('for ')
self.visit(node.target)
self.write(' in ')
self.visit(node.iter)
self.write(':')
self.body_or_else(node)
def visit_While(self, node):
self.newline()
self.write('while ')
self.visit(node.test)
self.write(':')
self.body_or_else(node)
def visit_With(self, node):
self.newline()
self.write('with ')
self.visit(node.context_expr)
if node.optional_vars is not None:
self.write(' as ')
self.visit(node.optional_vars)
self.write(':')
self.body(node.body)
def visit_Pass(self, node):
self.newline()
self.write('pass')
def visit_Print(self, node):
# XXX: python 2.6 only
self.newline()
self.write('print ')
want_comma = False
if node.dest is not None:
self.write(' >> ')
self.visit(node.dest)
want_comma = True
for value in node.values:
if want_comma:
self.write(', ')
self.visit(value)
want_comma = True
if not node.nl:
self.write(',')
def visit_Delete(self, node):
self.newline()
self.write('del ')
for idx, target in enumerate(node):
if idx:
self.write(', ')
self.visit(target)
def visit_TryExcept(self, node):
self.newline()
self.write('try:')
self.body(node.body)
for handler in node.handlers:
self.visit(handler)
def visit_TryFinally(self, node):
self.newline()
self.write('try:')
self.body(node.body)
self.newline()
self.write('finally:')
self.body(node.finalbody)
def visit_Global(self, node):
self.newline()
self.write('global ' + ', '.join(node.names))
def visit_Nonlocal(self, node):
self.newline()
self.write('nonlocal ' + ', '.join(node.names))
def visit_Return(self, node):
self.newline()
self.write('return ')
self.visit(node.value)
def visit_Break(self, node):
self.newline()
self.write('break')
def visit_Continue(self, node):
self.newline()
self.write('continue')
def visit_Raise(self, node):
# XXX: Python 2.6 / 3.0 compatibility
self.newline()
self.write('raise')
if hasattr(node, 'exc') and node.exc is not None:
self.write(' ')
self.visit(node.exc)
if node.cause is not None:
self.write(' from ')
self.visit(node.cause)
elif hasattr(node, 'type') and node.type is not None:
self.visit(node.type)
if node.inst is not None:
self.write(', ')
self.visit(node.inst)
if node.tback is not None:
self.write(', ')
self.visit(node.tback)
# Expressions
def visit_Attribute(self, node):
self.visit(node.value)
self.write('.' + node.attr)
def visit_Call(self, node):
want_comma = []
def write_comma():
if want_comma:
self.write(', ')
else:
want_comma.append(True)
self.visit(node.func)
self.write('(')
for arg in node.args:
write_comma()
self.visit(arg)
for keyword in node.keywords:
write_comma()
self.write(keyword.arg + '=')
self.visit(keyword.value)
if node.starargs is not None:
write_comma()
self.write('*')
self.visit(node.starargs)
if node.kwargs is not None:
write_comma()
self.write('**')
self.visit(node.kwargs)
self.write(')')
def visit_Name(self, node):
self.write(node.id)
def visit_Str(self, node):
self.write(repr(node.s))
def visit_Bytes(self, node):
self.write(repr(node.s))
def visit_Num(self, node):
self.write(repr(node.n))
def visit_Tuple(self, node):
self.write('(')
idx = -1
for idx, item in enumerate(node.elts):
if idx:
self.write(', ')
self.visit(item)
self.write(idx and ')' or ',)')
def sequence_visit(left, right):
def visit(self, node):
self.write(left)
for idx, item in enumerate(node.elts):
if idx:
self.write(', ')
self.visit(item)
self.write(right)
return visit
visit_List = sequence_visit('[', ']')
visit_Set = sequence_visit('{', '}')
del sequence_visit
def visit_Dict(self, node):
self.write('{')
for idx, (key, value) in enumerate(zip(node.keys, node.values)):
if idx:
self.write(', ')
self.visit(key)
self.write(': ')
self.visit(value)
self.write('}')
def visit_BinOp(self, node):
self.write('(')
self.visit(node.left)
self.write(' %s ' % BINOP_SYMBOLS[type(node.op)])
self.visit(node.right)
self.write(')')
def visit_BoolOp(self, node):
self.write('(')
for idx, value in enumerate(node.values):
if idx:
self.write(' %s ' % BOOLOP_SYMBOLS[type(node.op)])
self.visit(value)
self.write(')')
def visit_Compare(self, node):
self.write('(')
self.visit(node.left)
for op, right in zip(node.ops, node.comparators):
self.write(' %s ' % CMPOP_SYMBOLS[type(op)])
self.visit(right)
self.write(')')
def visit_UnaryOp(self, node):
self.write('(')
op = UNARYOP_SYMBOLS[type(node.op)]
self.write(op)
if op == 'not':
self.write(' ')
self.visit(node.operand)
self.write(')')
def visit_Subscript(self, node):
self.visit(node.value)
self.write('[')
self.visit(node.slice)
self.write(']')
def visit_Slice(self, node):
if node.lower is not None:
self.visit(node.lower)
self.write(':')
if node.upper is not None:
self.visit(node.upper)
if node.step is not None:
self.write(':')
if not (isinstance(node.step, Name) and node.step.id == 'None'):
self.visit(node.step)
def visit_ExtSlice(self, node):
for idx, item in node.dims:
if idx:
self.write(', ')
self.visit(item)
def visit_Yield(self, node):
self.write('yield ')
self.visit(node.value)
def visit_Lambda(self, node):
self.write('lambda ')
self.signature(node.args)
self.write(': ')
self.visit(node.body)
def visit_Ellipsis(self, node):
self.write('Ellipsis')
def generator_visit(left, right):
def visit(self, node):
self.write(left)
self.visit(node.elt)
for comprehension in node.generators:
self.visit(comprehension)
self.write(right)
return visit
visit_ListComp = generator_visit('[', ']')
visit_GeneratorExp = generator_visit('(', ')')
visit_SetComp = generator_visit('{', '}')
del generator_visit
def visit_DictComp(self, node):
self.write('{')
self.visit(node.key)
self.write(': ')
self.visit(node.value)
for comprehension in node.generators:
self.visit(comprehension)
self.write('}')
def visit_IfExp(self, node):
self.visit(node.body)
self.write(' if ')
self.visit(node.test)
self.write(' else ')
self.visit(node.orelse)
def visit_Starred(self, node):
self.write('*')
self.visit(node.value)
def visit_Repr(self, node):
# XXX: python 2.6 only
self.write('`')
self.visit(node.value)
self.write('`')
# Helper Nodes
def visit_alias(self, node):
self.write(node.name)
if node.asname is not None:
self.write(' as ' + node.asname)
def visit_comprehension(self, node):
self.write(' for ')
self.visit(node.target)
self.write(' in ')
self.visit(node.iter)
if node.ifs:
for if_ in node.ifs:
self.write(' if ')
self.visit(if_)
def visit_excepthandler(self, node):
self.newline()
self.write('except')
if node.type is not None:
self.write(' ')
self.visit(node.type)
if node.name is not None:
self.write(' as ')
self.visit(node.name)
self.write(':')
self.body(node.body)
| [
[
8,
0,
0.0232,
0.031,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0393,
0.0012,
0,
0.66,
0.0385,
709,
0,
1,
0,
0,
709,
0,
0
],
[
14,
0,
0.0447,
0.0048,
0,
0.66... | [
"\"\"\"\n ast\n ~~~\n\n The `ast` module helps Python applications to process trees of the Python\n abstract syntax grammar. The abstract syntax itself might change with\n each Python release; this module helps to find out programmatically what\n the current grammar looks like and allows modifica... |
# mako/cache.py
# Copyright (C) 2006-2011 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from mako import exceptions
cache = None
class BeakerMissing(object):
def get_cache(self, name, **kwargs):
raise exceptions.RuntimeException("the Beaker package is required to use cache functionality.")
class Cache(object):
"""Represents a data content cache made available to the module
space of a :class:`.Template` object.
:class:`.Cache` is a wrapper on top of a Beaker CacheManager object.
This object in turn references any number of "containers", each of
which defines its own backend (i.e. file, memory, memcached, etc.)
independently of the rest.
"""
def __init__(self, id, starttime):
self.id = id
self.starttime = starttime
self.def_regions = {}
def put(self, key, value, **kwargs):
"""Place a value in the cache.
:param key: the value's key.
:param value: the value
:param \**kwargs: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
values will use that same backend.
"""
defname = kwargs.pop('defname', None)
expiretime = kwargs.pop('expiretime', None)
createfunc = kwargs.pop('createfunc', None)
self._get_cache(defname, **kwargs).put_value(key, starttime=self.starttime, expiretime=expiretime)
def get(self, key, **kwargs):
"""Retrieve a value from the cache.
:param key: the value's key.
:param \**kwargs: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
values will use that same backend.
"""
defname = kwargs.pop('defname', None)
expiretime = kwargs.pop('expiretime', None)
createfunc = kwargs.pop('createfunc', None)
return self._get_cache(defname, **kwargs).get_value(key, starttime=self.starttime, expiretime=expiretime, createfunc=createfunc)
def invalidate(self, key, **kwargs):
"""Invalidate a value in the cache.
:param key: the value's key.
:param \**kwargs: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
values will use that same backend.
"""
defname = kwargs.pop('defname', None)
expiretime = kwargs.pop('expiretime', None)
createfunc = kwargs.pop('createfunc', None)
self._get_cache(defname, **kwargs).remove_value(key, starttime=self.starttime, expiretime=expiretime)
def invalidate_body(self):
"""Invalidate the cached content of the "body" method for this template.
"""
self.invalidate('render_body', defname='render_body')
def invalidate_def(self, name):
"""Invalidate the cached content of a particular <%def> within this template."""
self.invalidate('render_%s' % name, defname='render_%s' % name)
def invalidate_closure(self, name):
"""Invalidate a nested <%def> within this template.
Caching of nested defs is a blunt tool as there is no
management of scope - nested defs that use cache tags
need to have names unique of all other nested defs in the
template, else their content will be overwritten by
each other.
"""
self.invalidate(name, defname=name)
def _get_cache(self, defname, type=None, **kw):
global cache
if not cache:
try:
from beaker import cache as beaker_cache
cache = beaker_cache.CacheManager()
except ImportError:
# keep a fake cache around so subsequent
# calls don't attempt to re-import
cache = BeakerMissing()
if type == 'memcached':
type = 'ext:memcached'
if not type:
(type, kw) = self.def_regions.get(defname, ('memory', {}))
else:
self.def_regions[defname] = (type, kw)
return cache.get_cache(self.id, type=type, **kw)
| [
[
1,
0,
0.0565,
0.0081,
0,
0.66,
0,
682,
0,
1,
0,
0,
682,
0,
0
],
[
14,
0,
0.0726,
0.0081,
0,
0.66,
0.3333,
419,
1,
0,
0,
0,
0,
9,
0
],
[
3,
0,
0.0968,
0.0242,
0,
0... | [
"from mako import exceptions",
"cache = None",
"class BeakerMissing(object):\n def get_cache(self, name, **kwargs):\n raise exceptions.RuntimeException(\"the Beaker package is required to use cache functionality.\")",
" def get_cache(self, name, **kwargs):\n raise exceptions.RuntimeExcepti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import web
import uuid
from mako.lookup import TemplateLookup
from mako import exceptions
__author__ = 'Michael Liao'
class emptyobject(object):
def __getattr__(self, attr):
return ''
def __setattr__(self, attr, value):
pass
class odict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
class WebError(StandardError):
def __init__(self, message):
super(WebError, self).__init__(message)
def next_id():
return uuid.uuid4().hex
def _create_db():
host = 'localhost'
db = 'weather'
port = 3306
user = 'weather'
pw = 'weather'
try:
import sae.const
db = sae.const.MYSQL_DB
user = sae.const.MYSQL_USER
pw = sae.const.MYSQL_PASS
host = sae.const.MYSQL_HOST
port = int(sae.const.MYSQL_PORT)
except ImportError:
pass
return web.database(dbn='mysql', host=host, port=port, db=db, user=user, pw=pw)
db = _create_db()
def _create_memcache_client():
try:
import pylibmc
return pylibmc.Client()
except ImportError:
import memcache
return memcache.Client(['127.0.0.1:11211'])
cache = _create_memcache_client()
TEMPLATE_PATH = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'templates')
logging.info('Init template path: %s' % TEMPLATE_PATH)
TEMPLATES_LOOKUP = TemplateLookup(directories=[TEMPLATE_PATH], input_encoding='utf-8', output_encoding='utf-8')
def handler(method='GET', use_template=True):
'''
using decorator:
@handler('GET')
def login():
return 'success'
is equal to:
def login():
return 'success'
login = handler('GET')(login)
'''
def _wrapper(func):
def _new_func(**kw):
if method=='GET' and web.ctx.method!='GET':
raise web.badrequest()
if method=='POST' and web.ctx.method!='POST':
raise web.badrequest()
r = func(**kw)
logging.info('Url handler returns: %s' % type(r))
if r is None or method=='POST':
return r
if func.use_template and isinstance(r, dict):
try:
template = TEMPLATES_LOOKUP.get_template('%s.html' % func.__name__)
logging.info('Model: %s' % str(r))
return template.render(**r)
except:
return exceptions.html_error_template().render()
if isinstance(r, str):
return r
if isinstance(r, unicode):
return r.encode('utf-8')
return str(r)
_new_func.__name__ = func.__name__
_new_func.handler = True
func.use_template = use_template
return _new_func
return _wrapper
| [
[
1,
0,
0.037,
0.0093,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0556,
0.0093,
0,
0.66,
0.0556,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0648,
0.0093,
0,
0... | [
"import logging",
"import os",
"import web",
"import uuid",
"from mako.lookup import TemplateLookup",
"from mako import exceptions",
"__author__ = 'Michael Liao'",
"class emptyobject(object):\n def __getattr__(self, attr):\n return ''\n\n def __setattr__(self, attr, value):\n pass"... |
from pandas.io.data import DataReader
from pandas.io.data import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from datetime import datetime
from datetime import timedelta
import pandas as pd
import numpy as np
import urllib
import codecs
import csv
import os
import glob
import json
import requests
#from pykalman import UnscentedKalmanFilter
# Only provide the analysis tool, no ticker pick included
def ticker_retrive(ticker):
data = DataReader(ticker, "yahoo", datetime(2000, 1, 1), datetime.today())
filename = ticker + ".csv"
data.to_csv(filename)
def ticker_update():
return
def ticker_from_csv(ticker):
filename = ticker + ".csv"
df = DataFrame.from_csv(filename)
return df
def ticker_price_av(line):
line['Open'] = ''
def df_ticker_return(tickerdf):
'''
Not good strategy
'''
columnName = ['p12','p26','v12','v26', 'pAv']
ma = pd.DataFrame(index=tickerdf.index, columns=columnName)
# moving average
ma['p12'] = pd.rolling_mean(tickerdf['Adj Close'],12, min_periods=2)
ma['p26'] = pd.rolling_mean(tickerdf['Adj Close'],26, min_periods=2)
ma['v12'] = pd.rolling_mean(tickerdf['Volume'],12, min_periods=2)
ma['v26'] = pd.rolling_mean(tickerdf['Volume'],26, min_periods=2)
# average price
ma['gain'] = ma['v12'] - ma['v26']
ma['gainMA'] = pd.rolling_mean(ma['gain'],5, min_periods=2)
ma['close'] = tickerdf['Adj Close']*10000
ma = ma[-30:]
N = len(ma)
ind = np.arange(N) # the evenly spaced plot indices
fig, ax = plt.subplots()
ax.plot(ind, ma['gain'], '-')
ax.plot(ind, ma['gainMA'],'o-')
ax.bar(ind, ma['close'])
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return ma.index[thisind].strftime('%Y-%m-%d')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.show()
#return ma
def df_ticker_volume(tickerdf):
tickerdf['VolMA10'] = pd.rolling_mean(tickerDf['Volume'],12, min_periods=2)
tickerdf['VolMA26'] = pd.rolling_mean(tickerDf['Volume'],26, min_periods=2)
return tickerdf
def chart_weekly(tickerdf):
''' Chart for weekly price and volume movement
'''
print "weekly chart"
if __name__ =='__main__':
ticker = 'amrs'
#ticker_retrive(ticker)
tickerdf = ticker_from_csv(ticker);
| [
[
1,
0,
0.0112,
0.0112,
0,
0.66,
0,
190,
0,
1,
0,
0,
190,
0,
0
],
[
1,
0,
0.0225,
0.0112,
0,
0.66,
0.0455,
190,
0,
1,
0,
0,
190,
0,
0
],
[
1,
0,
0.0337,
0.0112,
0,
... | [
"from pandas.io.data import DataReader",
"from pandas.io.data import DataFrame",
"import matplotlib.pyplot as plt",
"import matplotlib.ticker as ticker",
"from datetime import datetime",
"from datetime import timedelta",
"import pandas as pd",
"import numpy as np",
"import urllib",
"import codecs"... |
import csv
import numpy as np
from pandas import DataFrame
import pandas as pd
# all digits are decreased by 1
len_total = 280
len_freq = 7
len_body = 5
len_star = 2
freq_body = []
freq_star = []
relation_body = np.zeros(shape=(50,50))
relation_star = np.zeros(shape=(11,11))
def rel_body(firstCounter, list_data):
first = firstCounter + 1
if (first>= len_body):
return
for i in range(first, len_body):
relation_body[int(list_data[firstCounter])-1, int(list_data[i])-1] += 1
relation_body[int(list_data[i])-1, int(list_data[firstCounter])-1] += 1
def rel_star(first,second):
relation_star[int(first)-1,int(second)-1] +=1
relation_star[int(second)-1,int(first)-1] +=1
def read():
with open('data.csv','rb') as csvfile:
data = csv.reader(csvfile, delimiter=';')
for row in data:
for i in range(len_body):
rel_body(i,row)
rel_star(row[len_body],row[len_body+1])
def read_freq():
with open('data.csv','rb') as csvfile:
data = csv.reader(csvfile, delimiter=';')
counter = 0
for row in data:
if counter > 28:
return
else :
counter += 1
for i in range(len_body):
freq_body
def to_csv():
df_body = pd.DataFrame(rel_body)
df_star = pd.DataFrame(rel_star)
| [
[
1,
0,
0.0182,
0.0182,
0,
0.66,
0,
312,
0,
1,
0,
0,
312,
0,
0
],
[
1,
0,
0.0364,
0.0182,
0,
0.66,
0.0625,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0545,
0.0182,
0,
... | [
"import csv",
"import numpy as np",
"from pandas import DataFrame",
"import pandas as pd",
"len_total = 280",
"len_freq = 7",
"len_body = 5",
"len_star = 2",
"freq_body = []",
"freq_star = []",
"relation_body = np.zeros(shape=(50,50))",
"relation_star = np.zeros(shape=(11,11))",
"def rel_bod... |
import sys, string, re, Queue
arith = ['sub', 'div', 'mod', 'cmple', 'add', 'mul', 'cmpeq', 'cmplt']
operators = ['-', '/', '%', '<=', '+', '*', '==', '<']
arith1 = ['neg']
targets = []
local_size = 0;
# get operand
def getOperand(t, sline, access_local):
#GP
if sline[t] == 'GP':
print '(char*)global',
return t+1
#FP
elif sline[t] == 'FP':
if access_local:
print '(char*)&local[' + str(local_size/8 -1) + ']',
else:
print '(char*)param',
return t+1
#constant
elif sline[t].isdigit():
print sline[t],
return t+1
#address offsets and field offsets
elif sline[t].endswith('_base') or sline[t].endswith('_offset'):
if sline[t+1][0] == '-':
print '(' + str(int(sline[t+1])+8) + ')',
return -(t+2)
else:
print str(int(sline[t+1])-8),
return t+2
#register name
elif sline[t][0] == '(':
print 'r' + sline[t].strip('()'),
return t+1
#code label
elif sline[t][0] == '[':
print 'instr_' + sline[t].strip('[]'),
return t+1
#local variables
else:
if sline[t+1][0] == '-':
print 'local[' + str((local_size-int(sline[t+1].strip('-')))/8) + ']',
else:
print 'param[' + str(int(sline[t+1])/8-1) + ']',
return t+2
# get next operand start
def getStart(t, sline):
#GP
if sline[t] == 'GP':
return t+1
#FP
elif sline[t] == 'FP':
return t+1
#constant
elif sline[t].isdigit():
return t+1
#address offsets and field offsets
elif sline[t].endswith('base') or sline[t].endswith('_offsets'):
if sline[t+1][0] == '-':
return -(t+2)
else:
return t+2
#register name
elif sline[t][0] == '(':
return t+1
#code label
elif sline[t][0] == '[':
return t+1
#local variables
else:
return t+2
#----------------- Main -----------------#
#if len(sys.argv) != 2:
# print "please specify input file name"
# sys.exit(0)
#
#ifile = open(sys.argv[1], 'r')
#parameters
params = Queue.LifoQueue()
params_n = 0
parsing_main = 0
# Print out header of the file
print '#include <stdio.h>\n\
#include <stdlib.h>\n\
#include <string.h>\n\
#define WriteLine() printf("\\n");\n\
#define WriteLong(x) printf(" %lld", x);\n\
#define ReadLong(a) if (fscanf(stdin, "%lld", &a) != 1) a = 0;\n\
#define long long long\n\n'
print 'long global[4096];\n'
# parse the file line by line
#for line in ifile:
for line in sys.stdin:
sline = re.split(': | |#', line.rstrip('\n').lstrip(' '))
if sline[2] == 'nop':
continue
#print label for next instruction
if sline[2] != 'enter' and sline[2] != 'entrypc':
print 'instr_' + sline[1] + ':;\n\t',
#function start
if sline[2] == 'enter':
assert int(sline[3]) % 8 == 0, 'operand not divisible by 8';
if not parsing_main:
print 'void func_' + sline[1] + '(long* param) {\n',
else:
print 'void main() {\n',
if (sline[3] != '0'):
print 'long local[' + str(int(sline[3])/8) + '];\n',
local_size = int(sline[3]);
parsing_main = 0
#main start
if sline[2] == 'entrypc':
parsing_main = 1
#function return
elif sline[2] == 'ret':
targets = []
print 'return;\n}\n',
#arithmatic
# elif sline[2] in arith:
# print 'long r' + sline[1] + ' =',
## t = getOperand(3, sline, 0)
## print operators[arith.index(sline[2])],
## if (t < 0):
## getOperand(-t, sline, 1)
## else:
## getOperand(t, sline, 0)
# t = getStart(3, sline)
# if (t < 0):
# getOperand(-t, sline, 1)
# else:
# getOperand(t, sline, 0)
# print operators[arith.index(sline[2])],
# getOperand(3, sline, 0)
# print ';\n',
elif sline[2] in arith:
if not sline[1] in targets:
sys.stdout.write('long ')
targets.append(sline[1])
print 'r'+sline[1] + ' =',
t = getOperand(3, sline, 0)
print operators[arith.index(sline[2])],
if (t < 0):
getOperand(-t, sline, 1)
else:
getOperand(t, sline, 0)
print ';\n',
elif sline[2] in arith1:
if not sline[1] in targets:
sys.stdout.write('long ')
targets.append(sline[1])
print 'r'+sline[1] + ' =',
t = getOperand(3, sline, 0)
print ' * (-1);\n',
#branch
elif sline[2] == 'br':
print 'goto ',
getOperand(3, sline, 0)
print ';\n',
elif sline[2] == 'blbs':
print 'if (',
t = getOperand(3, sline, 0)
print '!= 0) goto',
getOperand(t, sline, 0)
print ';\n',
elif sline[2] == 'blbc':
print 'if (',
t = getOperand(3, sline, 0)
print '== 0) goto',
getOperand(t, sline, 0)
print ';\n',
#data movement
elif sline[2] == 'load':
print 'long r' + sline[1] + ' = *(long*)',
getOperand(3, sline, 0)
print ';\n',
elif sline[2] == 'move':
temp = sline[4].strip('()')
if (temp.isdigit()) and (temp == sline[1]):
print 'long',
t = getStart(3, sline);
getOperand(t, sline, 0)
print ' = ',
getOperand(3, sline, 0)
print ';\n',
elif sline[2] == 'store':
print '*(long*)',
t = getStart(3, sline)
getOperand(t, sline, 0)
print ' =',
getOperand(3, sline, 0)
print ';\n',
#I/O
elif sline[2] == 'write':
print 'WriteLong(',
getOperand(3, sline, 0)
print ');\n',
elif sline[2] == 'wrl':
print 'WriteLine();\n',
elif sline[2] == 'read':
#TODO: read didn't appear in all any tests.. need to be tested
print 'long r' + sline[1] + ';\n\t',
print 'ReadLong( r' + sline[1],
print ');\n',
#Parameter and call
elif sline[2] == 'param':
print 'long r' + sline[1] + ' = ',
getOperand(3, sline, 0)
print ';//input parameter\n',
params.put(sline[1])
params_n += 1
elif sline[2] == 'call':
param_name = 'param_' + sline[1]
print 'long* ' + param_name + ' = (long*)malloc(sizeof(long)*' + str(params_n+1) + ');\n',
params_n = 0;
while not params.empty():
tt = params.get();
print 'memcpy(' + param_name + '+' + str(params_n+1) + ', &r' + tt + ', sizeof(long));\n',
params_n += 1
params_n = 0
print 'func_' + sline[3].strip('[]') + '(' + param_name + ');\n',
print 'free (' + str(param_name) + ');\n',
sys.exit(0)
| [
[
1,
0,
0.0039,
0.0039,
0,
0.66,
0,
509,
0,
4,
0,
0,
509,
0,
0
],
[
14,
0,
0.0157,
0.0039,
0,
0.66,
0.0769,
899,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.0196,
0.0039,
0,
... | [
"import sys, string, re, Queue",
"arith = ['sub', 'div', 'mod', 'cmple', 'add', 'mul', 'cmpeq', 'cmplt']",
"operators = ['-', '/', '%', '<=', '+', '*', '==', '<']",
"arith1 = ['neg']",
"targets = []",
"local_size = 0;",
"def getOperand(t, sline, access_local):\n#GP\n if sline[t] == 'GP':\n print('(c... |
#!/usr/bin/python2.5
import pacparser
pacparser.init()
pacparser.parse_pac("wpad.dat")
proxy = pacparser.find_proxy("http://www.manugarg.com")
print proxy
pacparser.cleanup()
# Or simply,
print pacparser.just_find_proxy("wpad.dat", "http://www2.manugarg.com")
| [
[
1,
0,
0.25,
0.0833,
0,
0.66,
0,
892,
0,
1,
0,
0,
892,
0,
0
],
[
8,
0,
0.4167,
0.0833,
0,
0.66,
0.1667,
319,
3,
0,
0,
0,
0,
0,
1
],
[
8,
0,
0.5,
0.0833,
0,
0.66,
... | [
"import pacparser",
"pacparser.init()",
"pacparser.parse_pac(\"wpad.dat\")",
"proxy = pacparser.find_proxy(\"http://www.manugarg.com\")",
"print(proxy)",
"pacparser.cleanup()",
"print(pacparser.just_find_proxy(\"wpad.dat\", \"http://www2.manugarg.com\"))"
] |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
Python module to parse pac files. Look at project's homepage
http://code.google.com/p/pacparser for more information.
"""
__author__ = 'manugarg@gmail.com (Manu Garg)'
__copyright__ = 'Copyright (C) 2008 Manu Garg'
__license__ = 'LGPL'
from pacparser import _pacparser
import os
import re
import sys
url_regex = re.compile('.*\:\/\/([^\/]+).*')
def init():
"""
Initializes pacparser engine.
"""
_pacparser.init()
def parse_pac(pacfile):
"""
(Deprecated) Same as parse_pac_file.
"""
parse_pac_file(pacfile)
def parse_pac_file(pacfile):
"""
Reads the pacfile and evaluates it in the Javascript engine created by
init().
"""
try:
f = open(pacfile)
pac_script = f.read()
except IOError:
print('Could not read the pacfile: %s\n%s' % (pacfile, sys.exc_info()[1]))
return
f.close()
_pacparser.parse_pac_string(pac_script)
def parse_pac_string(pac_script):
"""
Evaluates pac_script in the Javascript engine created by init().
"""
_pacparser.parse_pac_string(pac_script)
def find_proxy(url, host=None):
"""
Finds proxy string for the given url and host. If host is not
defined, it's extracted from the url.
"""
if host is None:
m = url_regex.match(url)
if not m:
print('URL: %s is not a valid URL' % url)
return None
if len(m.groups()) is 1:
host = m.groups()[0]
else:
print('URL: %s is not a valid URL' % url)
return None
return _pacparser.find_proxy(url, host)
def version():
"""
Returns the compiled pacparser version.
"""
return _pacparser.version()
def cleanup():
"""
Destroys pacparser engine.
"""
_pacparser.cleanup()
def just_find_proxy(pacfile, url, host=None):
"""
This function is a wrapper around init, parse_pac, find_proxy
and cleanup. This is the function to call if you want to find
proxy just for one url.
"""
if os.path.isfile(pacfile):
pass
else:
print('PAC file: %s doesn\'t exist' % pacfile)
return None
if host is None:
m = url_regex.match(url)
if not m:
print('URL: %s is not a valid URL' % url)
return None
if len(m.groups()) is 1:
host = m.groups()[0]
else:
print('URL: %s is not a valid URL' % url)
return None
init()
parse_pac(pacfile)
proxy = find_proxy(url,host)
cleanup()
return proxy
def setmyip(ip_address):
"""
Set my ip address. This is the IP address returned by myIpAddress()
"""
_pacparser.setmyip(ip_address)
def enable_microsoft_extensions():
"""
Enables Microsoft PAC extensions (dnsResolveEx, isResolvableEx,
myIpAddressEx).
"""
_pacparser.enable_microsoft_extensions()
| [
[
8,
0,
0.1715,
0.0292,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1971,
0.0073,
0,
0.66,
0.0556,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.2044,
0.0073,
0,
0.66... | [
"\"\"\"\nPython module to parse pac files. Look at project's homepage\nhttp://code.google.com/p/pacparser for more information.\n\"\"\"",
"__author__ = 'manugarg@gmail.com (Manu Garg)'",
"__copyright__ = 'Copyright (C) 2008 Manu Garg'",
"__license__ = 'LGPL'",
"from pacparser import _pacparser",
"import o... |
import shutil
import sys
from distutils import sysconfig
def main():
if sys.platform == 'win32':
shutil.rmtree('%s\\pacparser' % sysconfig.get_python_lib(),
ignore_errors=True)
shutil.copytree('pacparser', '%s\\pacparser' % sysconfig.get_python_lib())
else:
print 'This script should be used only on Win32 systems.'
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0667,
0.0667,
0,
0.66,
0,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.1333,
0.0667,
0,
0.66,
0.25,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2,
0.0667,
0,
0.66,... | [
"import shutil",
"import sys",
"from distutils import sysconfig",
"def main():\n if sys.platform == 'win32':\n shutil.rmtree('%s\\\\pacparser' % sysconfig.get_python_lib(),\n ignore_errors=True)\n shutil.copytree('pacparser', '%s\\\\pacparser' % sysconfig.get_python_lib())\n else:\n ... |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
"""
Wrapper script around python module Makefiles. This script take care of
identifying python setup and setting up some environment variables needed by
Makefiles.
"""
import sys
import os
from distutils import sysconfig
from distutils.core import setup
from distutils.core import Extension
def main():
# Use Makefile for windows. distutils doesn't work well with windows.
if sys.platform == 'win32':
pydll = ('C:\windows\system32\python%s.dll' %
sysconfig.get_config_vars('VERSION')[0])
os.system('make -f Makefile.win32 %s PY_HOME="%s" PY_DLL="%s"' %
(' '.join(sys.argv[1:]), sys.prefix, pydll))
return
pacparser_module = Extension('_pacparser',
include_dirs = ['../spidermonkey/js/src', '..'],
sources = ['pacparser_py.c'],
extra_objects = ['../pacparser.o', '../libjs.a'])
setup (name = 'pacparser',
version = '1',
description = 'Pacparser package',
author = 'Manu Garg',
author_email = 'manugarg@gmail.com',
url = 'http://code.google.com/p/pacparser',
long_description = 'python library to parse proxy auto-config (PAC) '
'files.',
license = 'LGPL',
ext_package = 'pacparser',
ext_modules = [pacparser_module],
py_modules = ['pacparser.__init__'])
if __name__ == '__main__':
main()
| [
[
8,
0,
0.4032,
0.0806,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4516,
0.0161,
0,
0.66,
0.1429,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4677,
0.0161,
0,
0.66... | [
"\"\"\"\nWrapper script around python module Makefiles. This script take care of\nidentifying python setup and setting up some environment variables needed by\nMakefiles.\n\"\"\"",
"import sys",
"import os",
"from distutils import sysconfig",
"from distutils.core import setup",
"from distutils.core import... |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
import getopt
import glob
import os
import sys
def runtests(pacfile, testdata, tests_dir):
py_ver = '.'.join([str(x) for x in sys.version_info[0:2]])
if sys.platform == 'win32':
pacparser_module_path = os.path.join(tests_dir, '..', 'src', 'pymod', 'dist')
if os.path.exists(os.path.join(pacparser_module_path, '_pacparser.pyd')):
raise Exception('Tests failed. Could not determine pacparser path.')
else:
try:
pacparser_module_path = glob.glob(os.path.join(
tests_dir, '..', 'src', 'pymod', 'build', 'lib*%s' % py_ver))[0]
except Exception:
raise Exception('Tests failed. Could not determine pacparser path.')
if 'DEBUG' in os.environ: print('Pacparser module path: %s' %
pacparser_module_path)
sys.path.insert(0, pacparser_module_path)
try:
import pacparser
except ImportError:
raise Exception('Tests failed. Could not import pacparser.')
if 'DEBUG' in os.environ: print('Imported pacparser module: %s' %
sys.modules['pacparser'])
f = open(testdata)
for line in f:
comment = ''
if '#' in line:
comment = line.split('#', 1)[1]
line = line.split('#', 1)[0].strip()
if not line:
continue
if ('NO_INTERNET' in os.environ and os.environ['NO_INTERNET'] and
'INTERNET_REQUIRED' in comment):
continue
if 'DEBUG' in os.environ: print(line)
(params, expected_result) = line.strip().split('|')
args = dict(getopt.getopt(params.split(), 'eu:c:')[0])
if '-e' in args:
pacparser.enable_microsoft_extensions()
if '-c' in args:
pacparser.setmyip(args['-c'])
pacparser.init()
pacparser.parse_pac_file(pacfile)
result = pacparser.find_proxy(args['-u'])
pacparser.cleanup()
if result != expected_result:
raise Exception('Tests failed. Got "%s", expected "%s"' % (result, expected_result))
print('All tests were successful.')
def main():
tests_dir = os.path.dirname(os.path.join(os.getcwd(), sys.argv[0]))
pacfile = os.path.join(tests_dir, 'proxy.pac')
testdata = os.path.join(tests_dir, 'testdata')
runtests(pacfile, testdata, tests_dir)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.2644,
0.0115,
0,
0.66,
0,
588,
0,
1,
0,
0,
588,
0,
0
],
[
1,
0,
0.2759,
0.0115,
0,
0.66,
0.1667,
958,
0,
1,
0,
0,
958,
0,
0
],
[
1,
0,
0.2874,
0.0115,
0,
... | [
"import getopt",
"import glob",
"import os",
"import sys",
"def runtests(pacfile, testdata, tests_dir):\n py_ver = '.'.join([str(x) for x in sys.version_info[0:2]])\n if sys.platform == 'win32':\n pacparser_module_path = os.path.join(tests_dir, '..', 'src', 'pymod', 'dist')\n if os.path.exists(os.pa... |
import cherrypy
import sqlite3
import Common
import os
import time
import hashlib
from postmarkup import render_bbcode
localdir = os.path.dirname(__file__)
absdir = os.path.join(os.getcwd(), localdir)
class User(Common.Template):
def index (self):
return self.default()
index.exposed = True
# this function receives post data from the register page. at this point we already know the username is unique. all we do here is add the user to the db and set the user's session. we then display the /User index
def user_register(self, Username=None, Password=None, Avatar=None, Signature=None):
c = cherrypy.thread_data.db.cursor()
c.execute('select max(ID) from User')
uid = c.fetchone()[0] + 1
# add the user to the system
c.execute('insert into User (ID,Username,Password,Permission,Avatar,Signature,JoinDate) values (NULL,?,?,2,?,?, date(\'now\'))', (self.strip_html_bbcode(Username), hashlib.md5(Password).hexdigest(), str(self.upload(Avatar, uid)), Signature,))
cherrypy.thread_data.db.commit()
# create the user's session
cherrypy.session['ID'] = uid
cherrypy.session['Username'] = self.strip_html_bbcode(Username)
cherrypy.session['Permission'] = c.execute('select Permission from User where ID=?', (uid,)).fetchone()[0]
return self.index()
user_register.exposed = True
#this page displays the registration form on the /login page after the user hits the register button. the post information is directed here and put in its respective fields. the form itself posts to user_register
def registerUserPage(self, user, passwd):
cursor = cherrypy.thread_data.db.cursor()
yield self.header()
yield self.links()
yield "<h1>Registration:</h1>"
yield "<table class='registration' width='100%'>"
#selects the admin which will always be there
cursor.execute("SELECT * FROM User WHERE ID IS 0")
info = cursor.fetchone()
#grabs a list of all column names
attr = cursor.description
yield "<form method='post' action='User/user_register' enctype='multipart/form-data'>"
#loop through all 8 columns
for i in range(8):
attrTmp = attr[i]
yield "<tr>"
#horrific if/else block for the register form. basically makes a row for each column and selectively lets the user edit them.
if not (attrTmp[0]=='ID' or attrTmp[0]=='BanTimestamp' or attrTmp[0]=='Permission' or attrTmp[0]=='JoinDate'):
yield "<td class='registration_list'>%s</td>"%str(attrTmp[0])
yield "<td class='registration_list_edit'>"
if attrTmp[0]=='Password':
yield "<input name='%s' type='password' value='%s' readonly></input>"%(attrTmp[0],str(passwd))
elif attrTmp[0]=='Avatar':
yield "<input name='%s' type='file'></input>"%attrTmp[0]
elif attrTmp[0]=='Username':
yield "<input name='%s' type='text' value='%s' readonly></input>"%(attrTmp[0],str(user))
elif attrTmp[0]=='Signature':
yield "<textarea class='monospace' name='Signature' rows='20' cols='80'>Signature</textarea>"
yield "</td>"
yield "</tr>"
yield "<tr><td class='registration_list'><input type='submit' value='Register'></input>"
yield "</form>"
yield "</table>"
yield "<br />"+self.footer()
registerUserPage.exposed = True
# simple method to determine if you can edit userinfo
def ownpage (self, id):
if self.getLoginPermission() == 0 or id == self.getLoginID() or ( self.getLoginPermission() == 1 and id != 0 ) or ( self.getLoginPermission() == 0 and id == 0 ):
return True
else:
return False
def upload (self, image=None, id=None):
#because image is still an object even if nothing is uploaded this is the only way i could find to determine if nothing was uploaded. seems like there should be an easier way to do this...
if image.fullvalue()=="":
#reutrn empty string so it doesnt break all avatar pics in the forum
return ""
saved_image = open('images/avatars/%s.dat'%id, 'wb')
while True:
#write pic file in 512bit(byte?) chunks
data = image.file.read(512)
if not data:
break
saved_image.write(data)
saved_image.close()
return saved_image.name
def user_edit (self, Username=None, Permission=None, BanTimestamp=None, Avatar=None, Password=None, ID = None, JoinDate = None, Signature = None):
c = cherrypy.thread_data.db.cursor()
#somewhat better if block than the register form. if a value was entered, change it in the db.
if Password:
c.execute("UPDATE User SET Password=? WHERE ID=?",(hashlib.md5(Password).hexdigest(), int(ID),))
cherrypy.thread_data.db.commit()
#would probably work fine with just the fullvalue()==""
if Avatar and (not Avatar.fullvalue() == ""):
Av = self.upload(Avatar, ID)
c.execute("UPDATE User Set Avatar=? WHERE ID=?",(Av,int(ID),))
cherrypy.thread_data.db.commit()
if Permission and self.getLoginPermission() < 1:
c.execute("UPDATE User Set Permission=? WHERE ID=?",(Permission,int(ID),))
cherrypy.thread_data.db.commit()
if BanTimestamp and self.getLoginPermission() < 2:
#parse correct timestamp
ts = int(BanTimestamp)
if ts < 0:
ts = "NULL"
elif ts > 0:
ts = time.time() + ts * 24 * 60 * 60
c.execute("UPDATE User Set BanTimestamp=? WHERE ID=?",(ts,int(ID),))
cherrypy.thread_data.db.commit()
if Signature:
c.execute("UPDATE User Set Signature=? WHERE ID=?",(Signature,int(ID),))
cherrypy.thread_data.db.commit()
yield self.redirect("/User/%s"%ID)
user_edit.exposed = True
#should be -1 by default to indicate something went wrong if its not changed
def default (self, id = -1):
# for some reason id is passed as a string
id = int(id)
cursor = cherrypy.thread_data.db.cursor()
cursor2 = cherrypy.thread_data.db.cursor()
yield self.header()
yield self.links()
# i dont think i need breadcrumbs in this pageview
yield self.breadcrumbs()
yield "<br/>"
# if the user is looking at the root Users page, display list of all + links
if id == -1:
cursor.execute('''
SELECT User.ID, User.Username, User.Avatar, User.Joindate, User.Signature
FROM User''')
#print list of all users
yield "<table class='user_list' align='center' width='100%'>"
yield "<tr><th class='user_list' width='200px'>Username</th><th class='user_list' width='125px'>Avatar</th><th class='user_list' width='125px'>Post Count</th><th class='user_list' width='125px'>Join Date</th><th class='user_list'>Signature</th></tr>"
#select number of posts by UserID
for UserID, Username, Avatar, Joindate, Signature in cursor.fetchall():
cursor2.execute('''SELECT COUNT(Post.ID) FROM Post WHERE Post.UserID = ?''', (UserID,))
count = cursor2.fetchone()[0]
if Avatar == "" or Avatar == None:
yield "<tr align='center'><td class='user_list'><a href='%s'>%s</a></td><td class='user_list'><td class='user_list'>%s</td><td class='user_list'>%s</td><td class='user_list'>%s</td></tr>" % (UserID, Username, count, Joindate, render_bbcode(Signature))
else:
yield "<tr align='center' valign='center'><td class='user_list'><a href='%s'>%s</a></td><td class='user_list'><img src='/%s' width='100px' height='100px' /></td><td class='user_list'>%s</td><td class='user_list'>%s</td><td class='user_list'>%s</td></tr>" % (UserID, Username, Avatar, count, Joindate, render_bbcode(Signature))
yield "</table>"
else:
#print all the user info for a given user
yield "<br /><h1>%s's User Info</h1><br />"%self.getUsername(id)
yield "<table class='user_info' width='100%'>"
cursor.execute("SELECT * FROM User WHERE ID IS ?",(id,))
info = cursor.fetchone()
attr = cursor.description
yield "<form method='post' action='user_edit' enctype='multipart/form-data'>"
#loop like the other loops through all columns in the user table
for i in range(8):
attrTmp = attr[i]
yield "<tr>"
#someone elses page
if attrTmp[0] != 'Password' or self.ownpage(id):
yield "<td class='user_info_list'>%s</td>"%str(attrTmp[0])
if attrTmp[0]=='BanTimestamp' and info[i] != None and info[i] != "NULL":
# decode the timestamp
yield "<td class='user_info_list'>%s</td>"%str(time.ctime(int(info[i])))
elif attrTmp[0]=="Password":
yield "<td class='user_info_list'> </td>"
else:
yield "<td class='user_info_list'>%s</td>"%render_bbcode(str(info[i]))
if self.ownpage(id):
yield "<td class='user_info_list_edit'>"
if attrTmp[0]=='Password':
yield "<input name='%s' "%attrTmp[0]
yield "type='password'>"
elif attrTmp[0]=='JoinDate':
yield "<input name='%s' "%attrTmp[0]
yield "type='hidden' readonly>"
elif attrTmp[0]=='Avatar':
yield "<input name='%s' "%attrTmp[0]
yield "type='file'>"
elif attrTmp[0]=='ID':
yield "<input name='%s' "%attrTmp[0]
yield "type='hidden' value='%s' readonly>"%id
elif attrTmp[0]=='Signature':
yield "<textarea class='monospace' name='%s' rows='20' cols='80'>%s</textarea>" % (attrTmp[0], info[i])
elif attrTmp[0]=='Username':
yield "<input name='%s' "%attrTmp[0]
yield "type='hidden' value='%s' readonly>"%str(info[i])
#mod/admin editable stuff below
elif attrTmp[0]=='BanTimestamp':
if self.getLoginPermission() < 2 and id != self.getLoginID():
yield "<input name='%s' "%attrTmp[0]
yield "type='text'> <i>(offest in days, 0 == permaban, -1 == clear)</i>"
else:
yield "<input name='%s' "%attrTmp[0]
yield "type='hidden' readonly>"
elif attrTmp[0]=='Permission':
if self.getLoginPermission() < 1:
yield "<input name='%s' "%attrTmp[0]
yield "type='text'>"
else:
yield "<input name='%s' "%attrTmp[0]
yield "type='hidden' readonly>"
yield "</input></td>"
yield "</tr>"
# now print all your info
yield "<tr><td class='user_info_list'>"
# display submit button only if the user has permission to
if self.ownpage(id):
yield "<input type='submit' value='Submit Changes'></input>"
yield "</form>"
yield "</table>"
yield "<br />"+self.footer()
default.exposed = True
| [
[
1,
0,
0.0045,
0.0045,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0089,
0.0045,
0,
0.66,
0.1111,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0134,
0.0045,
0,
... | [
"import cherrypy",
"import sqlite3",
"import Common",
"import os",
"import time",
"import hashlib",
"from postmarkup import render_bbcode",
"localdir = os.path.dirname(__file__)",
"absdir = os.path.join(os.getcwd(), localdir)",
"class User(Common.Template):\n\n\tdef index (self):\n\t\treturn self.... |
# -*- coding: UTF-8 -*-
"""
Post Markup
Author: Will McGugan (http://www.willmcgugan.com)
"""
__version__ = "1.1.4"
import re
from urllib import quote, unquote, quote_plus, urlencode
from urlparse import urlparse, urlunparse
pygments_available = True
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name, ClassNotFound
from pygments.formatters import HtmlFormatter
except ImportError:
# Make Pygments optional
pygments_available = False
def annotate_link(domain):
"""This function is called by the url tag. Override to disable or change behaviour.
domain -- Domain parsed from url
"""
return u" [%s]"%_escape(domain)
_re_url = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE)
_re_html=re.compile('<.*?>|\&.*?\;', re.UNICODE)
def textilize(s):
"""Remove markup from html"""
return _re_html.sub("", s)
_re_excerpt = re.compile(r'\[".*?\]+?.*?\[/".*?\]+?', re.DOTALL|re.UNICODE)
_re_remove_markup = re.compile(r'\[.*?\]', re.DOTALL|re.UNICODE)
_re_break_groups = re.compile(r'\n+', re.DOTALL|re.UNICODE)
def get_excerpt(post):
"""Returns an excerpt between ["] and [/"]
post -- BBCode string"""
match = _re_excerpt.search(post)
if match is None:
return ""
excerpt = match.group(0)
excerpt = excerpt.replace(u'\n', u"<br/>")
return _re_remove_markup.sub("", excerpt)
def strip_bbcode(bbcode):
"""Strips bbcode tags from a string.
bbcode -- A string to remove tags from
"""
return u"".join([t[1] for t in PostMarkup.tokenize(bbcode) if t[0] == PostMarkup.TOKEN_TEXT])
def create(include=None, exclude=None, use_pygments=True, **kwargs):
"""Create a postmarkup object that converts bbcode to XML snippets. Note
that creating postmarkup objects is _not_ threadsafe, but rendering the
html _is_ threadsafe. So typically you will need just one postmarkup instance
to render the bbcode accross threads.
include -- List or similar iterable containing the names of the tags to use
If omitted, all tags will be used
exclude -- List or similar iterable containing the names of the tags to exclude.
If omitted, no tags will be excluded
use_pygments -- If True, Pygments (http://pygments.org/) will be used for the code tag,
otherwise it will use <pre>code</pre>
kwargs -- Remaining keyword arguments are passed to tag constructors.
"""
postmarkup = PostMarkup()
postmarkup_add_tag = postmarkup.tag_factory.add_tag
def add_tag(tag_class, name, *args, **kwargs):
if include is None or name in include:
if exclude is not None and name in exclude:
return
postmarkup_add_tag(tag_class, name, *args, **kwargs)
add_tag(SimpleTag, 'b', 'strong')
add_tag(SimpleTag, 'i', 'em')
add_tag(SimpleTag, 'u', 'u')
add_tag(SimpleTag, 's', 'strike')
add_tag(LinkTag, 'link', **kwargs)
add_tag(LinkTag, 'url', **kwargs)
add_tag(QuoteTag, 'quote')
add_tag(SearchTag, u'wiki',
u"http://en.wikipedia.org/wiki/Special:Search?search=%s", u'wikipedia.com', **kwargs)
add_tag(SearchTag, u'google',
u"http://www.google.com/search?hl=en&q=%s&btnG=Google+Search", u'google.com', **kwargs)
add_tag(SearchTag, u'dictionary',
u"http://dictionary.reference.com/browse/%s", u'dictionary.com', **kwargs)
add_tag(SearchTag, u'dict',
u"http://dictionary.reference.com/browse/%s", u'dictionary.com', **kwargs)
add_tag(ImgTag, u'img')
add_tag(ListTag, u'list')
add_tag(ListItemTag, u'*')
add_tag(SizeTag, u"size")
add_tag(ColorTag, u"color")
add_tag(CenterTag, u"center")
if use_pygments:
assert pygments_available, "Install Pygments (http://pygments.org/) or call create with use_pygments=False"
add_tag(PygmentsCodeTag, u'code', **kwargs)
else:
add_tag(CodeTag, u'code', **kwargs)
add_tag(ParagraphTag, u"p")
return postmarkup
class TagBase(object):
def __init__(self, name, enclosed=False, auto_close=False, inline=False, strip_first_newline=False, **kwargs):
"""Base class for all tags.
name -- The name of the bbcode tag
enclosed -- True if the contents of the tag should not be bbcode processed.
auto_close -- True if the tag is standalone and does not require a close tag.
inline -- True if the tag generates an inline html tag.
"""
self.name = name
self.enclosed = enclosed
self.auto_close = auto_close
self.inline = inline
self.strip_first_newline = strip_first_newline
self.open_pos = None
self.close_pos = None
self.open_node_index = None
self.close_node_index = None
def open(self, parser, params, open_pos, node_index):
""" Called when the open tag is initially encountered. """
self.params = params
self.open_pos = open_pos
self.open_node_index = node_index
def close(self, parser, close_pos, node_index):
""" Called when the close tag is initially encountered. """
self.close_pos = close_pos
self.close_node_index = node_index
def render_open(self, parser, node_index):
""" Called to render the open tag. """
pass
def render_close(self, parser, node_index):
""" Called to render the close tag. """
pass
def get_contents(self, parser):
"""Returns the string between the open and close tag."""
return parser.markup[self.open_pos:self.close_pos]
def get_contents_text(self, parser):
"""Returns the string between the the open and close tag, minus bbcode tags."""
return u"".join( parser.get_text_nodes(self.open_node_index, self.close_node_index) )
def skip_contents(self, parser):
"""Skips the contents of a tag while rendering."""
parser.skip_to_node(self.close_node_index)
def __str__(self):
return '[%s]'%self.name
class SimpleTag(TagBase):
"""A tag that can be rendered with a simple substitution. """
def __init__(self, name, html_name, **kwargs):
""" html_name -- the html tag to substitute."""
TagBase.__init__(self, name, inline=True)
self.html_name = html_name
def render_open(self, parser, node_index):
return u"<%s>"%self.html_name
def render_close(self, parser, node_index):
return u"</%s>"%self.html_name
class DivStyleTag(TagBase):
"""A simple tag that is replaces with a div and a style."""
def __init__(self, name, style, value, **kwargs):
TagBase.__init__(self, name)
self.style = style
self.value = value
def render_open(self, parser, node_index):
return u'<div style="%s:%s;">' % (self.style, self.value)
def render_close(self, parser, node_index):
return u'</div>'
class LinkTag(TagBase):
_safe_chars = frozenset('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789'
'_.-=/&?:%&')
_re_domain = re.compile(r"//([a-z0-9-\.]*)", re.UNICODE)
def __init__(self, name, annotate_links=True, **kwargs):
TagBase.__init__(self, name, inline=True)
self.annotate_links = annotate_links
def render_open(self, parser, node_index):
self.domain = u''
tag_data = parser.tag_data
nest_level = tag_data['link_nest_level'] = tag_data.setdefault('link_nest_level', 0) + 1
if nest_level > 1:
return u""
if self.params:
url = self.params.strip()
else:
url = self.get_contents_text(parser).strip()
url = _unescape(url)
self.domain = ""
if u"javascript:" in url.lower():
return ""
if ':' not in url:
url = 'http://' + url
scheme, uri = url.split(':', 1)
if scheme not in ['http', 'https']:
return u''
try:
domain = self._re_domain.search(uri.lower()).group(1)
except IndexError:
return u''
domain = domain.lower()
if domain.startswith('www.'):
domain = domain[4:]
def percent_encode(s):
safe_chars = self._safe_chars
def replace(c):
if c not in safe_chars:
return "%%%02X"%ord(c)
else:
return c
return "".join([replace(c) for c in s])
self.url = percent_encode(url.encode('utf-8', 'replace'))
self.domain = domain
if not self.url:
return u""
if self.domain:
return u'<a href="%s">'%self.url
else:
return u""
def render_close(self, parser, node_index):
tag_data = parser.tag_data
tag_data['link_nest_level'] -= 1
if tag_data['link_nest_level'] > 0:
return u''
if self.domain:
return u'</a>'+self.annotate_link(self.domain)
else:
return u''
def annotate_link(self, domain=None):
if domain and self.annotate_links:
return annotate_link(domain)
else:
return u""
class QuoteTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, strip_first_newline=True)
def open(self, parser, *args):
TagBase.open(self, parser, *args)
def close(self, parser, *args):
TagBase.close(self, parser, *args)
def render_open(self, parser, node_index):
if self.params:
return u'<blockquote><em>%s</em><br/>'%(PostMarkup.standard_replace(self.params))
else:
return u'<blockquote>'
def render_close(self, parser, node_index):
return u"</blockquote>"
class SearchTag(TagBase):
def __init__(self, name, url, label="", annotate_links=True, **kwargs):
TagBase.__init__(self, name, inline=True)
self.url = url
self.label = label
self.annotate_links = annotate_links
def render_open(self, parser, node_idex):
if self.params:
search=self.params
else:
search=self.get_contents(parser)
link = u'<a href="%s">' % self.url
if u'%' in link:
return link%quote_plus(search.encode("UTF-8"))
else:
return link
def render_close(self, parser, node_index):
if self.label:
if self.annotate_links:
return u'</a>'+ annotate_link(self.label)
else:
return u'</a>'
else:
return u''
class PygmentsCodeTag(TagBase):
def __init__(self, name, pygments_line_numbers=False, **kwargs):
TagBase.__init__(self, name, enclosed=True, strip_first_newline=True)
self.line_numbers = pygments_line_numbers
def render_open(self, parser, node_index):
contents = self.get_contents(parser)
self.skip_contents(parser)
try:
lexer = get_lexer_by_name(self.params, stripall=True)
except ClassNotFound:
contents = _escape(contents)
return '<div class="code"><pre>%s</pre></div>' % contents
formatter = HtmlFormatter(linenos=self.line_numbers, cssclass="code")
return highlight(contents, lexer, formatter)
class CodeTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, enclosed=True, strip_first_newline=True)
def render_open(self, parser, node_index):
contents = _escape_no_breaks(self.get_contents(parser))
self.skip_contents(parser)
return '<div class="code"><pre>%s</pre></div>' % contents
class ImgTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, inline=True)
def render_open(self, parser, node_index):
contents = self.get_contents(parser)
self.skip_contents(parser)
contents = strip_bbcode(contents).replace(u'"', "%22")
return u'<img src="%s"></img>' % contents
class ListTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, strip_first_newline=True)
def open(self, parser, params, open_pos, node_index):
TagBase.open(self, parser, params, open_pos, node_index)
def close(self, parser, close_pos, node_index):
TagBase.close(self, parser, close_pos, node_index)
def render_open(self, parser, node_index):
self.close_tag = u""
tag_data = parser.tag_data
tag_data.setdefault("ListTag.count", 0)
if tag_data["ListTag.count"]:
return u""
tag_data["ListTag.count"] += 1
tag_data["ListItemTag.initial_item"]=True
if self.params == "1":
self.close_tag = u"</li></ol>"
return u"<ol><li>"
elif self.params == "a":
self.close_tag = u"</li></ol>"
return u'<ol style="list-style-type: lower-alpha;"><li>'
elif self.params == "A":
self.close_tag = u"</li></ol>"
return u'<ol style="list-style-type: upper-alpha;"><li>'
else:
self.close_tag = u"</li></ul>"
return u"<ul><li>"
def render_close(self, parser, node_index):
tag_data = parser.tag_data
tag_data["ListTag.count"] -= 1
return self.close_tag
class ListItemTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name)
self.closed = False
def render_open(self, parser, node_index):
tag_data = parser.tag_data
if not tag_data.setdefault("ListTag.count", 0):
return u""
if tag_data["ListItemTag.initial_item"]:
tag_data["ListItemTag.initial_item"] = False
return
return u"</li><li>"
class SizeTag(TagBase):
valid_chars = frozenset("0123456789")
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, inline=True)
def render_open(self, parser, node_index):
try:
self.size = int( "".join([c for c in self.params if c in self.valid_chars]) )
except ValueError:
self.size = None
if self.size is None:
return u""
self.size = self.validate_size(self.size)
return u'<span style="font-size:%spx">' % self.size
def render_close(self, parser, node_index):
if self.size is None:
return u""
return u'</span>'
def validate_size(self, size):
size = min(64, size)
size = max(4, size)
return size
class ColorTag(TagBase):
valid_chars = frozenset("#0123456789abcdefghijklmnopqrstuvwxyz")
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, inline=True)
def render_open(self, parser, node_index):
valid_chars = self.valid_chars
color = self.params.split()[0:1][0].lower()
self.color = "".join([c for c in color if c in valid_chars])
if not self.color:
return u""
return u'<span style="color:%s">' % self.color
def render_close(self, parser, node_index):
if not self.color:
return u''
return u'</span>'
class CenterTag(TagBase):
def render_open(self, parser, node_index, **kwargs):
return u'<div style="text-align:center;">'
def render_close(self, parser, node_index):
return u'</div>'
class ParagraphTag(TagBase):
def __init__(self, name, **kwargs):
TagBase.__init__(self, name)
def render_open(self, parser, node_index, **kwargs):
tag_data = parser.tag_data
level = tag_data.setdefault('ParagraphTag.level', 0)
ret = []
if level > 0:
ret.append(u'</p>')
tag_data['ParagraphTag.level'] -= 1;
ret.append(u'<p>')
tag_data['ParagraphTag.level'] += 1;
return u''.join(ret)
def render_close(self, parser, node_index):
tag_data = parser.tag_data
level = tag_data.setdefault('ParagraphTag.level', 0)
if not level:
return u''
tag_data['ParagraphTag.level'] -= 1;
return u'</p>'
class SectionTag(TagBase):
"""A specialised tag that stores its contents in a dictionary. Can be
used to define extra contents areas.
"""
def __init__(self, name, **kwargs):
TagBase.__init__(self, name, enclosed=True)
def render_open(self, parser, node_index):
self.section_name = self.params.strip().lower().replace(u' ', u'_')
contents = self.get_contents(parser)
self.skip_contents(parser)
tag_data = parser.tag_data
sections = tag_data.setdefault('sections', {})
sections.setdefault(self.section_name, []).append(contents)
return u''
# http://effbot.org/zone/python-replace.htm
class MultiReplace:
def __init__(self, repl_dict):
# string to string mapping; use a regular expression
keys = repl_dict.keys()
keys.sort(reverse=True) # lexical order
pattern = u"|".join([re.escape(key) for key in keys])
self.pattern = re.compile(pattern)
self.dict = repl_dict
def replace(self, s):
# apply replacement dictionary to string
def repl(match, get=self.dict.get):
item = match.group(0)
return get(item, item)
return self.pattern.sub(repl, s)
__call__ = replace
def _escape(s):
return PostMarkup.standard_replace(s.rstrip('\n'))
def _escape_no_breaks(s):
return PostMarkup.standard_replace_no_break(s.rstrip('\n'))
def _unescape(s):
return PostMarkup.standard_unreplace(s)
class TagFactory(object):
def __init__(self):
self.tags = {}
@classmethod
def tag_factory_callable(cls, tag_class, name, *args, **kwargs):
"""
Returns a callable that returns a new tag instance.
"""
def make():
return tag_class(name, *args, **kwargs)
return make
def add_tag(self, cls, name, *args, **kwargs):
self.tags[name] = self.tag_factory_callable(cls, name, *args, **kwargs)
def __getitem__(self, name):
return self.tags[name]()
def __contains__(self, name):
return name in self.tags
def get(self, name, default=None):
if name in self.tags:
return self.tags[name]()
return default
class _Parser(object):
""" This is an interface to the parser, used by Tag classes. """
def __init__(self, post_markup, tag_data=None):
self.pm = post_markup
if tag_data is None:
self.tag_data = {}
else:
self.tag_data = tag_data
self.render_node_index = 0
def skip_to_node(self, node_index):
""" Skips to a node, ignoring intermediate nodes. """
assert node_index is not None, "Node index must be non-None"
self.render_node_index = node_index
def get_text_nodes(self, node1, node2):
""" Retrieves the text nodes between two node indices. """
if node2 is None:
node2 = node1+1
return [node for node in self.nodes[node1:node2] if not callable(node)]
def begin_no_breaks(self):
"""Disables replacing of newlines with break tags at the start and end of text nodes.
Can only be called from a tags 'open' method.
"""
assert self.phase==1, "Can not be called from render_open or render_close"
self.no_breaks_count += 1
def end_no_breaks(self):
"""Re-enables auto-replacing of newlines with break tags (see begin_no_breaks)."""
assert self.phase==1, "Can not be called from render_open or render_close"
if self.no_breaks_count:
self.no_breaks_count -= 1
class PostMarkup(object):
standard_replace = MultiReplace({ u'<':u'<',
u'>':u'>',
u'&':u'&',
u'\n':u'<br/>'})
standard_unreplace = MultiReplace({ u'<':u'<',
u'>':u'>',
u'&':u'&'})
standard_replace_no_break = MultiReplace({ u'<':u'<',
u'>':u'>',
u'&':u'&',})
TOKEN_TAG, TOKEN_PTAG, TOKEN_TEXT = range(3)
_re_end_eq = re.compile(u"\]|\=", re.UNICODE)
_re_quote_end = re.compile(u'\"|\]', re.UNICODE)
# I tried to use RE's. Really I did.
@classmethod
def tokenize(cls, post):
re_end_eq = cls._re_end_eq
re_quote_end = cls._re_quote_end
text = True
pos = 0
def find_first(post, pos, re_ff):
try:
return re_ff.search(post, pos).start()
except AttributeError:
return -1
TOKEN_TAG, TOKEN_PTAG, TOKEN_TEXT = range(3)
post_find = post.find
while True:
brace_pos = post_find(u'[', pos)
if brace_pos == -1:
if pos<len(post):
yield TOKEN_TEXT, post[pos:], pos, len(post)
return
if brace_pos - pos > 0:
yield TOKEN_TEXT, post[pos:brace_pos], pos, brace_pos
pos = brace_pos
end_pos = pos+1
open_tag_pos = post_find(u'[', end_pos)
end_pos = find_first(post, end_pos, re_end_eq)
if end_pos == -1:
yield TOKEN_TEXT, post[pos:], pos, len(post)
return
if open_tag_pos != -1 and open_tag_pos < end_pos:
yield TOKEN_TEXT, post[pos:open_tag_pos], pos, open_tag_pos
end_pos = open_tag_pos
pos = end_pos
continue
if post[end_pos] == ']':
yield TOKEN_TAG, post[pos:end_pos+1], pos, end_pos+1
pos = end_pos+1
continue
if post[end_pos] == '=':
try:
end_pos += 1
while post[end_pos] == ' ':
end_pos += 1
if post[end_pos] != '"':
end_pos = post_find(u']', end_pos+1)
if end_pos == -1:
return
yield TOKEN_TAG, post[pos:end_pos+1], pos, end_pos+1
else:
end_pos = find_first(post, end_pos, re_quote_end)
if end_pos==-1:
return
if post[end_pos] == '"':
end_pos = post_find(u'"', end_pos+1)
if end_pos == -1:
return
end_pos = post_find(u']', end_pos+1)
if end_pos == -1:
return
yield TOKEN_PTAG, post[pos:end_pos+1], pos, end_pos+1
else:
yield TOKEN_TAG, post[pos:end_pos+1], pos, end_pos
pos = end_pos+1
except IndexError:
return
def add_tag(self, cls, name, *args, **kwargs):
return self.tag_factory.add_tag(cls, name, *args, **kwargs)
def tagify_urls(self, postmarkup ):
""" Surrounds urls with url bbcode tags. """
def repl(match):
return u'[url]%s[/url]' % match.group(0)
text_tokens = []
TOKEN_TEXT = PostMarkup.TOKEN_TEXT
for tag_type, tag_token, start_pos, end_pos in self.tokenize(postmarkup):
if tag_type == TOKEN_TEXT:
text_tokens.append(_re_url.sub(repl, tag_token))
else:
text_tokens.append(tag_token)
return u"".join(text_tokens)
def __init__(self, tag_factory=None):
self.tag_factory = tag_factory or TagFactory()
def default_tags(self):
""" Add some basic tags. """
add_tag = self.tag_factory.add_tag
add_tag(SimpleTag, u'b', u'strong')
add_tag(SimpleTag, u'i', u'em')
add_tag(SimpleTag, u'u', u'u')
add_tag(SimpleTag, u's', u's')
def get_supported_tags(self):
""" Returns a list of the supported tags. """
return sorted(self.tag_factory.tags.keys())
def insert_paragraphs(self, post_markup):
"""Inserts paragraph tags in place of newlines. A more complex task than
it may seem -- Multiple newlines result in just one paragraph tag, and
paragraph tags aren't inserted inside certain other tags (such as the
code tag). Returns a postmarkup string.
post_markup -- A string containing the raw postmarkup
"""
parts = [u'[p]']
tag_factory = self.tag_factory
enclosed_count = 0
TOKEN_TEXT = PostMarkup.TOKEN_TEXT
TOKEN_TAG = PostMarkup.TOKEN_TAG
for tag_type, tag_token, start_pos, end_pos in self.tokenize(post_markup):
if tag_type == TOKEN_TEXT:
if enclosed_count:
parts.append(post_markup[start_pos:end_pos])
else:
txt = post_markup[start_pos:end_pos]
txt = _re_break_groups.sub(u'[p]', txt)
parts.append(txt)
continue
elif tag_type == TOKEN_TAG:
tag_token = tag_token[1:-1].lstrip()
if ' ' in tag_token:
tag_name = tag_token.split(u' ', 1)[0]
else:
if '=' in tag_token:
tag_name = tag_token.split(u'=', 1)[0]
else:
tag_name = tag_token
else:
tag_token = tag_token[1:-1].lstrip()
tag_name = tag_token.split(u'=', 1)[0]
tag_name = tag_name.strip().lower()
end_tag = False
if tag_name.startswith(u'/'):
end_tag = True
tag_name = tag_name[1:]
tag = tag_factory.get(tag_name, None)
if tag is not None and tag.enclosed:
if end_tag:
enclosed_count -= 1
else:
enclosed_count += 1
parts.append(post_markup[start_pos:end_pos])
new_markup = u"".join(parts)
return new_markup
# Matches simple blank tags containing only whitespace
_re_blank_tags = re.compile(r"\<(\w+?)\>\s*\</\1\>")
@classmethod
def cleanup_html(cls, html):
"""Cleans up html. Currently only removes blank tags, i.e. tags containing only
whitespace. Only applies to tags without attributes. Tag removal is done
recursively until there are no more blank tags. So <strong><em></em></strong>
would be completely removed.
html -- A string containing (X)HTML
"""
original_html = ''
while original_html != html:
original_html = html
html = cls._re_blank_tags.sub(u"", html)
return html
def render_to_html(self,
post_markup,
encoding="ascii",
exclude_tags=None,
auto_urls=True,
paragraphs=False,
clean=True,
tag_data=None):
"""Converts post markup (ie. bbcode) to XHTML. This method is threadsafe,
buy virtue that the state is entirely stored on the stack.
post_markup -- String containing bbcode.
encoding -- Encoding of string, defaults to "ascii" if the string is not
already unicode.
exclude_tags -- A collection of tag names to ignore.
auto_urls -- If True, then urls will be wrapped with url bbcode tags.
paragraphs -- If True then line breaks will be replaced with paragraph
tags, rather than break tags.
clean -- If True, html will be run through the cleanup_html method.
tag_data -- An optional dictionary to store tag data in. The default of
None will create a dictionary internaly. Set this to your own dictionary
if you want to retrieve information from the Tag Classes.
"""
if not isinstance(post_markup, unicode):
post_markup = unicode(post_markup, encoding, 'replace')
if auto_urls:
post_markup = self.tagify_urls(post_markup)
if paragraphs:
post_markup = self.insert_paragraphs(post_markup)
parser = _Parser(self, tag_data=tag_data)
parser.markup = post_markup
if exclude_tags is None:
exclude_tags = []
tag_factory = self.tag_factory
nodes = []
parser.nodes = nodes
parser.phase = 1
parser.no_breaks_count = 0
enclosed_count = 0
open_stack = []
tag_stack = []
break_stack = []
remove_next_newline = False
def check_tag_stack(tag_name):
for tag in reversed(tag_stack):
if tag_name == tag.name:
return True
return False
def redo_break_stack():
while break_stack:
tag = break_stack.pop()
open_tag(tag)
tag_stack.append(tag)
def break_inline_tags():
while tag_stack:
if tag_stack[-1].inline:
tag = tag_stack.pop()
close_tag(tag)
break_stack.append(tag)
else:
break
def open_tag(tag):
def call(node_index):
return tag.render_open(parser, node_index)
nodes.append(call)
def close_tag(tag):
def call(node_index):
return tag.render_close(parser, node_index)
nodes.append(call)
TOKEN_TEXT = PostMarkup.TOKEN_TEXT
TOKEN_TAG = PostMarkup.TOKEN_TAG
# Pass 1
for tag_type, tag_token, start_pos, end_pos in self.tokenize(post_markup):
raw_tag_token = tag_token
if tag_type == TOKEN_TEXT:
if parser.no_breaks_count:
tag_token = tag_token.strip()
if not tag_token:
continue
if remove_next_newline:
tag_token = tag_token.lstrip(' ')
if tag_token.startswith('\n'):
tag_token = tag_token.lstrip(' ')[1:]
if not tag_token:
continue
remove_next_newline = False
if tag_stack and tag_stack[-1].strip_first_newline:
tag_token = tag_token.lstrip()
tag_stack[-1].strip_first_newline = False
if not tag_stack[-1]:
tag_stack.pop()
continue
if not enclosed_count:
redo_break_stack()
nodes.append(self.standard_replace(tag_token))
continue
elif tag_type == TOKEN_TAG:
tag_token = tag_token[1:-1].lstrip()
if ' ' in tag_token:
tag_name, tag_attribs = tag_token.split(u' ', 1)
tag_attribs = tag_attribs.strip()
else:
if '=' in tag_token:
tag_name, tag_attribs = tag_token.split(u'=', 1)
tag_attribs = tag_attribs.strip()
else:
tag_name = tag_token
tag_attribs = u""
else:
tag_token = tag_token[1:-1].lstrip()
tag_name, tag_attribs = tag_token.split(u'=', 1)
tag_attribs = tag_attribs.strip()[1:-1]
tag_name = tag_name.strip().lower()
end_tag = False
if tag_name.startswith(u'/'):
end_tag = True
tag_name = tag_name[1:]
if enclosed_count and tag_stack[-1].name != tag_name:
continue
if tag_name in exclude_tags:
continue
if not end_tag:
tag = tag_factory.get(tag_name, None)
if tag is None:
continue
redo_break_stack()
if not tag.inline:
break_inline_tags()
tag.open(parser, tag_attribs, end_pos, len(nodes))
if tag.enclosed:
enclosed_count += 1
tag_stack.append(tag)
open_tag(tag)
if tag.auto_close:
tag = tag_stack.pop()
tag.close(self, start_pos, len(nodes)-1)
close_tag(tag)
else:
if break_stack and break_stack[-1].name == tag_name:
break_stack.pop()
tag.close(parser, start_pos, len(nodes))
elif check_tag_stack(tag_name):
while tag_stack[-1].name != tag_name:
tag = tag_stack.pop()
break_stack.append(tag)
close_tag(tag)
tag = tag_stack.pop()
tag.close(parser, start_pos, len(nodes))
if tag.enclosed:
enclosed_count -= 1
close_tag(tag)
if not tag.inline:
remove_next_newline = True
if tag_stack:
redo_break_stack()
while tag_stack:
tag = tag_stack.pop()
tag.close(parser, len(post_markup), len(nodes))
if tag.enclosed:
enclosed_count -= 1
close_tag(tag)
parser.phase = 2
# Pass 2
parser.nodes = nodes
text = []
parser.render_node_index = 0
while parser.render_node_index < len(parser.nodes):
i = parser.render_node_index
node_text = parser.nodes[i]
if callable(node_text):
node_text = node_text(i)
if node_text is not None:
text.append(node_text)
parser.render_node_index += 1
html = u"".join(text)
if clean:
html = self.cleanup_html(html)
return html
# A shortcut for render_to_html
__call__ = render_to_html
_postmarkup = create(use_pygments=pygments_available)
def render_bbcode(bbcode,
encoding="ascii",
exclude_tags=None,
auto_urls=True,
paragraphs=False,
clean=True,
tag_data=None):
""" Renders a bbcode string in to XHTML. This is a shortcut if you don't
need to customize any tags.
post_markup -- String containing bbcode.
encoding -- Encoding of string, defaults to "ascii" if the string is not
already unicode.
exclude_tags -- A collection of tag names to ignore.
auto_urls -- If True, then urls will be wrapped with url bbcode tags.
paragraphs -- If True then line breaks will be replaces with paragraph
tags, rather than break tags.
clean -- If True, html will be run through a cleanup_html method.
tag_data -- An optional dictionary to store tag data in. The default of
None will create a dictionary internally.
"""
return _postmarkup(bbcode,
encoding,
exclude_tags=exclude_tags,
auto_urls=auto_urls,
paragraphs=paragraphs,
clean=clean,
tag_data=tag_data)
def _tests():
import sys
#sys.stdout=open('test.htm', 'w')
post_markup = create(use_pygments=True)
tests = []
print """<link rel="stylesheet" href="code.css" type="text/css" />\n"""
tests.append(']')
tests.append('[')
tests.append(':-[ Hello, [b]World[/b]')
tests.append("[link=http://www.willmcgugan.com]My homepage[/link]")
tests.append('[link="http://www.willmcgugan.com"]My homepage[/link]')
tests.append("[link http://www.willmcgugan.com]My homepage[/link]")
tests.append("[link]http://www.willmcgugan.com[/link]")
tests.append(u"[b]Hello André[/b]")
tests.append(u"[google]André[/google]")
tests.append("[s]Strike through[/s]")
tests.append("[b]bold [i]bold and italic[/b] italic[/i]")
tests.append("[google]Will McGugan[/google]")
tests.append("[wiki Will McGugan]Look up my name in Wikipedia[/wiki]")
tests.append("[quote Will said...]BBCode is very cool[/quote]")
tests.append("""[code python]
# A proxy object that calls a callback when converted to a string
class TagStringify(object):
def __init__(self, callback, raw):
self.callback = callback
self.raw = raw
r[b]=3
def __str__(self):
return self.callback()
def __repr__(self):
return self.__str__()
[/code]""")
tests.append(u"[img]http://upload.wikimedia.org/wikipedia/commons"\
"/6/61/Triops_longicaudatus.jpg[/img]")
tests.append("[list][*]Apples[*]Oranges[*]Pears[/list]")
tests.append("""[list=1]
[*]Apples
[*]Oranges
are not the only fruit
[*]Pears
[/list]""")
tests.append("[list=a][*]Apples[*]Oranges[*]Pears[/list]")
tests.append("[list=A][*]Apples[*]Oranges[*]Pears[/list]")
long_test="""[b]Long test[/b]
New lines characters are converted to breaks."""\
"""Tags my be [b]ove[i]rl[/b]apped[/i].
[i]Open tags will be closed.
[b]Test[/b]"""
tests.append(long_test)
tests.append("[dict]Will[/dict]")
tests.append("[code unknownlanguage]10 print 'In yr code'; 20 goto 10[/code]")
tests.append("[url=http://www.google.com/coop/cse?cx=006850030468302103399%3Amqxv78bdfdo]CakePHP Google Groups[/url]")
tests.append("[url=http://www.google.com/search?hl=en&safe=off&client=opera&rls=en&hs=pO1&q=python+bbcode&btnG=Search]Search for Python BBCode[/url]")
#tests = []
# Attempt to inject html in to unicode
tests.append("[url=http://www.test.com/sfsdfsdf/ter?t=\"></a><h1>HACK</h1><a>\"]Test Hack[/url]")
tests.append('Nested urls, i.e. [url][url]www.becontrary.com[/url][/url], are condensed in to a single tag.')
tests.append(u'[google]ɸβfvθðsz[/google]')
tests.append(u'[size 30]Hello, World![/size]')
tests.append(u'[color red]This should be red[/color]')
tests.append(u'[color #0f0]This should be green[/color]')
tests.append(u"[center]This should be in the center!")
tests.append('Nested urls, i.e. [url][url]www.becontrary.com[/url][/url], are condensed in to a single tag.')
#tests = []
tests.append('[b]Hello, [i]World[/b]! [/i]')
tests.append('[b][center]This should be centered![/center][/b]')
tests.append('[list][*]Hello[i][*]World![/i][/list]')
tests.append("""[list=1]
[*]Apples
[*]Oranges
are not the only fruit
[*]Pears
[/list]""")
tests.append("[b]urls such as http://www.willmcgugan.com are authomaticaly converted to links[/b]")
tests.append("""
[b]
[code python]
parser.markup[self.open_pos:self.close_pos]
[/code]
asdasdasdasdqweqwe
""")
tests.append("""[list 1]
[*]Hello
[*]World
[/list]""")
#tests = []
tests.append("[b][p]Hello, [p]World")
tests.append("[p][p][p]")
tests.append("http://www.google.com/search?as_q=bbcode&btnG=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA")
#tests=["""[b]b[i]i[/b][/i]"""]
for test in tests:
print u"<pre>%s</pre>"%str(test.encode("ascii", "xmlcharrefreplace"))
print u"<p>%s</p>"%str(post_markup(test).encode("ascii", "xmlcharrefreplace"))
print u"<hr/>"
print
#print repr(post_markup('[url=<script>Attack</script>]Attack[/url]'))
#print repr(post_markup('http://www.google.com/search?as_q=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA&test=hai'))
#p = create(use_pygments=False)
#print (p('[code]foo\nbar[/code]'))
#print render_bbcode("[b]For the lazy, use the http://www.willmcgugan.com render_bbcode function.[/b]")
smarkup = create()
smarkup.add_tag(SectionTag, 'section')
test = """Hello, World.[b][i]This in italics
[section sidebar]This is the [b]sidebar[/b][/section]
[section footer]
This is the footer
[/section]
More text"""
print smarkup(test, paragraphs=True, clean=False)
tag_data = {}
print smarkup(test, tag_data=tag_data, paragraphs=True, clean=True)
print tag_data
def _run_unittests():
# TODO: Expand tests for better coverage!
import unittest
class TestPostmarkup(unittest.TestCase):
def testcleanuphtml(self):
postmarkup = create()
tests = [("""\n<p>\n </p>\n""", ""),
("""<b>\n\n<i> </i>\n</b>Test""", "Test"),
("""<p id="test">Test</p>""", """<p id="test">Test</p>"""),]
for test, result in tests:
self.assertEqual(PostMarkup.cleanup_html(test).strip(), result)
def testsimpletag(self):
postmarkup = create()
tests= [ ('[b]Hello[/b]', "<strong>Hello</strong>"),
('[i]Italic[/i]', "<em>Italic</em>"),
('[s]Strike[/s]', "<strike>Strike</strike>"),
('[u]underlined[/u]', "<u>underlined</u>"),
]
for test, result in tests:
self.assertEqual(postmarkup(test), result)
def testoverlap(self):
postmarkup = create()
tests= [ ('[i][b]Hello[/i][/b]', "<em><strong>Hello</strong></em>"),
('[b]bold [u]both[/b] underline[/u]', '<strong>bold <u>both</u></strong><u> underline</u>')
]
for test, result in tests:
self.assertEqual(postmarkup(test), result)
def testlinks(self):
postmarkup = create(annotate_links=False)
tests= [ ('[link=http://www.willmcgugan.com]blog1[/link]', '<a href="http://www.willmcgugan.com">blog1</a>'),
('[link="http://www.willmcgugan.com"]blog2[/link]', '<a href="http://www.willmcgugan.com">blog2</a>'),
('[link http://www.willmcgugan.com]blog3[/link]', '<a href="http://www.willmcgugan.com">blog3</a>'),
('[link]http://www.willmcgugan.com[/link]', '<a href="http://www.willmcgugan.com">http://www.willmcgugan.com</a>')
]
for test, result in tests:
self.assertEqual(postmarkup(test), result)
suite = unittest.TestLoader().loadTestsFromTestCase(TestPostmarkup)
unittest.TextTestRunner(verbosity=2).run(suite)
def _ff_test():
def ff1(post, pos, c1, c2):
f1 = post.find(c1, pos)
f2 = post.find(c2, pos)
if f1 == -1:
return f2
if f2 == -1:
return f1
return min(f1, f2)
re_ff=re.compile('a|b', re.UNICODE)
def ff2(post, pos, c1, c2):
try:
return re_ff.search(post).group(0)
except AttributeError:
return -1
text = u"sdl;fk;sdlfks;dflksd;flksdfsdfwerwerwgwegwegwegwegwegegwweggewwegwegwegwettttttttttttttttttttttttttttttttttgggggggggg;slbdfkwelrkwelrkjal;sdfksdl;fksdf;lb"
REPEAT = 100000
from time import time
start = time()
for n in xrange(REPEAT):
ff1(text, 0, "a", "b")
end = time()
print end - start
start = time()
for n in xrange(REPEAT):
ff2(text, 0, "a", "b")
end = time()
print end - start
if __name__ == "__main__":
_tests()
_run_unittests()
#_ff_test()
| [
[
8,
0,
0.003,
0.0027,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0054,
0.0007,
0,
0.66,
0.0222,
162,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0068,
0.0007,
0,
0.66,
... | [
"\"\"\"\nPost Markup\nAuthor: Will McGugan (http://www.willmcgugan.com)\n\"\"\"",
"__version__ = \"1.1.4\"",
"import re",
"from urllib import quote, unquote, quote_plus, urlencode",
"from urlparse import urlparse, urlunparse",
"pygments_available = True",
"try:\n from pygments import highlight\n f... |
import cherrypy
import sqlite3
import time
from postmarkup import render_bbcode
import Common
class PrivateMessage(Common.Template):
# Call the default function with no arguments
def index(self):
return self.default()
index.exposed = True
# This function handles basically everything. If no ID is given, it
# displays in the inbox and outbox of the user. If an ID is given, it
# displays the PM with that ID. Pretty straightforward.
def default(self, id = None):
cursor = cherrypy.thread_data.db.cursor()
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
# Display the inbox and outbox
elif id == None:
yield self.header("Private Messages")
yield self.links()
yield self.breadcrumbs()
yield "<p align='center'><a href='New'>New Message</a></p>"
# Get all of the Private Messages to the logged in user
cursor.execute('''
SELECT PrivateMessage.ID, PrivateMessage.Title, User.ID, User.Username
FROM PrivateMessage, User
WHERE PrivateMessage.ToUserID = ? AND
PrivateMessage.FromUserID = User.ID
ORDER BY PrivateMessage.ID DESC
''', (self.getLoginID(),))
yield "<table width='100%'>"
yield "<tr valign='top'>"
yield "<td width='49%'>"
# Display these messages in the sent box
yield "<h2 align='center'>Inbox</h2>"
yield "<table width='100%' class='pm_list'>"
yield "<tr><th class='pm_list'>From</th><th class='pm_list'>Title</th></tr>"
for ID, Title, UserID, Username in cursor.fetchall():
yield "<tr>"
yield "<td width='35%%' class='pm_list'><a href='/User/%s'>%s</a></td>" % (UserID, Username)
yield "<td class='pm_list'><a href='%s'>%s</a></td>" % (ID, Title)
yield "</tr>"
yield "</table>"
yield "</td><td width='2%'> </td><td width='49%'>"
# Get all ofthe private messages from the logged in user
cursor.execute('''
SELECT PrivateMessage.ID, PrivateMessage.Title, User.ID, User.Username
FROM PrivateMessage, User
WHERE PrivateMessage.FromUserID = ? AND
PrivateMessage.ToUserID = User.ID
ORDER BY PrivateMessage.ID DESC
''', (self.getLoginID(),))
# Display these messages in the sent box
yield "<h2 align='center'>Sent Box</h2>"
yield "<table width='100%' class='pm_list'>"
yield "<tr><th class='pm_list'>To</th><th class='pm_list'>Title</th></tr>"
for ID, Title, UserID, Username in cursor.fetchall():
yield "<tr>"
yield "<td width='35%%' class='pm_list'><a href='/User/%s'>%s</a></td>" % (UserID, Username)
yield "<td class='pm_list'><a href='%s'>%s</a></td>" % (ID, Title)
yield "</tr>"
yield "</table>"
yield "</td>"
yield "</tr>"
yield "</table>"
yield self.footer()
else:
# An ID was given, show that PM
yield self.header("Private Messages")
yield self.links()
yield self.breadcrumbs()
# Get the private message, from and to user names
cursor.execute('''
SELECT PrivateMessage.ID, PrivateMessage.Title, PrivateMessage.Content, F.ID, F.Username, T.ID, T.Username
FROM PrivateMessage, User F, User T
WHERE
PrivateMessage.FromUserID = F.ID AND
PrivateMessage.ToUserID = T.ID AND
PrivateMessage.ID = ?
''', (id,))
(ID, Title, Content, FUserID, FUsername, TUserID, TUsername) = cursor.fetchone()
# Display the PM
yield "<p><b>Title:</b> %s</p>" % Title
yield "<p><b>To:</b> <a href='/User/%s'>%s</a></p>" % (TUserID, TUsername)
yield "<p><b>From:</b> <a href='/User/%s'>%s</a></p>" % (FUserID, FUsername)
yield "<p><b>Content:</b></p>"
yield "<p>%s</p>" % render_bbcode(Content)
yield self.footer()
default.exposed = True
# This message is how to send a new message. If any arguments are blank,
# then the new message form is showed. If not, the message is sent
def New(self, touser = "", title = "", content = ""):
# Get the uid of the user to send to
toid = self.get_uid(touser)
# Clean surrounding spaces
title = title.strip()
content = content.strip()
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
elif toid != None and title != "" and content != "":
cursor = cherrypy.thread_data.db.cursor()
# Create the PM
cursor.execute('''
INSERT INTO PrivateMessage (ID, Title, Content, FromUserID, ToUserID)
VALUES (NULL, ?, ?, ?, ?)
''', (title, content, self.getLoginID(), toid,))
cherrypy.thread_data.db.commit()
# Redirect back to the thread at the PM view
yield self.redirect("/PrivateMessage")
else:
yield self.header("New Private Message")
yield self.links()
yield self.breadcrumbs()
# Show the PM form
yield "<form method='post' action='/PrivateMessage/New'>"
yield "To User: <br />"
yield "<input class='monospace' type='text' name='touser' size='60' value='%s' /><br />" % touser
yield "Title: <br />"
yield "<input class='monospace' type='text' name='title' size='60' value='%s' /><br />" % title
yield "Content: <br />"
yield "<textarea class='monospace' name='content' rows='20' cols='80'>%s</textarea><br />" % content
yield "<input type='submit' value='Send' />"
yield "</form>"
yield self.footer()
New.exposed = True
# Get the userid of the a given usrename
def get_uid(self, username):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT User.ID FROM User WHERE User.Username = ?", (username,))
result = cursor.fetchone()
if result == None:
return None
else:
return result[0]
| [
[
1,
0,
0.0061,
0.0061,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0122,
0.0061,
0,
0.66,
0.2,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0183,
0.0061,
0,
0.6... | [
"import cherrypy",
"import sqlite3",
"import time",
"from postmarkup import render_bbcode",
"import Common",
"class PrivateMessage(Common.Template):\n\t# Call the default function with no arguments\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\n\t# This function handles basicall... |
import sqlite3
import getpass
# Create the connection
connection = sqlite3.connect("forum.db")
cursor = connection.cursor()
with open("dump.sql", "w") as f:
for line in connection.iterdump():
f.write("%s\n" % line)
| [
[
1,
0,
0.1,
0.1,
0,
0.66,
0,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.2,
0.1,
0,
0.66,
0.3333,
784,
0,
1,
0,
0,
784,
0,
0
],
[
14,
0,
0.5,
0.1,
0,
0.66,
0.6667,... | [
"import sqlite3",
"import getpass",
"connection = sqlite3.connect(\"forum.db\")",
"cursor = connection.cursor()",
" for line in connection.iterdump():\n f.write(\"%s\\n\" % line)",
" f.write(\"%s\\n\" % line)"
] |
import cherrypy
import sqlite3
import time
import Common
class Post(Common.Template):
def index(self):
return self.default()
index.exposed = True
# This function allows users to create new posts. It requres the thread_id
# argument. If Reply is set, it takes the user name and content from
# the given post. If title and content are not set or are not valid,
# this function shows the new post form. Otherwise, it inserts the post
# and then redirects back to the thread
def New(self, thread_id = None, title = "", content = "", Reply = False):
# Get the thread name
thread_name = self.get_thread_name(thread_id)
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
elif thread_name == None:
yield self.error("Specified thread not found", True)
elif self.Thread_Closed(thread_id):
yield self.error("Thread is closed", True)
elif content == "" or Reply == True:
# The user is logged in and the thread is valid, so show the input form
yield self.header("Reply to %s" % thread_name)
yield self.links()
yield self.breadcrumbs(ThreadID = thread_id)
yield "<form method='post' action='/Post/New/%s'>" % thread_id
yield "Post Title (optional): <br />"
yield "<input class='monospace' type='text' name='title' size='60' value='%s' /><br />" % title
yield "Content: <br />"
yield "<textarea class='monospace' name='content' rows='20' cols='80'>%s</textarea><br />" % content
yield "<input type='submit' value='Reply' />"
yield "</form>"
yield self.footer()
else:
# There is content in the post, insert a new post and redirect to the thread
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
# Add the Post
cursor.execute('''
INSERT INTO Post (ID, Title, Content, Timestamp, UserID, ThreadID, EditTimestamp, EditUserID)
VALUES (NULL, ?, ?, ?, ?, ?, NULL, NULL)
''', (title, self.strip_html_bbcode(content), int(time.time()), self.getLoginID(), thread_id,))
cherrypy.thread_data.db.commit()
# After this commit, the post counts will update because of the triggers
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s#%s" % (thread_id, cursor.lastrowid))
New.exposed = True
# Reply takes the thread and post the user wants to reply to and loads
# up the new post page with bbcode for the quote already filled out
def Reply(self, thread_id = None, reply_id = None):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT User.Username, Post.Content FROM Post, User WHERE Post.ID = ? AND Post.UserID = User.ID", (reply_id,))
(reply_username, reply_content) = cursor.fetchone()
content = "[QUOTE=%s]%s[/QUOTE]" % (reply_username, reply_content)
return self.New(thread_id, "", content, True)
Reply.exposed = True
# Edit behaves very simililarily to New, just refer to that comment
def Edit(self, PostID = None, NewPostTitle = "", NewPostContent = "", Delete = False):
# Get the post info
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Post.Title, Post.Content, Post.UserID, Post.ThreadID FROM Post WHERE Post.ID = ?", (PostID,))
(PostTitle, PostContent, PostUserID, thread_id) = cursor.fetchone()
if (NewPostTitle == "" and NewPostContent == "" and Delete == False) or (NewPostTitle == "" and self.post_is_first(PostID) and Delete == False):
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
elif str(self.getLoginID()) != str(PostUserID) and self.getLoginPermission() >= 2:
yield self.error("You don't have suffecient permission to edit that post", True)
elif PostTitle == None and PostContent == None:
yield self.error("Specified post does not exist", True)
elif self.Thread_Closed(thread_id):
yield self.error("Thread is closed", True)
else:
# The user is logged in and the post is valid, so show the input form
yield self.header("Edit Post")
yield self.links()
yield self.breadcrumbs(ThreadID = thread_id)
# This forum has hidden userid and threadid values to feed to the SavePost function
yield "<form method='post' action='/Post/Edit/%s'>" % PostID
if self.post_is_first(PostID):
yield "Post Title: <br />"
else:
yield "Post Title (optional): <br />"
yield "<input class='monospace' type='text' name='NewPostTitle' size='60' value='%s'/><br />" % PostTitle
yield "Content: <br />"
yield "<textarea class='monospace' name='NewPostContent' rows='20' cols='80'>%s</textarea><br />" % PostContent
yield "<input type='submit' value='Update Post' />"
if not self.post_is_first(PostID):
yield "<input type='submit' name='Delete' value='Delete Post' />"
yield "</form>"
yield self.footer()
else:
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
elif str(self.getLoginID()) != str(PostUserID) and self.getLoginPermission() >= 2:
yield self.error("You don't have suffecient permission to edit that post", True)
elif PostTitle == None and PostContent == None:
yield self.error("Specified post does not exist", True)
elif self.Thread_Closed(thread_id):
yield self.error("Thread is closed", True)
else:
if Delete:
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
cursor.execute("DELETE FROM Post WHERE Post.ID = ?", (PostID,))
cherrypy.thread_data.db.commit()
# After this commit, the post counts will update because of the triggers
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s" % (thread_id))
else:
# Add the Post
cursor.execute('''UPDATE Post SET Title = ?, Content = ?, EditTimestamp = ?, EditUserID = ? WHERE Post.ID = ?''', (self.strip_html_bbcode(NewPostTitle), NewPostContent, int(time.time()), self.getLoginID(), PostID,))
cherrypy.thread_data.db.commit()
cursor.execute("SELECT Post.ThreadID FROM Post WHERE Post.ID = ?", (PostID,))
threadid = cursor.fetchone()[0]
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s#%s" % (threadid, PostID))
Edit.exposed = True
# This function takes in a post and determines if it is the first post.
# This allows us to figure out if the user should be allowed to delete the post.
def post_is_first(self, PostID):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT MIN(Post.ID) FROM Post WHERE Post.ThreadID = (SELECT Post.ThreadID FROM Post WHERE Post.ID = ?)", (PostID,))
FirstPostID = cursor.fetchone()[0]
return str(FirstPostID) == str(PostID)
| [
[
1,
0,
0.0062,
0.0062,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0124,
0.0062,
0,
0.66,
0.25,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0186,
0.0062,
0,
0.... | [
"import cherrypy",
"import sqlite3",
"import time",
"import Common",
"class Post(Common.Template):\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\t\n\t# This function allows users to create new posts. It requres the thread_id\n\t# argument. If Reply is set, it takes the user name... |
import cherrypy
import sqlite3
import time
from postmarkup import render_bbcode
import Common
class Thread(Common.Template):
# Call the default function with no arguments
def index(self):
return self.default()
index.exposed = True
# Default function displays a given thread.
def default(self, id = None):
# Get the thread name
thread_name = self.get_thread_name(id)
if self.Thread_Closed(id):
thread_name += " - CLOSED"
if thread_name == None:
yield self.error("The specified thread does not exist!", True)
else:
# The thread exists
# Print the top of the page
yield self.header(thread_name)
yield self.links()
yield self.breadcrumbs(ThreadID = id)
yield '<br />'
# Print the action buttons
yield self.generator_expand(self.action_buttons(id))
# Print the posts
yield self.generator_expand(self.post_list(id))
# Print the action buttons again
yield self.generator_expand(self.action_buttons(id))
# Print the footer
yield self.footer()
# The page was viewed, so increment the viewcount
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("UPDATE Thread SET ViewCount = ViewCount + 1 WHERE ID = ?", (id,))
cherrypy.thread_data.db.commit()
default.exposed = True
# The action buttons are reply and the moderator actions. This function
# takes a given ID and prints the actions for that thread, respecting
# the permisisons of the logged in user
def action_buttons(self, id):
if self.getLoginID() != None:
yield "<p align='right'>"
if self.hasPermission(id):
# If the user is a mod in this given subforum, print the
# moderator action buttons
# Determine if the given thread is stickied to figure out
# what value to give the sticky function
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Thread.Sticky FROM Thread WHERE Thread.ID = ?", (id,))
Sticky = cursor.fetchone()[0]
if Sticky == 0:
yield "<a href='Sticky/%s/1'>Sticky Thread</a> | " % id
else:
yield "<a href='Sticky/%s/0'>Unsticky Thread</a> | " % id
# Determine if the given thread is closed to figure out
# what value to give the close function
if self.Thread_Closed(id):
yield "<a href='Closed/%s/0'>Open Thread</a> | " % id
else:
yield "<a href='Closed/%s/1'>Close Thread</a> | " % id
# Print the Move and Delete buttons
yield "<a href='Move/%s'>Move Thread</a> | " % id
yield "<a href='Delete/%s'>Delete Thread</a><br />" % id
if self.Thread_Closed(id) == False:
# If the thread isn't closed, print the reply button
yield "<a href='/Post/New/%s'>New Reply</a>" % id
yield "</p>"
# This function prints all of the posts in a given thread
def post_list(self, id):
# We actually need two cursors for this view
cursor = cherrypy.thread_data.db.cursor()
cursor2 = cherrypy.thread_data.db.cursor()
# Get all the posts in this thread, sorted by ascending post ID (chronological order)
cursor.execute('''
SELECT
Post.ID, Post.Title, Post.Content, Post.Timestamp, User.ID, User.Username, User.Permission, User.Avatar, User.Signature, Post.EditTimestamp, Post.EditUserID
FROM
Post, User
WHERE
Post.ThreadID = ? AND
Post.UserID = User.ID
ORDER BY
Post.ID ASC
''', (id,))
# Print the post, each in a separate table
count = 1
# An enum of the different permisison levles
permissions = ["Administrator", "Moderator", "Member"]
# If the user is logged in, we need an extra row for the reply with
# quote button.
if self.getLoginPermission() <= 2:
rowspan = 4
else:
rowspan = 3
# Print each post
for ID, Title, Content, Timestamp, UserID, Username, Permission, Avatar, Signature, EditTimestamp, EditUserID in cursor.fetchall():
yield "<table width='100%' cols='2' class='thread' >"
yield "<tr>"
yield "<td class='thread' colspan='2'><a name='%s'></a>%s <span style='float:right; text-align: right;'><a href='#%s'>#%s</a></span></td>" % (ID, Title, ID, count)
yield "</tr>"
yield "<tr>"
# If avatar is not set, print a 100x100 blank div, otherwise, print the image
if Avatar == "" or Avatar == None:
yield "<td class='thread' rowspan='%s' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><div width='100px' height='100px'> </div></td><td class='thread' height='75px' >%s</td>" % (rowspan, UserID, Username, permissions[Permission], render_bbcode(Content))
else:
yield "<td class='thread' rowspan='%s' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><img src='/%s' width='100px' height='100px' /></td><td class='thread' height='75px' >%s</td>" % (rowspan, UserID, Username, permissions[Permission], Avatar, render_bbcode(Content))
yield "</tr>"
yield "<tr>"
# Print the bbcode-ized sig
yield "<td class='thread'>%s</td>" % render_bbcode(Signature)
yield "</tr>"
yield "<tr>"
if EditTimestamp == None:
# The post hasn't been editted, just print the timestamp
yield "<td class='thread'>Posted on %s</td>" % time.strftime("%c", time.localtime(Timestamp))
else:
# The post has been editted, get the editing user's name
cursor2.execute('''SELECT User.Username FROM User WHERE User.ID = ?''', (EditUserID,))
EditUsername = cursor2.fetchone()[0]
yield "<td class='thread'>Posted on %s, Last Edited on %s by %s</td>" % (time.strftime("%c", time.localtime(Timestamp)), time.strftime("%c", time.localtime(EditTimestamp)), EditUsername)
yield "</tr>"
# If the thread isn't closed, print the reply buttons
if self.Thread_Closed(id) == False and self.getLoginPermission() <= 2:
yield "<tr>"
yield "<td class='thread' align='right'>"
if self.getLoginPermission() <= 1 or self.getLoginID() == UserID:
yield "<a href='/Post/Edit/%s'>Edit</a> " % ID
if self.getLoginPermission() <= 2:
yield "<a href='/Post/Reply/%s/%s'>Reply with Quote</a>" % (id, ID)
yield "</td>"
yield "</tr>"
yield "</table>"
yield "<br />"
count = count + 1
# This function is what creates new threads. If title and content aren't
# set, the form is showed. Otherwise, the new thread and new post
# are created
def New(self, subforum_id, title = "", content = ""):
# Get the thread name
subforum_name = self.get_subforum_name(subforum_id)
title = title.strip()
content = content.strip()
if self.getLoginPermission() >= 3:
yield self.error("You are not logged in", True)
elif subforum_name == None and subforum_id != "NULL":
yield self.error("Specified subforum doesn't exist", True)
elif title != "" and content != "":
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
# Add the Thread
cursor.execute('''
INSERT INTO Thread (ID, SubforumID, PostCount, ViewCount, Sticky, Closed)
VALUES (NULL, ?, 0, 0, 0, 0)
''', (subforum_id,))
cherrypy.thread_data.db.commit()
thread_id = cursor.lastrowid
# Add the Post
cursor.execute('''
INSERT INTO Post (ID, Title, Content, Timestamp, UserID, ThreadID, EditTimestamp, EditUserID)
VALUES (NULL, ?, ?, ?, ?, ?, NULL, NULL)
''', (self.strip_html_bbcode(title), content, int(time.time()), self.getLoginID(), thread_id,))
cherrypy.thread_data.db.commit()
# After this commit, the post counts will update because of the triggers
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s" % thread_id)
else:
# Show the create thread form
yield self.header("New Thread in %s" % subforum_name)
yield self.links()
yield self.breadcrumbs(SubforumID = subforum_id)
yield "<form method='post' action='/Thread/New'>"
yield "Thread Title: <br />"
yield "<input class='monospace' type='text' name='title' size='60' value='%s' /><br />" % title
yield "Content: <br />"
yield "<textarea class='monospace' name='content' rows='20' cols='80'>%s</textarea><br />" % content
yield "<input type='hidden' readonly='readonly' name='subforum_id' value='%s'>" % subforum_id
yield "<input type='submit' value='New Thread' />"
yield "</form>"
yield self.footer()
New.exposed = True
# This function sets or unsets the Sticky attribute for a given thread
def Sticky(self, id, value):
if self.hasPermission(id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("UPDATE Thread SET Sticky = ? WHERE ID = ?", (value, id,))
cherrypy.thread_data.db.commit()
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s" % (id))
else:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
Sticky.exposed = True
# This function sets or unsets the Closed attribute for a given thread
def Closed(self, id, value):
if self.hasPermission(id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("UPDATE Thread SET Closed = ? WHERE ID = ?", (value, id,))
cherrypy.thread_data.db.commit()
# Redirect back to the thread at the new post location
yield self.redirect("/Thread/%s" % (id))
else:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
Closed.exposed = True
# This function moves a given thread. If NewParentID isn't set, the form
# is displayed, otherwise, the thread is moved
def Move(self, id, NewParentID = None):
if self.hasPermission(id) and NewParentID == None:
# show the move form
yield self.header("Move Thread")
yield self.links()
yield self.breadcrumbs(ThreadID = id)
yield "<p>"
yield "<form method='post' action='%s'>" % id
yield self.RelocateTree()
yield "<br /><br /><input type='submit' value='Move Thread' />"
yield "</form>"
yield "</p>"
yield self.footer()
elif self.hasPermission(id):
# Move the thread
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
cursor.execute("UPDATE Thread SET SubforumID = ? WHERE ID = ?", (NewParentID, id,))
cherrypy.thread_data.db.commit()
# Triggers will delete posts and update post/thread counts
yield self.redirect("/Thread/%s" % (id))
else:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
Move.exposed = True
# This function recursively builds the tree of the available subforums
def RelocateTree(self, id = "", depth = ""):
if id == "" and depth == "":
out = "<select name='NewParentID'><option value='NULL' style='font-style: italic;'>(Forum Root)</option>" + self.RelocateTree("NULL", "—") + "</select>"
else:
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT ID, Name FROM Subforum WHERE ParentSubforumID IS ?", (id,))
out = ""
for ID, Name in cursor.fetchall():
out += "<option value='%s'>%s%s</option>" % (ID, depth, Name)
out += self.RelocateTree(ID, depth + "—")
return out
# This function deletes the thread with the given id. Triggers will take
# care of the posts contained in the thraed
def Delete(self, id):
if self.hasPermission(id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Thread.SubforumID FROM Thread WHERE Thread.ID = ?", (id,))
SubforumID = cursor.fetchone()[0]
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
cursor.execute("DELETE FROM Thread WHERE ID = ?", (id,))
cherrypy.thread_data.db.commit()
# Triggers will delete posts and update post/thread counts
# Redirect back to the thread at the new post location
yield self.redirect("/Subforum/%s" % (SubforumID))
else:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
Delete.exposed = True
| [
[
1,
0,
0.0031,
0.0031,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0062,
0.0031,
0,
0.66,
0.2,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0092,
0.0031,
0,
0.6... | [
"import cherrypy",
"import sqlite3",
"import time",
"from postmarkup import render_bbcode",
"import Common",
"class Thread(Common.Template):\n\t# Call the default function with no arguments\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\n\t# Default function displays a given thre... |
import cherrypy
import sqlite3
import os.path
import hashlib
# Import our modules
import Common
import Subforum
import Thread
import Post
import User
import Search
import Structure
import PrivateMessage
# root_dir is used by the config file
root_dir = os.path.dirname(os.path.abspath(__file__))
# connect to the database
def connect(thread_index):
cherrypy.thread_data.db = sqlite3.connect('forum.db')
cherrypy.engine.subscribe('start_thread', connect)
# the actual forum
class Forum(Common.Template):
def __init__(self):
# Register our modules
self.Subforum = Subforum.Subforum()
self.Thread = Thread.Thread()
self.Post = Post.Post()
self.User = User.User()
self.Search = Search.Search()
self.Structure = Structure.Structure()
self.PrivateMessage = PrivateMessage.PrivateMessage()
# For the index, just load the root forum display
def index(self):
return self.Subforum.default()
index.exposed = True
# event: log in or register a user
def login(self, user = None, passwd = None, reg = None):
if user and passwd:
c = cherrypy.thread_data.db.cursor()
uid = None
# check if the user pressed register
if reg:
c.execute('select ID from User where Username=?', (user,))
uid = c.fetchone()
# if the user is not registered
if uid is None:
# find a unique id for the new user
return self.User.registerUserPage(user, passwd)
else:
# display an error
return self.error('Username already exists.')
# otherwise, the default action is to login
else:
# check the database
c.execute('select ID from User where Username=? AND Password=?', (user, hashlib.md5(passwd).hexdigest(),))
uid = c.fetchone()
if uid is None:
# display an error
return self.error('Incorrect user/password combination.')
else:
uid = uid[0]
# display an error if the user is banned
ban = self.banCheck(uid)
if ban != None:
return self.error('You are banned. You will be unbanned: %s' % ban, True)
# create the user's session
cherrypy.session['ID'] = uid
cherrypy.session['Username'] = user
cherrypy.session['Permission'] = c.execute('select Permission from User where ID=?', (uid,)).fetchone()[0]
# if the user pressed register
if reg:
# take them to their user info page
return self.User.index()
else:
# otherwise, redirect them to the page they came from
#[todo] this seems unstable for some reason
return self.redirect("javascript:r=document.referrer;if(r.indexOf('logout')!=-1|r.indexOf('login')!=-1){r='/'};location.replace(r)")
else:
# display an error
return self.error('One or more login fields are blank.')
#raise cherrypy.HTTPError(401)
login.exposed = True
# event: log out a user
def logout(self):
# destroy the user's session
cherrypy.session['ID'] = None
cherrypy.session['Username'] = None
cherrypy.session['Permission'] = 3
return self.index()
logout.exposed = True
# event: user pressed search
# this function must be here, otherwise it won't capture the GET requests
def search(self, q = None):
return self.Search.default(q)
search.exposed = True
# Load the config file
conf = os.path.join(os.path.dirname(__file__), 'forum.conf')
# This is how they start the server in the tutorials
if __name__ == '__main__':
cherrypy.quickstart(Forum(), config=conf)
else:
cherrypy.tree.mount(Forum(), config=conf)
| [
[
1,
0,
0.009,
0.009,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.018,
0.009,
0,
0.66,
0.0588,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.027,
0.009,
0,
0.66,
... | [
"import cherrypy",
"import sqlite3",
"import os.path",
"import hashlib",
"import Common",
"import Subforum",
"import Thread",
"import Post",
"import User",
"import Search",
"import Structure",
"import PrivateMessage",
"root_dir = os.path.dirname(os.path.abspath(__file__))",
"def connect(th... |
import sqlite3
import getpass
import hashlib
# Create the connection
connection = sqlite3.connect("forum.db")
cursor = connection.cursor()
# Restore the dump
install_dump = open('install.sql', 'r')
cursor.executescript(install_dump.read())
install_dump.close()
# Add an administrator account
cursor.execute('INSERT INTO User (ID, Username, Password, Permission, JoinDate, Signature) VALUES (0, "Administrator", ?, 0, date(\'now\'),"ADMIN")', (hashlib.md5(getpass.getpass("Enter new administrator password: ")).hexdigest(),))
connection.commit()
# Populate the database if the user wants us to
if raw_input("Populate Database with Sample Data? [y/N]: ").lower() == "y":
populate_dump = open('populate.sql', 'r')
cursor.executescript(populate_dump.read())
populate_dump.close()
connection.commit()
# Otherwise, ask for forum information and create a blank froum
else:
name=raw_input("Forum Name: ")
desc=raw_input("Forum Description: ")
legal=raw_input("Forum Legal info [d=default]: ")
if legal.lower() == "d":
legal = "<br />Copyright 2011: Sean Fox, Mark Schultz, Jacob Snyder <br /> This software is under development. Use at your own risk."
logo=raw_input("Path to forum logo [d=default]: ")
if logo.lower() == "d":
logo = "/images/logos/logo.png"
cursor.execute('INSERT INTO Forum (Name, Description, LegalInfo, Logo) VALUES (?, ?, ?, ?)', (name,desc,legal,logo,))
connection.commit()
print "you entered: "
print name
print desc
print legal
print logo
| [
[
1,
0,
0.025,
0.025,
0,
0.66,
0,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.05,
0.025,
0,
0.66,
0.1,
784,
0,
1,
0,
0,
784,
0,
0
],
[
1,
0,
0.075,
0.025,
0,
0.66,
... | [
"import sqlite3",
"import getpass",
"import hashlib",
"connection = sqlite3.connect(\"forum.db\")",
"cursor = connection.cursor()",
"install_dump = open('install.sql', 'r')",
"cursor.executescript(install_dump.read())",
"install_dump.close()",
"cursor.execute('INSERT INTO User (ID, Username, Passwor... |
import cherrypy
import sqlite3
import time
import Common
class Subforum(Common.Template):
# Call the default function with no arguments
def index(self):
return self.default()
index.exposed = True
# The default view displays a given subforum. If no ID is given, it
# displays the root subforum
def default(self, id = None):
# If no ID is given, we are viewing the root. Set id to NULL for queries
if id == None or id == "None":
id = "NULL"
# Get the subforum name
subforum_name = self.get_subforum_name(id)
if subforum_name == None and id != "NULL":
# The subforum doesn't exist so make an error page
yield self.error("The specified subforum does not exist!", True)
else:
# Print the top of the page
yield self.header(subforum_name)
yield self.links()
yield self.breadcrumbs(SubforumID = id)
# Print the subforum list
yield self.generator_expand(self.subforum_list(id))
# Print the thread list
yield self.generator_expand(self.thread_list(id))
yield self.footer()
default.exposed = True
# This function prints the subforums contained by the parent subforum
def subforum_list(self, id):
cursor = cherrypy.thread_data.db.cursor()
if self.is_parent(id):
yield "<br /><table class='subforum_list' width='100%'>"
yield "<tr><th colspan='3' class='subforum_list'>Subforums</th></tr>"
# This is a "parent" subforum, which means there are subforum beneath it, so list these
cursor.execute("SELECT * FROM Subforum WHERE ParentSubforumID IS ? ORDER BY RelativeOrder", (id,))
for ID, Name, Description, ParentSubforumID, ThreadCount, PostCount, RelativeOrder in cursor.fetchall():
# compile list of moderators for this subforum
modlist = self.getModeratorsOf(ID)
mods = ""
if len(modlist) > 0:
for uid, mod in modlist:
mods += '<a href="/User/%s">%s</a>, ' % (uid, mod)
mods = mods.rstrip(', ')
else:
mods = "<i>None</i>"
# output
yield "<tr>"
yield "<td class='subforum_list'><h2 class='subforum_list'><a href='/Subforum/%s'>%s</a></h2>%s<br />Moderators: %s</td>" % (ID, Name, Description, mods)
yield "<td class='subforum_list' width='100px'>Threads: %s<br />Posts: %s</td>" % (ThreadCount, PostCount)
yield "</tr>"
yield "</table>"
# Returns if a given subforum is a "parent". This is if the subforum has
# subforums beneath it.
def is_parent(self, id):
cursor = cherrypy.thread_data.db.cursor()
# Find children of this subforum
cursor.execute("SELECT * FROM Subforum WHERE ParentSubforumID IS ?", (id,))
for row in cursor:
# There is at least one child, so this is a parent
return True
return False
# This function prints the threads contained by the parent
def thread_list(self, id):
cursor = cherrypy.thread_data.db.cursor()
yield "<p align='right'> "
# If a user is logged in, show the new thread button
if self.getLoginPermission() <= 2:
yield "<a href='/Thread/New/%s'>New Thread</a>" % id
yield " </p>"
# Make a table across the screen
yield "<table class='thread_list' width='100%'>"
yield "<tr><th colspan='3' class='thread_list'>Threads</th></tr>"
# Get the threads in the current subforum. Sort them by decreasing ID of their latest post (chronological)
cursor.execute('''
SELECT
Thread.ID, Post.Title, User.ID, User.Username, Post.Timestamp, Thread.PostCount, Thread.ViewCount, Thread.Sticky, Thread.Closed, Post2.ID, Post2.Title, Post2.Content, User2.ID, User2.Username, Post2.Timestamp
FROM
Post, Thread, User, Post Post2, User User2,
(SELECT ThreadID, MIN(Post.ID) AS MinPostID, MAX(Post.ID) AS MaxPostID
FROM Post
GROUP BY ThreadID) Times
WHERE
Thread.ID = Times.ThreadID AND
Post.ID = Times.MinPostID AND
Post.UserID = User.ID AND
Thread.SubforumID IS ? AND
Post2.ID = Times.MaxPostID AND
Post2.UserID = User2.ID
ORDER BY
Thread.Sticky DESC, Times.MaxPostID DESC
''', (id,))
# Print the thread
count = 0
for ID, Title, UserID, Username, Timestamp, PostCount, ViewCount, Sticky, Closed, PostID, PostTitle, PostContent, PostUserID, PostUsername, PostTimestamp in cursor.fetchall():
if Sticky == 1:
Title += " - STICKY"
if Closed == 1:
Title += " - CLOSED"
yield "<tr>"
yield "<td class='thread_list'><h2 class='thread_list'><a href='/Thread/%s'>%s</a></h2>Started by <a href='/User/%s'>%s</a> on %s</td>" % (ID, Title, UserID, Username, time.strftime("%c", time.localtime(Timestamp)))
yield "<td class='thread_list' width='100px'>Replies: %s<br />Views: %s<br /></td>" % (PostCount, ViewCount)
if PostTitle == None or PostTitle == "":
blurb = PostContent
else:
blurb = PostTitle
if len(blurb) > 18:
blurb = "%s%s" % (blurb[0:18], "...")
yield "<td class='thread_list' width='200px'><a href='/Thread/%s#%s'>%s</a><br /><a href='/User/%s'>%s</a><br />%s</td>" % (ID, PostID, blurb, PostUserID, PostUsername, time.strftime("%c", time.localtime(PostTimestamp)))
count += 1
if count == 0:
yield "<tr><td class='thread_list' colspan='3'><i>There are no threads here</i></td></tr>"
yield "</table>"
| [
[
1,
0,
0.0072,
0.0072,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0144,
0.0072,
0,
0.66,
0.25,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0216,
0.0072,
0,
0.... | [
"import cherrypy",
"import sqlite3",
"import time",
"import Common",
"class Subforum(Common.Template):\n\t# Call the default function with no arguments\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\n\t# The default view displays a given subforum. If no ID is given, it \n\t# displ... |
import cherrypy
import sqlite3
import time
import re
# central base class that other pages inherit
class Template:
# header includes the logo and login/register form
def header(self, title=None):
if title:
title = "%s - %s" % (title,self.getForumName())
else:
title = "%s" % self.getForumName()
out = '''
<html>
<head>
<title>%s</title>
''' % title
out += '''
<link rel="stylesheet" type="text/css" href="/style.css" />
</head>
<body>
<table width='100%' height='100px'>
<tr id="header" valign='top'>
<td id="logo">
<a href="/"><h1>''' + self.getForumName() + '''</h1></a>''' + self.getForumDescription() + '''
</td>
<td id="logo">'''
if not (self.getForumLogo() == "" or self.getForumLogo() == None):
out += '''<img src="''' + self.getForumLogo() + '''" alt="No Logo"></img>'''
out+='''</td>
<td id="login" align="right">
'''
# if the user is logged in
if self.getLoginID() != None:
# display their username and a logout button
out += '''Welcome, <a href="/User/%d">%s</a><br><br />
<form method='post' action="/logout">
<input type="submit" value="Logout"></input>
</form>
''' % (self.getLoginID(), self.getLoginUsername())
else:
# display the login/register form
out += '''
<form method=post action="/login">
Username: <input name="user" type="text"></input>
<br>
Password: <input name="passwd" type="password"></input>
<br>
<input type="submit" value="Login"></input>
<input type="submit" name="reg" value="Register"></input>
</form>
'''
out += '''
</td>
</tr>
</table>
'''
return out
# The useful links section has the user list, PMs, and admin functions
# links depending onthe currently logged in user's permissions
def links(self):
out = '''
<table width='100%'>
<tr valign='top'>
<td id="links">
'''
out += '''Useful links: '''
out += '''<a href="/User">User List</a>'''
# display private message link if they're logged in
if self.getLoginID() != None:
out += ''' | <a href="/PrivateMessage">Private Messages</a>'''
# if the user is logged in as an admin
if self.getLoginPermission() == 0:
# link to admin functions
out += ''' | Administrator functions: <a href="/Structure">Modify forum structure</a>'''
out += '''
</td>
<td width=30% align="right">
<form method=get action="/search">
<input name="q" type="text"></input><input type="submit" value="Search"></input>
</form>
</td>
</tr>
</table>
'''
return out
# breadcrumbs section
#
# breadcrumbs are the directory-like path to where the user is looking.
# There are multiple arguments to this function. Only set one. They are
# self-explanatory, just set the ID for the view you're in and you're set.
def breadcrumbs(self, ThreadID = None, SubforumID = None):
cursor = cherrypy.thread_data.db.cursor()
breadcrumb = ""
# Thread is set, so the thread is at the end of the breadcrumb
if ThreadID != None:
# Get the thread's name and the subforum it's in
cursor.execute('''
SELECT Post.Title, Thread.SubforumID
FROM
Post, Thread,
(SELECT ThreadID, MIN(Post.ID) AS MinPostID
FROM Post
GROUP BY ThreadID) Time
WHERE
Time.ThreadID = %s AND
Thread.ID = Time.ThreadID AND
Time.MinPostID = Post.ID
''' % ThreadID)
thread = cursor.fetchone()
thread_name = thread[0]
if self.Thread_Closed(ThreadID):
thread_name += " - CLOSED"
# Put the thread at the end of the breadcrumb
breadcrumb = " > <a href='/Thread/%s'>%s</a> %s" % (ThreadID, thread_name, breadcrumb)
# Set the SubforumID to generate the rest of the path in the next loop
SubforumID = thread[1]
# Subforum ID is set, so generate the path up to the root
while SubforumID != "NULL" and SubforumID != None:
# Get the Name of this subforum and the parent's ID
cursor.execute("SELECT Name, ParentSubforumID FROM Subforum WHERE ID IS ?", (SubforumID,))
row = cursor.fetchone()
# Add this subforum to the breadcrumb
breadcrumb = " > <a href='/Subforum/%s'>%s</a> %s" % (SubforumID, row[0], breadcrumb)
SubforumID = row[1]
# Print the forum root in the breadcrumb
breadcrumb = "> <a href='/Subforum'>%s</a> %s<br />" % (self.getForumName(), breadcrumb)
return breadcrumb
# This function expands generators. This is needed if a function is
# yielding a value from a function that yields a value. Sometimes. Yields
# behave wieredly.
def generator_expand(self, generator):
out = ""
for item in generator:
out = "%s%s" % (out, item)
return out
# display an error page with a custom message
def error(self, msg = 'Unknown Error', severe = False):
out = self.header('Error')
out += self.links()
out += self.breadcrumbs()
if severe:
# red text is severe!
out += '<font color="red">'
out += '<h2>%s</h2>' % msg
if severe:
out += '</font>'
out += self.footer()
return out
# static footer
def footer(self):
out = "<p align='center'>%s</div>"%self.getForumLegal()
return out
# Returns name/ title of forum
def getForumName(self):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Name from Forum")
name = cursor.fetchone()
print "name: %s" % name
if name != None:
return name[0]
else:
return "Default Forum"
# Return description of forum
def getForumDescription(self):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Description from Forum")
name = cursor.fetchone()
if name != None:
return name[0]
else:
return "Default Forum Info"
# Return the legal info for the footer
def getForumLegal(self):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT LegalInfo from Forum")
name = cursor.fetchone()
if name != None:
return name[0]
else:
return "Default Forum Info"
# Return the path to the forum logo
def getForumLogo(self):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Logo from Forum")
name = cursor.fetchone()
if name != None:
return name[0]
else:
return ""
# Returns the currently logged in user or None
def getLoginID(self):
return cherrypy.session.get('ID', None)
# Returns the currently logged in user's name or None
def getLoginUsername(self):
return cherrypy.session.get('Username', None)
# Returns user info
def getUserInfo(self, id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT * FROM User WHERE ID IS ?", (id,))
return cursor.fetchall()
# Returns username of particular userid
def getUsername(self, id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Username FROM User WHERE ID IS ?", (id,))
uname=cursor.fetchone()
if uname != None:
return uname[0]
else:
return None
# Returns the currently logged in permission (3 if guest)
def getLoginPermission(self):
return cherrypy.session.get('Permission', 3)
# This returns the name of the current subforum given its id
def get_subforum_name(self, id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Name FROM Subforum WHERE ID IS ?", (id,))
subforum = cursor.fetchone()
if subforum != None:
return subforum[0]
else:
return None
# return a list of (id, name) tuples of moderators for a given a subforum id
def getModeratorsOf(self, SubforumID = "NULL"):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute('''
SELECT
User.ID, User.Username
FROM
User, Moderator
WHERE
User.Permission = 1 AND
User.ID = Moderator.UserID AND
Moderator.SubforumID IS ?
''', (SubforumID,))
return cursor.fetchall()
# does the user have moderator permissions on the given thread?
def hasPermission(self, ThreadID):
p = self.getLoginPermission()
if p == 3:
# they are a guest, of course not
return False
if p == 0:
# they are an admin, of course they do
return True
# otherwise, they're a moderator
cursor = cherrypy.thread_data.db.cursor()
# check if this user id is a mod of this subforum
cursor.execute('''
SELECT
Moderator.UserID
FROM
Thread, Moderator
WHERE
Thread.ID IS ? AND
Thread.SubforumID = Moderator.SubforumID
''', (ThreadID,))
uids = cursor.fetchall()
if len(uids) > 0:
id = self.getLoginID()
for uid in uids:
if id == uid[0]:
return True
return False
else:
return False
# return the date a ban will be lifted, or None
# unlift the ban if it has expired
def banCheck(self, uid):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute('''SELECT BanTimestamp FROM User WHERE ID IS ?''', (uid,))
ts = cursor.fetchone()
if ts == None:
return None
ts = ts[0]
if ts == 0:
# permaban
return "never"
if time.time() > ts:
# ban expired, lift it
cursor.execute('''UPDATE User SET BanTimestamp = NULL WHERE ID IS ?''', (uid,))
cherrypy.thread_data.db.commit()
return None
print type(ts)
return time.ctime(ts)
# get the ID of a thread containing a given post ID
def getThreadID(self, postID):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute('''
SELECT
ThreadID
FROM
Post
WHERE
ID = ?
''', (postID,))
threadID = cursor.fetchone()
if threadID:
return threadID[0]
else:
return None
# This returns the name of the current thread given its id
def get_thread_name(self, id):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute('''
SELECT Post.Title
FROM
Post, Thread,
(SELECT ThreadID, MIN(Post.ID) AS MinPostID
FROM Post
GROUP BY ThreadID) Time
WHERE
Time.ThreadID = ? AND
Thread.ID = Time.ThreadID AND
Time.MinPostID = Post.ID
''', (id,))
thread = cursor.fetchone()
if thread != None:
return thread[0]
else:
return None
# This generates a simple HTML document that will redirect to a given URL.
# Note that this does not actually redirect; callers of this funciton will
# have to manually return / yield this
def redirect(self, path):
return "<html><head><meta HTTP-EQUIV='REFRESH' content=\"0; url=%s\"></head></html>" % path
def Thread_Closed(self, threadid):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT Thread.Closed FROM Thread WHERE Thread.ID = ?", (threadid,))
Closed = cursor.fetchone()[0]
return Closed == 1
def strip_html_bbcode(self, string):
p = re.compile("<.*?>")
q = re.compile("\[.*?\]")
return p.sub("", q.sub("", string))
| [
[
1,
0,
0.0027,
0.0027,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0054,
0.0027,
0,
0.66,
0.25,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.008,
0.0027,
0,
0.6... | [
"import cherrypy",
"import sqlite3",
"import time",
"import re",
"class Template:\n\t# header includes the logo and login/register form\n\tdef header(self, title=None):\n\t\tif title:\n\t\t\ttitle = \"%s - %s\" % (title,self.getForumName())\n\t\telse:\n\t\t\ttitle = \"%s\" % self.getForumName()\n\t\tout = '... |
import cherrypy
import sqlite3
import time
import Common
from postmarkup import render_bbcode
class Search(Common.Template):
def index(self):
return self.default()
index.exposed = True
def default(self, q = None):
# if the user didn't search for anything
if q is None or q == '':
# return an error
yield self.error('Please enter valid search terms.')
else:
# build a query from the search terms
expr = '''
SELECT
Post.ID, Post.Title, Post.Content, Post.Timestamp, User.ID, User.Username, User.Permission, User.Avatar, User.Signature, Post.EditTimestamp, Post.EditUserID
FROM
Post, User
WHERE
User.ID = Post.UserID AND
'''
# place ANDs between each term
for term in q.split(' '):
expr += '''
Post.Content like "%''' + term + '''%" AND
'''
expr = expr.rstrip('\n\tAND') + '''
ORDER BY
Post.EditTimestamp DESC
'''
cursor = cherrypy.thread_data.db.cursor()
cursor.execute(expr)
# return the search results
res = cursor.fetchall()
yield self.header()
yield self.links()
yield self.breadcrumbs()
yield '<h2>Search Results for "%s"</h2>' % q
# if there are no results
if len(res) == 0:
yield '<p>No results.</p>'
else:
# copied with modifications from Thread.py
count = 1
permissions = ["Administrator", "Moderator", "Member"]
for ID, Title, Content, Timestamp, UserID, Username, Permission, Avatar, Signature, EditTimestamp, EditUserID in res:
# link in corner takes the user to the actual thread and post
tid = self.getThreadID(ID)
yield "<table width='100%' cols='2' class='thread' >"
yield "<tr>"
yield "<td class='thread' colspan='2'><a name='%s'></a>%s <span style='float:right; text-align: right;'><a href='/Thread/%s#%s'>#%s</a></span></td>" % (ID, Title, tid, ID, count)
yield "</tr>"
yield "<tr>"
if Avatar == "" or Avatar == None:
yield "<td class='thread' rowspan='3' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><div width='100px' height='100px'> </div></td><td class='thread' height='75px' >%s</td>" % (UserID, Username, permissions[Permission], render_bbcode(Content))
else:
yield "<td class='thread' rowspan='3' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><img src='/%s' width='100px' height='100px' /></td><td class='thread' height='75px' >%s</td>" % (UserID, Username, permissions[Permission], Avatar, render_bbcode(Content))
yield "</tr>"
yield "<tr>"
yield "<td class='thread'>%s</td>" % render_bbcode(Signature)
yield "</tr>"
yield "<tr>"
if EditTimestamp == None:
# post wasn't edited
yield "<td class='thread'>Posted on %s</td>" % time.strftime("%c", time.localtime(Timestamp))
else:
# show the username of the post editor
c = cherrypy.thread_data.db.cursor()
c.execute('''SELECT User.Username FROM User WHERE User.ID = ?''', (EditUserID,))
EditUsername = c.fetchone()[0]
yield "<td class='thread'>Posted on %s, Last Edited on %s by %s</td>" % (time.strftime("%c", time.localtime(Timestamp)), time.strftime("%c", time.localtime(EditTimestamp)), EditUsername)
yield "</tr>"
yield "</table>"
yield "<br />"
count = count + 1
yield self.footer()
default.exposed = True
| [
[
1,
0,
0.0118,
0.0118,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0235,
0.0118,
0,
0.66,
0.2,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0353,
0.0118,
0,
0.6... | [
"import cherrypy",
"import sqlite3",
"import time",
"import Common",
"from postmarkup import render_bbcode",
"class Search(Common.Template):\n\t\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\t\t\n\tdef default(self, q = None):\n\t\t# if the user didn't search for anything",
"\... |
import cherrypy
import sqlite3
import time
import Common
# restructure the forum
class Structure(Common.Template):
# Call the default function with no arguments
def index(self):
return self.default()
index.exposed = True
# This function is the default view for the restructure view and shows the
# subforum tree along with all of the commands for each subforum
def default(self):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
else:
# display the current forum structure
yield self.header("Restructure")
yield self.links()
yield self.breadcrumbs()
# Print the tree
yield self.Tree()
yield self.footer()
# This function is recursively called by default to build the subforum Tree.
# It continualy builds nested unordered (bulleted) lists.
def Tree(self, id = "NULL"):
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT ID, Name FROM Subforum WHERE ParentSubforumID IS ? ORDER BY RelativeOrder", (id,))
out = ""
for ID, Name in cursor.fetchall():
out += "<li>"
out += Name + " (<a href='AddSub/%s'>Add Subforum</a> | <a href='Relocate/%s'>Relocate</a> | <a href='Delete/%s'>Delete</a> | <a href='EditMod/%s'>Edit Moderators</a> | <a href='Up/%s'>Up</a> | <a href='Down/%s'>Down</a> | <a href='Top/%s'>Top</a> | <a href='Bottom/%s'>Bottom</a>)" % (ID, ID, ID, ID, ID, ID, ID, ID)
out += "</li>"
out += self.Tree(ID)
if out != "":
out = "<ul>" + out + "</ul>"
if id == "NULL":
out = "<ul><li><i>Forum Root</i> (<a href='AddSub/NULL'>Add Subforum</a> | <font style='color: gray'><u>Relocate</u></font> | <font style='color: gray'><u>Delete</u></font> | <a href='EditMod/NULL'>Edit Moderators</a> | <font style='color: gray'><u>Up</u></font> | <font style='color: gray'><u>Down</u></font> | <font style='color: gray'><u>Top</u></font> | <font style='color: gray'><u>Bottom</u></font>)</li>" + out + "</ul>"
return out
#[todo] Add more robust error-checking.
def EditMod(self, ForumID, ModList = None):
# figure out the subforum name
name = self.get_subforum_name(ForumID)
if name == None and ForumID == "NULL":
name = "Forum Root"
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif name == "Forum Root" and ForumID != "NULL":
# The thread is not found, so error
yield self.error('Specified subforum not found.')
elif ModList == None:
# get list of mods for the subforum
cursor = cherrypy.thread_data.db.cursor()
cursor.execute('''
SELECT
User.Username
FROM
User, Moderator
WHERE
User.Permission = 1 AND
User.ID = Moderator.UserID AND
Moderator.SubforumID IS ?
''', (ForumID,))
mods = ""
for mod in cursor.fetchall():
mods += mod[0] + "\n"
# display moderator entry form
yield self.header("Edit Moderators")
yield self.links()
yield self.breadcrumbs()
yield '''
<form method="post" action="%s">
<h2>Moderator List for "%s"</h2>
Please enter one username per line:<br /><br />
<textarea class="monospace" type="text" name="ModList" rows="8" cols="40">%s</textarea><br />
<input type="submit" value="Update" />
</form>
''' % (ForumID, name, mods)
yield self.footer()
else:
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
# get a list of the old mod's user ids
cursor.execute('''
SELECT
User.ID
FROM
User, Moderator
WHERE
User.Permission = 1 AND
User.ID = Moderator.UserID AND
Moderator.SubforumID IS ?
''', (ForumID,))
oldmods = cursor.fetchall()
# format old mod ids into a query
if len(oldmods) > 0:
old = ""
for uid in oldmods:
old += '''ID = %s OR ''' % uid
old = old.rstrip(' OR')
# remove all moderators for this subforum
cursor.execute('''UPDATE User SET Permission = 2 WHERE %s''' % old)
cherrypy.thread_data.db.commit()
cursor.execute('''DELETE FROM Moderator WHERE SubforumID IS ?''', (ForumID,))
cherrypy.thread_data.db.commit()
# format the moderator list into a query
mods = ""
ModList = list(set([mod.rstrip() for mod in ModList.split("\n") if mod.strip() != '']))
for mod in ModList:
mods += '''Username LIKE "%s" OR ''' % mod
mods = mods.rstrip(' OR')
# get the new mod's user ids
cursor.execute('''SELECT ID FROM User WHERE %s''' % mods)
ModList = cursor.fetchall()
# add the new list of moderators for this subforum
cursor.execute('''UPDATE User SET Permission = 1 WHERE %s''' % mods)
cherrypy.thread_data.db.commit()
for uid in ModList:
cursor.execute('''INSERT INTO Moderator VALUES (%s,%s)''' % (uid[0], ForumID))
# commit changes
cherrypy.thread_data.db.commit()
# display success message
yield self.redirect("/Structure")
EditMod.exposed = True
# This function is the add subforum form. If the Name and Description args
# are not given, then the form to create the subforum is showed. If they
# are set, then the given subforum is created benesath the Parent subforum
def AddSub(self, ParentID, Name = None, Description = None):
cursor = cherrypy.thread_data.db.cursor()
# Determine if the given subforum has child threads
cursor.execute("SELECT * FROM Thread WHERE Thread.SubforumID IS ?", (ParentID,))
hasthreads = cursor.fetchone() != None
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(ParentID) == None and ParentID != "NULL":
# The thread is not found, so error
yield self.error('Specified subforum not found.')
elif Name == None or Name == "":
# There is no name given, so show the create form
yield self.header("Add Subforum")
yield self.links()
yield self.breadcrumbs()
yield "<form method='post' action='%s'>" % ParentID
yield "Subforum Name: <br />"
yield "<input class='monospace' type='text' name='Name' size='60' /><br />"
yield "Description: <br />"
yield "<textarea class='monospace' name='Description' rows='3' cols='80'></textarea><br />"
yield "<input type='submit' value='New Subforum' />"
yield "</form>"
yield self.footer()
else:
# Get the largest relative order value in this subforum. If there are
# no subforums, set it to 0
cursor.execute("SELECT MAX(Subforum.RelativeOrder) FROM Subforum WHERE Subforum.ParentSubforumID IS ?", (ParentID,))
max = cursor.fetchone()[0]
if max == None:
order = 0
else:
order = max + 1
# Create the new subforum. Recursive triggers are not needed in this case
cursor.execute('''
INSERT INTO Subforum (ID, Name, Description, ParentSubforumID, ThreadCount, PostCount, RelativeOrder)
VALUES (NULL, ?, ?, ?, 0, 0, ?)
''', (Name, Description, ParentID, order,))
cherrypy.thread_data.db.commit()
# Return to the restructure page
yield self.redirect("/Structure")
AddSub.exposed = True
# This function moves a subforum underneath a new parent. If NewParentID
# is not set, it shows the form, otherwise, it moves the subforum
def Relocate(self, id, NewParentID = None):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(id) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
elif NewParentID == None or id == NewParentID:
# The new parent is not valid, so show the form
yield self.header("Relocate Subforum")
yield self.links()
yield self.breadcrumbs()
yield "<p>"
yield "<form method='post' action='%s'>" % id
# Show the subforum tree
yield self.RelocateTree()
yield "<br /><br /><input type='submit' value='Move Subforum' />"
yield "</form>"
yield "</p>"
yield self.footer()
else:
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
# Movethe subforum to the new parent
cursor.execute("UPDATE Subforum SET ParentSubforumID = ? WHERE ID = ?", (NewParentID, id,))
cherrypy.thread_data.db.commit()
# Move this subforum to the bottom of the subforum
self.Bottom(id)
yield self.redirect("/Structure")
Relocate.exposed = True
# This function creates the drop down tree structure of the subforum tree.
# Depth is acutally a string of mdashes that is added to at each level
def RelocateTree(self, id = "", depth = ""):
if id == "" and depth == "":
# This is the root, so make the root node and then recursively call self
out = "<select name='NewParentID'><option value='NULL' style='font-style: italic;'>(Forum Root)</option>" + self.RelocateTree("NULL", "—") + "</select>"
else:
# Get all of the children of the given parent and then recursively call RelocateTree
cursor = cherrypy.thread_data.db.cursor()
cursor.execute("SELECT ID, Name FROM Subforum WHERE ParentSubforumID IS ?", (id,))
out = ""
for ID, Name in cursor.fetchall():
out += "<option value='%s'>%s%s</option>" % (ID, depth, Name)
out += self.RelocateTree(ID, depth + "—")
return out
# This deletes a given subforum and in turn all of its containing subforums,
# threads, and posts via triggers
def Delete(self, id):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(id) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
else:
cursor = cherrypy.thread_data.db.cursor()
# This PRAGMA is needed to ensure recursive triggers work
cursor.execute("PRAGMA recursive_triggers = 1;")
cherrypy.thread_data.db.commit()
cursor.execute("DELETE FROM Subforum WHERE ID = ?", (id,))
cherrypy.thread_data.db.commit()
# Triggers will delete subforums, threads, posts and update post/thread counts
yield self.redirect("/Structure")
Delete.exposed = True
# This moves a given subforum to the top of the ordering in the given
# subforum by setting its order to one less than the minimum in that
# subforum
def Top(self, id):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(id) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
else:
cursor = cherrypy.thread_data.db.cursor()
# Get the minimum subforum in that subforum
cursor.execute("SELECT MIN(Subforum.RelativeOrder) FROM Subforum WHERE Subforum.ParentSubforumID IS (SELECT Subforum.ParentSubforumID FROM Subforum WHERE Subforum.ID = ?)", (id,))
# Change the given subforum's order
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", ((cursor.fetchone()[0] - 1), id,))
cherrypy.thread_data.db.commit()
yield self.redirect("/Structure")
Top.exposed = True
# This moves a given subforum to the bottom of the ordering in the given
# subforum by setting its order to one more than the maximum in that
# subforum
def Bottom(self, id):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(id) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
else:
cursor = cherrypy.thread_data.db.cursor()
# Get the maximum subforum in that subforum
cursor.execute("SELECT MAX(Subforum.RelativeOrder) FROM Subforum WHERE Subforum.ParentSubforumID IS (SELECT Subforum.ParentSubforumID FROM Subforum WHERE Subforum.ID = ?)", (id,))
# Change the given subforum's order
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", ((cursor.fetchone()[0] + 1), id,))
cherrypy.thread_data.db.commit()
yield self.redirect("/Structure")
Bottom.exposed = True
# This function moves a given subforum down. To do this, it swaps its order
# with the subforum "below" it
def Down(self, MoveDownID):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(MoveDownID) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
else:
cursor = cherrypy.thread_data.db.cursor()
# Get this subforum's relative order
cursor.execute("SELECT Subforum.RelativeOrder FROM Subforum WHERE Subforum.ID = ?", (MoveDownID,))
MoveDownOrder = cursor.fetchone()[0]
# Get the ID and Relative order of the subforum below this
cursor.execute('''
SELECT Subforum.ID, Subforum.RelativeOrder
FROM Subforum
WHERE Subforum.RelativeOrder IS
(
SELECT MIN(Subforum.RelativeOrder)
FROM Subforum
WHERE
Subforum.ParentSubforumID IS
(
SELECT Subforum.ParentSubforumID
FROM Subforum
WHERE Subforum.ID = ?
)
AND
Subforum.RelativeOrder >
(
SELECT Subforum.RelativeOrder
FROM Subforum
WHERE Subforum.ID = ?
)
)
AND Subforum.ParentSubforumID IS
(
SELECT Subforum.ParentSubforumID
FROM Subforum
WHERE Subforum.ID = ?
)
''', (MoveDownID, MoveDownID, MoveDownID,))
result = cursor.fetchone()
if result != None:
(MoveUpID, MoveUpOrder) = result
# Swap the orders
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", (MoveDownOrder,MoveUpID,))
cherrypy.thread_data.db.commit()
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", (MoveUpOrder,MoveDownID,))
cherrypy.thread_data.db.commit()
yield self.redirect("/Structure")
Down.exposed = True
# This function moves a given subforum up. To do this, it swaps its order
# with the subforum "above" it
def Up(self, MoveUpID):
if self.getLoginPermission() != 0:
# Not an admin, error
yield self.error('You do not have permission to view this page!', True)
elif self.get_subforum_name(MoveUpID) == None:
# The thread is not found, so error
yield self.error('Specified subforum not found.')
else:
cursor = cherrypy.thread_data.db.cursor()
# Get this subforum's relative order
cursor.execute("SELECT Subforum.RelativeOrder FROM Subforum WHERE Subforum.ID = ?", (MoveUpID,))
MoveUpOrder = cursor.fetchone()[0]
# Get the ID and Relative order of the subforum above this
cursor.execute('''
SELECT Subforum.ID, Subforum.RelativeOrder
FROM Subforum
WHERE Subforum.RelativeOrder IS
(
SELECT MAX(Subforum.RelativeOrder)
FROM Subforum
WHERE
Subforum.ParentSubforumID IS
(
SELECT Subforum.ParentSubforumID
FROM Subforum
WHERE Subforum.ID = ?
)
AND
Subforum.RelativeOrder <
(
SELECT Subforum.RelativeOrder
FROM Subforum
WHERE Subforum.ID = ?
)
)
AND Subforum.ParentSubforumID IS
(
SELECT Subforum.ParentSubforumID
FROM Subforum
WHERE Subforum.ID = ?
)
''', (MoveUpID, MoveUpID, MoveUpID,))
result = cursor.fetchone()
if result != None:
(MoveDownID, MoveDownOrder) = result
# Swap the orders
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", (MoveDownOrder,MoveUpID,))
cherrypy.thread_data.db.commit()
cursor.execute("UPDATE Subforum SET RelativeOrder = ? WHERE ID = ?", (MoveUpOrder,MoveDownID,))
cherrypy.thread_data.db.commit()
yield self.redirect("/Structure")
Up.exposed = True
| [
[
1,
0,
0.0022,
0.0022,
0,
0.66,
0,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.0044,
0.0022,
0,
0.66,
0.25,
790,
0,
1,
0,
0,
790,
0,
0
],
[
1,
0,
0.0066,
0.0022,
0,
0.... | [
"import cherrypy",
"import sqlite3",
"import time",
"import Common",
"class Structure(Common.Template):\n\t# Call the default function with no arguments\n\tdef index(self):\n\t\treturn self.default()\n\tindex.exposed = True\n\t\n\t# This function is the default view for the restructure view and shows the \n... |
import sqlite3 as sql
conn = sql.connect('sample.db')
curs = conn.cursor()
# Create Item table
curs.execute('''create table item
(id integer primary key, itemno text unique,
scancode text, descr text, price real)''')
curs.execute("insert into item values\
(NULL,0001,32187645,'Milk',2.50)")
curs.execute("insert into item values\
(NULL,0002,45321876,'Beer',4.50)")
curs.execute("insert into item values\
(NULL,0003,18764532,'Bread',1.50)")
conn.commit()
curs.execute("select * from item")
for row in curs:
print row
curs.execute('''create table itemvendor
(id integer primary key, itemno text, vendor text)''')
curs.execute("insert into itemvendor values\
(NULL,0001,2345)")
curs.execute("insert into itemvendor values\
(NULL,0002,6789)")
curs.execute("insert into itemvendor values\
(NULL,0001,0543)")
conn.commit()
curs.execute("select * from item, itemvendor WHERE item.itemno = itemvendor.itemno")
for row in curs:
print row
| [
[
1,
0,
0.0278,
0.0278,
0,
0.66,
0,
790,
0,
1,
0,
0,
790,
0,
0
],
[
14,
0,
0.0833,
0.0278,
0,
0.66,
0.0625,
345,
3,
1,
0,
0,
242,
10,
1
],
[
14,
0,
0.1111,
0.0278,
0,
... | [
"import sqlite3 as sql",
"conn = sql.connect('sample.db')",
"curs = conn.cursor()",
"curs.execute('''create table item\n (id integer primary key, itemno text unique,\n scancode text, descr text, price real)''')",
"curs.execute(\"insert into item values\\\n (NULL,0001,32187645,'Milk',2.50)... |
"""
Tutorial - Multiple objects
This tutorial shows you how to create a site structure through multiple
possibly nested request handler objects.
"""
import cherrypy
class HomePage:
def index(self):
return '''
<p>Hi, this is the home page! Check out the other
fun stuff on this site:</p>
<ul>
<li><a href="/joke/">A silly joke</a></li>
<li><a href="/links/">Useful links</a></li>
</ul>'''
index.exposed = True
class JokePage:
def index(self):
return '''
<p>"In Python, how do you create a string of random
characters?" -- "Read a Perl file!"</p>
<p>[<a href="../">Return</a>]</p>'''
index.exposed = True
class LinksPage:
def __init__(self):
# Request handler objects can create their own nested request
# handler objects. Simply create them inside their __init__
# methods!
self.extra = ExtraLinksPage()
def index(self):
# Note the way we link to the extra links page (and back).
# As you can see, this object doesn't really care about its
# absolute position in the site tree, since we use relative
# links exclusively.
return '''
<p>Here are some useful links:</p>
<ul>
<li><a href="http://www.cherrypy.org">The CherryPy Homepage</a></li>
<li><a href="http://www.python.org">The Python Homepage</a></li>
</ul>
<p>You can check out some extra useful
links <a href="./extra/">here</a>.</p>
<p>[<a href="../">Return</a>]</p>
'''
index.exposed = True
class ExtraLinksPage:
def index(self):
# Note the relative link back to the Links page!
return '''
<p>Here are some extra useful links:</p>
<ul>
<li><a href="http://del.icio.us">del.icio.us</a></li>
<li><a href="http://www.mornography.de">Hendrik's weblog</a></li>
</ul>
<p>[<a href="../">Return to links page</a>]</p>'''
index.exposed = True
# Of course we can also mount request handler objects right here!
root = HomePage()
root.joke = JokePage()
root.links = LinksPage()
# Remember, we don't need to mount ExtraLinksPage here, because
# LinksPage does that itself on initialization. In fact, there is
# no reason why you shouldn't let your root object take care of
# creating all contained request handler objects.
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(root, config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(root, config=tutconf)
| [
[
8,
0,
0.0357,
0.0612,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0816,
0.0102,
0,
0.66,
0.0909,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.1633,
0.1122,
0,
0.66... | [
"\"\"\"\nTutorial - Multiple objects\n\nThis tutorial shows you how to create a site structure through multiple\npossibly nested request handler objects.\n\"\"\"",
"import cherrypy",
"class HomePage:\n def index(self):\n return '''\n <p>Hi, this is the home page! Check out the other\n ... |
"""
Tutorial: HTTP errors
HTTPError is used to return an error response to the client.
CherryPy has lots of options regarding how such errors are
logged, displayed, and formatted.
"""
import os
localDir = os.path.dirname(__file__)
curpath = os.path.normpath(os.path.join(os.getcwd(), localDir))
import cherrypy
class HTTPErrorDemo(object):
# Set a custom response for 403 errors.
_cp_config = {'error_page.403' : os.path.join(curpath, "custom_error.html")}
def index(self):
# display some links that will result in errors
tracebacks = cherrypy.request.show_tracebacks
if tracebacks:
trace = 'off'
else:
trace = 'on'
return """
<html><body>
<p>Toggle tracebacks <a href="toggleTracebacks">%s</a></p>
<p><a href="/doesNotExist">Click me; I'm a broken link!</a></p>
<p><a href="/error?code=403">Use a custom error page from a file.</a></p>
<p>These errors are explicitly raised by the application:</p>
<ul>
<li><a href="/error?code=400">400</a></li>
<li><a href="/error?code=401">401</a></li>
<li><a href="/error?code=402">402</a></li>
<li><a href="/error?code=500">500</a></li>
</ul>
<p><a href="/messageArg">You can also set the response body
when you raise an error.</a></p>
</body></html>
""" % trace
index.exposed = True
def toggleTracebacks(self):
# simple function to toggle tracebacks on and off
tracebacks = cherrypy.request.show_tracebacks
cherrypy.config.update({'request.show_tracebacks': not tracebacks})
# redirect back to the index
raise cherrypy.HTTPRedirect('/')
toggleTracebacks.exposed = True
def error(self, code):
# raise an error based on the get query
raise cherrypy.HTTPError(status = code)
error.exposed = True
def messageArg(self):
message = ("If you construct an HTTPError with a 'message' "
"argument, it wil be placed on the error page "
"(underneath the status line by default).")
raise cherrypy.HTTPError(500, message=message)
messageArg.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HTTPErrorDemo(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(HTTPErrorDemo(), config=tutconf)
| [
[
8,
0,
0.0617,
0.1111,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1358,
0.0123,
0,
0.66,
0.125,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.1481,
0.0123,
0,
0.66... | [
"\"\"\"\n\nTutorial: HTTP errors\n\nHTTPError is used to return an error response to the client.\nCherryPy has lots of options regarding how such errors are\nlogged, displayed, and formatted.",
"import os",
"localDir = os.path.dirname(__file__)",
"curpath = os.path.normpath(os.path.join(os.getcwd(), localDir)... |
"""
Tutorial - Hello World
The most basic (working) CherryPy application possible.
"""
# Import CherryPy global namespace
import cherrypy
class HelloWorld:
""" Sample request handler class. """
def index(self):
# CherryPy will call this method for the root URI ("/") and send
# its return value to the client. Because this is tutorial
# lesson number 01, we'll just send something really simple.
# How about...
return "Hello world!"
# Expose the index method through the web. CherryPy will never
# publish methods that don't have the exposed attribute set to True.
index.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(HelloWorld(), config=tutconf)
| [
[
8,
0,
0.0857,
0.1429,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2286,
0.0286,
0,
0.66,
0.2,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.4571,
0.3714,
0,
0.66,
... | [
"\"\"\"\nTutorial - Hello World\n\nThe most basic (working) CherryPy application possible.\n\"\"\"",
"import cherrypy",
"class HelloWorld:\n \"\"\" Sample request handler class. \"\"\"\n\n def index(self):\n # CherryPy will call this method for the root URI (\"/\") and send\n # its return va... |
'''
Bonus Tutorial: Using SQLObject
This is a silly little contacts manager application intended to
demonstrate how to use SQLObject from within a CherryPy2 project. It
also shows how to use inline Cheetah templates.
SQLObject is an Object/Relational Mapper that allows you to access
data stored in an RDBMS in a pythonic fashion. You create data objects
as Python classes and let SQLObject take care of all the nasty details.
This code depends on the latest development version (0.6+) of SQLObject.
You can get it from the SQLObject Subversion server. You can find all
necessary information at <http://www.sqlobject.org>. This code will NOT
work with the 0.5.x version advertised on their website!
This code also depends on a recent version of Cheetah. You can find
Cheetah at <http://www.cheetahtemplate.org>.
After starting this application for the first time, you will need to
access the /reset URI in order to create the database table and some
sample data. Accessing /reset again will drop and re-create the table,
so you may want to be careful. :-)
This application isn't supposed to be fool-proof, it's not even supposed
to be very GOOD. Play around with it some, browse the source code, smile.
:)
-- Hendrik Mans <hendrik@mans.de>
'''
import cherrypy
from Cheetah.Template import Template
from sqlobject import *
# configure your database connection here
__connection__ = 'mysql://root:@localhost/test'
# this is our (only) data class.
class Contact(SQLObject):
lastName = StringCol(length = 50, notNone = True)
firstName = StringCol(length = 50, notNone = True)
phone = StringCol(length = 30, notNone = True, default = '')
email = StringCol(length = 30, notNone = True, default = '')
url = StringCol(length = 100, notNone = True, default = '')
class ContactManager:
def index(self):
# Let's display a list of all stored contacts.
contacts = Contact.select()
template = Template('''
<h2>All Contacts</h2>
#for $contact in $contacts
<a href="mailto:$contact.email">$contact.lastName, $contact.firstName</a>
[<a href="./edit?id=$contact.id">Edit</a>]
[<a href="./delete?id=$contact.id">Delete</a>]
<br/>
#end for
<p>[<a href="./edit">Add new contact</a>]</p>
''', [locals(), globals()])
return template.respond()
index.exposed = True
def edit(self, id = 0):
# we really want id as an integer. Since GET/POST parameters
# are always passed as strings, let's convert it.
id = int(id)
if id > 0:
# if an id is specified, we're editing an existing contact.
contact = Contact.get(id)
title = "Edit Contact"
else:
# if no id is specified, we're entering a new contact.
contact = None
title = "New Contact"
# In the following template code, please note that we use
# Cheetah's $getVar() construct for the form values. We have
# to do this because contact may be set to None (see above).
template = Template('''
<h2>$title</h2>
<form action="./store" method="POST">
<input type="hidden" name="id" value="$id" />
Last Name: <input name="lastName" value="$getVar('contact.lastName', '')" /><br/>
First Name: <input name="firstName" value="$getVar('contact.firstName', '')" /><br/>
Phone: <input name="phone" value="$getVar('contact.phone', '')" /><br/>
Email: <input name="email" value="$getVar('contact.email', '')" /><br/>
URL: <input name="url" value="$getVar('contact.url', '')" /><br/>
<input type="submit" value="Store" />
</form>
''', [locals(), globals()])
return template.respond()
edit.exposed = True
def delete(self, id):
# Delete the specified contact
contact = Contact.get(int(id))
contact.destroySelf()
return 'Deleted. <a href="./">Return to Index</a>'
delete.exposed = True
def store(self, lastName, firstName, phone, email, url, id = None):
if id and int(id) > 0:
# If an id was specified, update an existing contact.
contact = Contact.get(int(id))
# We could set one field after another, but that would
# cause multiple UPDATE clauses. So we'll just do it all
# in a single pass through the set() method.
contact.set(
lastName = lastName,
firstName = firstName,
phone = phone,
email = email,
url = url)
else:
# Otherwise, add a new contact.
contact = Contact(
lastName = lastName,
firstName = firstName,
phone = phone,
email = email,
url = url)
return 'Stored. <a href="./">Return to Index</a>'
store.exposed = True
def reset(self):
# Drop existing table
Contact.dropTable(True)
# Create new table
Contact.createTable()
# Create some sample data
Contact(
firstName = 'Hendrik',
lastName = 'Mans',
email = 'hendrik@mans.de',
phone = '++49 89 12345678',
url = 'http://www.mornography.de')
return "reset completed!"
reset.exposed = True
print("If you're running this application for the first time, please go to http://localhost:8080/reset once in order to create the database!")
cherrypy.quickstart(ContactManager())
| [
[
8,
0,
0.0952,
0.1845,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1964,
0.006,
0,
0.66,
0.125,
639,
0,
1,
0,
0,
639,
0,
0
],
[
1,
0,
0.2024,
0.006,
0,
0.66,
... | [
"'''\nBonus Tutorial: Using SQLObject\n\nThis is a silly little contacts manager application intended to\ndemonstrate how to use SQLObject from within a CherryPy2 project. It\nalso shows how to use inline Cheetah templates.\n\nSQLObject is an Object/Relational Mapper that allows you to access",
"import cherrypy",... |
"""
Tutorial: File upload and download
Uploads
-------
When a client uploads a file to a CherryPy application, it's placed
on disk immediately. CherryPy will pass it to your exposed method
as an argument (see "myFile" below); that arg will have a "file"
attribute, which is a handle to the temporary uploaded file.
If you wish to permanently save the file, you need to read()
from myFile.file and write() somewhere else.
Note the use of 'enctype="multipart/form-data"' and 'input type="file"'
in the HTML which the client uses to upload the file.
Downloads
---------
If you wish to send a file to the client, you have two options:
First, you can simply return a file-like object from your page handler.
CherryPy will read the file and serve it as the content (HTTP body)
of the response. However, that doesn't tell the client that
the response is a file to be saved, rather than displayed.
Use cherrypy.lib.static.serve_file for that; it takes four
arguments:
serve_file(path, content_type=None, disposition=None, name=None)
Set "name" to the filename that you expect clients to use when they save
your file. Note that the "name" argument is ignored if you don't also
provide a "disposition" (usually "attachement"). You can manually set
"content_type", but be aware that if you also use the encoding tool, it
may choke if the file extension is not recognized as belonging to a known
Content-Type. Setting the content_type to "application/x-download" works
in most cases, and should prompt the user with an Open/Save dialog in
popular browsers.
"""
import os
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)
import cherrypy
from cherrypy.lib import static
class FileDemo(object):
def index(self):
return """
<html><body>
<h2>Upload a file</h2>
<form action="upload" method="post" enctype="multipart/form-data">
filename: <input type="file" name="myFile" /><br />
<input type="submit" />
</form>
<h2>Download a file</h2>
<a href='download'>This one</a>
</body></html>
"""
index.exposed = True
def upload(self, myFile):
out = """<html>
<body>
myFile length: %s<br />
myFile filename: %s<br />
myFile mime-type: %s
</body>
</html>"""
# Although this just counts the file length, it demonstrates
# how to read large files in chunks instead of all at once.
# CherryPy reads the uploaded file into a temporary file;
# myFile.file.read reads from that.
size = 0
while True:
data = myFile.file.read(8192)
if not data:
break
size += len(data)
return out % (size, myFile.filename, myFile.content_type)
upload.exposed = True
def download(self):
path = os.path.join(absDir, "pdf_file.pdf")
return static.serve_file(path, "application/x-download",
"attachment", os.path.basename(path))
download.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(FileDemo(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(FileDemo(), config=tutconf)
| [
[
8,
0,
0.1963,
0.3832,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.4019,
0.0093,
0,
0.66,
0.1111,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.4112,
0.0093,
0,
0.6... | [
"\"\"\"\n\nTutorial: File upload and download\n\nUploads\n-------\n\nWhen a client uploads a file to a CherryPy application, it's placed",
"import os",
"localDir = os.path.dirname(__file__)",
"absDir = os.path.join(os.getcwd(), localDir)",
"import cherrypy",
"from cherrypy.lib import static",
"class Fil... |
"""
Bonus Tutorial: Using generators to return result bodies
Instead of returning a complete result string, you can use the yield
statement to return one result part after another. This may be convenient
in situations where using a template package like CherryPy or Cheetah
would be overkill, and messy string concatenation too uncool. ;-)
"""
import cherrypy
class GeneratorDemo:
def header(self):
return "<html><body><h2>Generators rule!</h2>"
def footer(self):
return "</body></html>"
def index(self):
# Let's make up a list of users for presentation purposes
users = ['Remi', 'Carlos', 'Hendrik', 'Lorenzo Lamas']
# Every yield line adds one part to the total result body.
yield self.header()
yield "<h3>List of users:</h3>"
for user in users:
yield "%s<br/>" % user
yield self.footer()
index.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(GeneratorDemo(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(GeneratorDemo(), config=tutconf)
| [
[
8,
0,
0.0957,
0.1702,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2128,
0.0213,
0,
0.66,
0.2,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.4894,
0.4468,
0,
0.66,
... | [
"\"\"\"\nBonus Tutorial: Using generators to return result bodies\n\nInstead of returning a complete result string, you can use the yield\nstatement to return one result part after another. This may be convenient\nin situations where using a template package like CherryPy or Cheetah\nwould be overkill, and messy st... |
"""
Tutorial - The default method
Request handler objects can implement a method called "default" that
is called when no other suitable method/object could be found.
Essentially, if CherryPy2 can't find a matching request handler object
for the given request URI, it will use the default method of the object
located deepest on the URI path.
Using this mechanism you can easily simulate virtual URI structures
by parsing the extra URI string, which you can access through
cherrypy.request.virtualPath.
The application in this tutorial simulates an URI structure looking
like /users/<username>. Since the <username> bit will not be found (as
there are no matching methods), it is handled by the default method.
"""
import cherrypy
class UsersPage:
def index(self):
# Since this is just a stupid little example, we'll simply
# display a list of links to random, made-up users. In a real
# application, this could be generated from a database result set.
return '''
<a href="./remi">Remi Delon</a><br/>
<a href="./hendrik">Hendrik Mans</a><br/>
<a href="./lorenzo">Lorenzo Lamas</a><br/>
'''
index.exposed = True
def default(self, user):
# Here we react depending on the virtualPath -- the part of the
# path that could not be mapped to an object method. In a real
# application, we would probably do some database lookups here
# instead of the silly if/elif/else construct.
if user == 'remi':
out = "Remi Delon, CherryPy lead developer"
elif user == 'hendrik':
out = "Hendrik Mans, CherryPy co-developer & crazy German"
elif user == 'lorenzo':
out = "Lorenzo Lamas, famous actor and singer!"
else:
out = "Unknown user. :-("
return '%s (<a href="./">back</a>)' % out
default.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(UsersPage(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(UsersPage(), config=tutconf)
| [
[
8,
0,
0.1406,
0.2656,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2969,
0.0156,
0,
0.66,
0.2,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.5625,
0.4531,
0,
0.66,
... | [
"\"\"\"\nTutorial - The default method\n\nRequest handler objects can implement a method called \"default\" that\nis called when no other suitable method/object could be found.\nEssentially, if CherryPy2 can't find a matching request handler object\nfor the given request URI, it will use the default method of the o... |
"""
Tutorial - Multiple methods
This tutorial shows you how to link to other methods of your request
handler.
"""
import cherrypy
class HelloWorld:
def index(self):
# Let's link to another method here.
return 'We have an <a href="showMessage">important message</a> for you!'
index.exposed = True
def showMessage(self):
# Here's the important message!
return "Hello world!"
showMessage.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(HelloWorld(), config=tutconf)
| [
[
8,
0,
0.1094,
0.1875,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.25,
0.0312,
0,
0.66,
0.2,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.4688,
0.3438,
0,
0.66,
... | [
"\"\"\"\nTutorial - Multiple methods\n\nThis tutorial shows you how to link to other methods of your request\nhandler.\n\"\"\"",
"import cherrypy",
"class HelloWorld:\n \n def index(self):\n # Let's link to another method here.\n return 'We have an <a href=\"showMessage\">important message</... |
"""
Tutorial - Passing variables
This tutorial shows you how to pass GET/POST variables to methods.
"""
import cherrypy
class WelcomePage:
def index(self):
# Ask for the user's name.
return '''
<form action="greetUser" method="GET">
What is your name?
<input type="text" name="name" />
<input type="submit" />
</form>'''
index.exposed = True
def greetUser(self, name = None):
# CherryPy passes all GET and POST variables as method parameters.
# It doesn't make a difference where the variables come from, how
# large their contents are, and so on.
#
# You can define default parameter values as usual. In this
# example, the "name" parameter defaults to None so we can check
# if a name was actually specified.
if name:
# Greet the user!
return "Hey %s, what's up?" % name
else:
if name is None:
# No name was specified
return 'Please enter your name <a href="./">here</a>.'
else:
return 'No, really, enter your name <a href="./">here</a>.'
greetUser.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(WelcomePage(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(WelcomePage(), config=tutconf)
| [
[
8,
0,
0.0566,
0.0943,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1321,
0.0189,
0,
0.66,
0.2,
639,
0,
1,
0,
0,
639,
0,
0
],
[
3,
0,
0.4717,
0.5849,
0,
0.66,
... | [
"\"\"\"\nTutorial - Passing variables\n\nThis tutorial shows you how to pass GET/POST variables to methods.\n\"\"\"",
"import cherrypy",
"class WelcomePage:\n\n def index(self):\n # Ask for the user's name.\n return '''\n <form action=\"greetUser\" method=\"GET\">\n What i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.