repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
nicko96/Chrome-Infra
appengine/chromium_cq_status/js/tests/stats_test_data.js
67294
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var stats_test_data = { "cursor": "CkYKEgoFYmVnaW4SCQiA4KDXkdbFAhIsahRzfmNocm9taXVtLWNxLXN0YXR1c3IUCxIHQ1FTdGF0cxiAgIDihtCbCwwYACAB", "results": [ { "begin": 1434146400, "end": 1434150000, "interval_minutes": 60, "project": "infra", "key": 5118706493423616, "stats": [ { "count": 0, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 3, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 2, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 2, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 2, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 1, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 3, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 1, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 1, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 2, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 1, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 1, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 2, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 3, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 2, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 5.4404699999999995, "min": 5.02505, "max": 5.85589, "percentile_90": 5.772806, "sample_size": 2, "percentile_25": 5.23276, "percentile_95": 5.814348, "mean": 5.4404699999999995, "percentile_75": 5.64818, "percentile_10": 5.108134, "percentile_99": 5.847581599999999, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 197.59681, "min": 197.59681, "max": 197.59681, "percentile_90": 197.59681, "sample_size": 1, "percentile_25": 197.59681, "percentile_95": 197.59681, "mean": 197.59681, "percentile_75": 197.59681, "percentile_10": 197.59681, "percentile_99": 197.59681, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 2, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 221.66323, "min": 220.97879, "max": 385.26816, "percentile_90": 352.54717400000004, "sample_size": 3, "percentile_25": 221.32101, "percentile_95": 368.907667, "mean": 275.97006000000005, "percentile_75": 303.465695, "percentile_10": 221.11567800000003, "percentile_99": 381.99606140000003, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 221.66323, "min": 220.97879, "max": 385.26816, "percentile_90": 352.54717400000004, "sample_size": 3, "percentile_25": 221.32101, "percentile_95": 368.907667, "mean": 275.97006000000005, "percentile_75": 303.465695, "percentile_10": 221.11567800000003, "percentile_99": 381.99606140000003, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 209.85367, "min": 208.81467, "max": 380.66758, "percentile_90": 346.504798, "sample_size": 3, "percentile_25": 209.33417, "percentile_95": 363.58618899999993, "mean": 266.4453066666667, "percentile_75": 295.260625, "percentile_10": 209.02247, "percentile_99": 377.2513018, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 221.66323, "min": 220.97879, "max": 385.26816, "percentile_90": 352.54717400000004, "sample_size": 3, "percentile_25": 221.32101, "percentile_95": 368.907667, "mean": 275.97006000000005, "percentile_75": 303.465695, "percentile_10": 221.11567800000003, "percentile_99": 381.99606140000003, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 208.81467, "min": 183.07077, "max": 209.85367, "percentile_90": 209.64587, "sample_size": 3, "percentile_25": 195.94272, "percentile_95": 209.74976999999998, "mean": 200.57970333333333, "percentile_75": 209.33417, "percentile_10": 188.21955000000003, "percentile_99": 209.83289, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 3, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 221.66323, "min": 220.97879, "max": 385.26816, "percentile_90": 352.54717400000004, "sample_size": 3, "percentile_25": 221.32101, "percentile_95": 368.907667, "mean": 275.97006000000005, "percentile_75": 303.465695, "percentile_10": 221.11567800000003, "percentile_99": 381.99606140000003, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, { "begin": 1434142800, "end": 1434146400, "interval_minutes": 60, "project": "infra", "key": 4854631502970880, "stats": [ { "count": 1, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 3, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 3, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 2, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 2, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 2, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 0, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 2, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 0, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 3, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 3, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 3, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 3.26568, "min": 3.19668, "max": 4.0898, "percentile_90": 3.9249760000000005, "sample_size": 3, "percentile_25": 3.23118, "percentile_95": 4.007388, "mean": 3.517386666666667, "percentile_75": 3.67774, "percentile_10": 3.2104800000000004, "percentile_99": 4.0733176, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 0, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 3, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 194.98331, "min": 9.20691, "max": 217.60494, "percentile_90": 213.080614, "sample_size": 3, "percentile_25": 102.09510999999999, "percentile_95": 215.34277699999998, "mean": 140.59838666666667, "percentile_75": 206.294125, "percentile_10": 46.36219, "percentile_99": 217.15250740000002, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 194.98331, "min": 9.20691, "max": 217.60494, "percentile_90": 213.080614, "sample_size": 3, "percentile_25": 102.09510999999999, "percentile_95": 215.34277699999998, "mean": 140.59838666666667, "percentile_75": 206.294125, "percentile_10": 46.36219, "percentile_99": 217.15250740000002, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 184.93013, "min": 0.05456, "max": 206.82086, "percentile_90": 202.442714, "sample_size": 3, "percentile_25": 92.492345, "percentile_95": 204.631787, "mean": 130.60185, "percentile_75": 195.875495, "percentile_10": 37.029674, "percentile_99": 206.38304540000001, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 194.98331, "min": 9.20691, "max": 217.60494, "percentile_90": 213.080614, "sample_size": 3, "percentile_25": 102.09510999999999, "percentile_95": 215.34277699999998, "mean": 140.59838666666667, "percentile_75": 206.294125, "percentile_10": 46.36219, "percentile_99": 217.15250740000002, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 195.875495, "min": 184.93013, "max": 206.82086, "percentile_90": 204.631787, "sample_size": 2, "percentile_25": 190.4028125, "percentile_95": 205.7263235, "mean": 195.875495, "percentile_75": 201.3481775, "percentile_10": 187.119203, "percentile_99": 206.60195270000003, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 3, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 194.98331, "min": 9.20691, "max": 217.60494, "percentile_90": 213.080614, "sample_size": 3, "percentile_25": 102.09510999999999, "percentile_95": 215.34277699999998, "mean": 140.59838666666667, "percentile_75": 206.294125, "percentile_10": 46.36219, "percentile_99": 217.15250740000002, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, { "begin": 1434139200, "end": 1434142800, "interval_minutes": 60, "project": "infra", "key": 6308229562761216, "stats": [ { "count": 0, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 1, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 1, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 1, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 1, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 1, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 0, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 1, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 0, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 1, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 1, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 2.97648, "min": 2.97648, "max": 2.97648, "percentile_90": 2.97648, "sample_size": 1, "percentile_25": 2.97648, "percentile_95": 2.97648, "mean": 2.97648, "percentile_75": 2.97648, "percentile_10": 2.97648, "percentile_99": 2.97648, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 0, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 473.01608, "min": 473.01608, "max": 473.01608, "percentile_90": 473.01608, "sample_size": 1, "percentile_25": 473.01608, "percentile_95": 473.01608, "mean": 473.01608, "percentile_75": 473.01608, "percentile_10": 473.01608, "percentile_99": 473.01608, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 473.01608, "min": 473.01608, "max": 473.01608, "percentile_90": 473.01608, "sample_size": 1, "percentile_25": 473.01608, "percentile_95": 473.01608, "mean": 473.01608, "percentile_75": 473.01608, "percentile_10": 473.01608, "percentile_99": 473.01608, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 465.62457, "min": 465.62457, "max": 465.62457, "percentile_90": 465.62457, "sample_size": 1, "percentile_25": 465.62457, "percentile_95": 465.62457, "mean": 465.62457, "percentile_75": 465.62457, "percentile_10": 465.62457, "percentile_99": 465.62457, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 473.01608, "min": 473.01608, "max": 473.01608, "percentile_90": 473.01608, "sample_size": 1, "percentile_25": 473.01608, "percentile_95": 473.01608, "mean": 473.01608, "percentile_75": 473.01608, "percentile_10": 473.01608, "percentile_99": 473.01608, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 465.62457, "min": 465.62457, "max": 465.62457, "percentile_90": 465.62457, "sample_size": 1, "percentile_25": 465.62457, "percentile_95": 465.62457, "mean": 465.62457, "percentile_75": 465.62457, "percentile_10": 465.62457, "percentile_99": 465.62457, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 1, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 473.01608, "min": 473.01608, "max": 473.01608, "percentile_90": 473.01608, "sample_size": 1, "percentile_25": 473.01608, "percentile_95": 473.01608, "mean": 473.01608, "percentile_75": 473.01608, "percentile_10": 473.01608, "percentile_99": 473.01608, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, { "begin": 1434132000, "end": 1434135600, "interval_minutes": 60, "project": "infra", "key": 5632176477437952, "stats": [ { "count": 0, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 1, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 1, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 1, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 1, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 1, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 0, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 1, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 0, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 1, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 1, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 3.25917, "min": 3.25917, "max": 3.25917, "percentile_90": 3.25917, "sample_size": 1, "percentile_25": 3.25917, "percentile_95": 3.25917, "mean": 3.25917, "percentile_75": 3.25917, "percentile_10": 3.25917, "percentile_99": 3.25917, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 0, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 245.63969, "min": 245.63969, "max": 245.63969, "percentile_90": 245.63969, "sample_size": 1, "percentile_25": 245.63969, "percentile_95": 245.63969, "mean": 245.63969, "percentile_75": 245.63969, "percentile_10": 245.63969, "percentile_99": 245.63969, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 245.63969, "min": 245.63969, "max": 245.63969, "percentile_90": 245.63969, "sample_size": 1, "percentile_25": 245.63969, "percentile_95": 245.63969, "mean": 245.63969, "percentile_75": 245.63969, "percentile_10": 245.63969, "percentile_99": 245.63969, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 234.9721, "min": 234.9721, "max": 234.9721, "percentile_90": 234.9721, "sample_size": 1, "percentile_25": 234.9721, "percentile_95": 234.9721, "mean": 234.9721, "percentile_75": 234.9721, "percentile_10": 234.9721, "percentile_99": 234.9721, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 245.63969, "min": 245.63969, "max": 245.63969, "percentile_90": 245.63969, "sample_size": 1, "percentile_25": 245.63969, "percentile_95": 245.63969, "mean": 245.63969, "percentile_75": 245.63969, "percentile_10": 245.63969, "percentile_99": 245.63969, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 234.9721, "min": 234.9721, "max": 234.9721, "percentile_90": 234.9721, "sample_size": 1, "percentile_25": 234.9721, "percentile_95": 234.9721, "mean": 234.9721, "percentile_75": 234.9721, "percentile_10": 234.9721, "percentile_99": 234.9721, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 1, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 245.63969, "min": 245.63969, "max": 245.63969, "percentile_90": 245.63969, "sample_size": 1, "percentile_25": 245.63969, "percentile_95": 245.63969, "mean": 245.63969, "percentile_75": 245.63969, "percentile_10": 245.63969, "percentile_99": 245.63969, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, { "begin": 1434128400, "end": 1434132000, "interval_minutes": 60, "project": "infra", "key": 5136106479681536, "stats": [ { "count": 0, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 1, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 1, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 1, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 1, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 1, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 0, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 1, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 0, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 1, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 1, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 7.47758, "min": 7.47758, "max": 7.47758, "percentile_90": 7.47758, "sample_size": 1, "percentile_25": 7.47758, "percentile_95": 7.47758, "mean": 7.47758, "percentile_75": 7.47758, "percentile_10": 7.47758, "percentile_99": 7.47758, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 0, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 1, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 214.27208, "min": 214.27208, "max": 214.27208, "percentile_90": 214.27208, "sample_size": 1, "percentile_25": 214.27208, "percentile_95": 214.27208, "mean": 214.27208, "percentile_75": 214.27208, "percentile_10": 214.27208, "percentile_99": 214.27208, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 214.27208, "min": 214.27208, "max": 214.27208, "percentile_90": 214.27208, "sample_size": 1, "percentile_25": 214.27208, "percentile_95": 214.27208, "mean": 214.27208, "percentile_75": 214.27208, "percentile_10": 214.27208, "percentile_99": 214.27208, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 197.00373, "min": 197.00373, "max": 197.00373, "percentile_90": 197.00373, "sample_size": 1, "percentile_25": 197.00373, "percentile_95": 197.00373, "mean": 197.00373, "percentile_75": 197.00373, "percentile_10": 197.00373, "percentile_99": 197.00373, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 214.27208, "min": 214.27208, "max": 214.27208, "percentile_90": 214.27208, "sample_size": 1, "percentile_25": 214.27208, "percentile_95": 214.27208, "mean": 214.27208, "percentile_75": 214.27208, "percentile_10": 214.27208, "percentile_99": 214.27208, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 197.00373, "min": 197.00373, "max": 197.00373, "percentile_90": 197.00373, "sample_size": 1, "percentile_25": 197.00373, "percentile_95": 197.00373, "mean": 197.00373, "percentile_75": 197.00373, "percentile_10": 197.00373, "percentile_99": 197.00373, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 1, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 214.27208, "min": 214.27208, "max": 214.27208, "percentile_90": 214.27208, "sample_size": 1, "percentile_25": 214.27208, "percentile_95": 214.27208, "mean": 214.27208, "percentile_75": 214.27208, "percentile_10": 214.27208, "percentile_99": 214.27208, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, { "begin": 1434067200, "end": 1434070800, "interval_minutes": 60, "project": "infra", "key": 5673948255617024, "stats": [ { "count": 0, "type": "count", "name": "tryjobverifier-skip-count", "description": "Number of tryjob verifier runs skipped." }, { "count": 5, "type": "count", "name": "patchset-count", "description": "Number of patchsets processed by the CQ." }, { "count": 5, "type": "count", "name": "patchset-commit-count", "description": "Number of patchsets committed by the CQ." }, { "count": 5, "type": "count", "name": "tryjobverifier-pass-count", "description": "Number of tryjob verifier runs passed." }, { "count": 0, "type": "count", "name": "patchset-false-reject-count", "description": "Number of patchsets rejected by the trybots that eventually passed." }, { "count": 5, "type": "count", "name": "trybot-pass-count", "description": "Number of passing runs across all trybots." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-fail-count", "description": "Number of failing runs by the infra_tester trybot." }, { "count": 5, "type": "count", "name": "tryjobverifier-start-count", "description": "Number of tryjob verifier runs started." }, { "count": 0, "type": "count", "name": "attempt-false-reject-trigger-count", "description": "Number of failed job trigger attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-false-reject-count", "description": "Number of false rejects across all trybots. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-cq-presubmit-count", "description": "Number of failed CQ presubmit checks on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-retry-count", "description": "Number of tryjob verifier runs retried." }, { "count": 0, "type": "count", "name": "patchset-reject-count", "description": "Number of patchsets rejected by the trybots at least once." }, { "count": 5, "type": "count", "name": "trybot-infra_tester-pass-count", "description": "Number of passing runs by the infra_tester trybot." }, { "count": 0, "type": "count", "name": "trybot-infra_tester-false-reject-count", "description": "Number of false rejects by the infra_tester trybot. This counts any failed runs that also had passing runs on the same patch." }, { "count": 0, "type": "count", "name": "attempt-false-reject-count", "description": "Number of failed attempts on a committed patch that passed presubmit, had all LGTMs and were not manually cancelled." }, { "count": 0, "type": "count", "name": "attempt-false-reject-commit-count", "description": "Number of failed commit attempts on a committed patch." }, { "count": 0, "type": "count", "name": "tryjobverifier-error-count", "description": "Number of tryjob verifier runs errored." }, { "count": 0, "type": "count", "name": "tryjobverifier-fail-count", "description": "Number of tryjob verifier runs failed." }, { "count": 0, "type": "count", "name": "tryjobverifier-timeout-count", "description": "Number of tryjob verifier runs that timed out." }, { "count": 0, "type": "count", "name": "attempt-false-reject-tryjob-count", "description": "Number of failed job attempts on a committed patch." }, { "count": 0, "type": "count", "name": "trybot-fail-count", "description": "Number of failing runs across all trybots." }, { "count": 5, "type": "count", "name": "issue-count", "description": "Number of issues processed by the CQ." }, { "count": 5, "type": "count", "name": "attempt-count", "description": "Number of CQ attempts made." }, { "description": "Time spent per committed patchset blocked on a closed tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 5, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-closed-tree-durations" }, { "description": "Time taken by the CQ to land a patch after passing all checks.", "percentile_50": 3.89683, "min": 2.37103, "max": 5.97471, "percentile_90": 5.2368500000000004, "sample_size": 5, "percentile_25": 2.38062, "percentile_95": 5.605779999999999, "mean": 3.7506500000000003, "percentile_75": 4.13006, "percentile_10": 2.374866, "percentile_99": 5.900924, "type": "list", "unit": "seconds", "name": "patchset-commit-durations" }, { "description": "Time spent on each tryjob verifier retry.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 0, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "tryjobverifier-retry-durations" }, { "description": "Time spent per committed patchset blocked on a throttled tree.", "percentile_50": 0, "min": 0, "max": 0, "percentile_90": 0, "sample_size": 5, "percentile_25": 0, "percentile_95": 0, "mean": 0, "percentile_75": 0, "percentile_10": 0, "percentile_99": 0, "type": "list", "unit": "seconds", "name": "blocked-on-throttled-tree-durations" }, { "description": "Total time spent in the CQ per patchset, counts multiple CQ attempts as one.", "percentile_50": 223.26259, "min": 191.31495, "max": 271.32364, "percentile_90": 264.574512, "sample_size": 5, "percentile_25": 222.58316, "percentile_95": 267.949076, "mean": 232.587032, "percentile_75": 254.45082, "percentile_10": 203.822234, "percentile_99": 270.6487272, "type": "list", "unit": "seconds", "name": "patchset-durations" }, { "description": "Total time spent in the CQ per patch.", "percentile_50": 223.26259, "min": 191.31495, "max": 271.32364, "percentile_90": 264.574512, "sample_size": 5, "percentile_25": 222.58316, "percentile_95": 267.949076, "mean": 232.587032, "percentile_75": 254.45082, "percentile_10": 203.822234, "percentile_99": 270.6487272, "type": "list", "unit": "seconds", "name": "patchset-total-commit-queue-durations" }, { "description": "Total time spent per CQ attempt on tryjob verifier runs.", "percentile_50": 212.13505, "min": 181.0709, "max": 260.80051, "percentile_90": 256.10323, "sample_size": 5, "percentile_25": 210.00244, "percentile_95": 258.45187, "mean": 222.61324199999999, "percentile_75": 249.05731, "percentile_10": 192.643516, "percentile_99": 260.330782, "type": "list", "unit": "seconds", "name": "tryjobverifier-total-durations" }, { "description": "Total time spent per CQ attempt.", "percentile_50": 223.26259, "min": 191.31495, "max": 271.32364, "percentile_90": 264.574512, "sample_size": 5, "percentile_25": 222.58316, "percentile_95": 267.949076, "mean": 232.587032, "percentile_75": 254.45082, "percentile_10": 203.822234, "percentile_99": 270.6487272, "type": "list", "unit": "seconds", "name": "attempt-durations" }, { "description": "Time spent on each tryjob verifier first run.", "percentile_50": 212.13505, "min": 181.0709, "max": 260.80051, "percentile_90": 256.10323, "sample_size": 5, "percentile_25": 210.00244, "percentile_95": 258.45187, "mean": 222.61324199999999, "percentile_75": 249.05731, "percentile_10": 192.643516, "percentile_99": 260.330782, "type": "list", "unit": "seconds", "name": "tryjobverifier-first-run-durations" }, { "description": "Number of CQ attempts per patchset.", "percentile_50": 1, "min": 1, "max": 1, "percentile_90": 1, "sample_size": 5, "percentile_25": 1, "percentile_95": 1, "mean": 1, "percentile_75": 1, "percentile_10": 1, "percentile_99": 1, "type": "list", "unit": "attempts", "name": "patchset-attempts" }, { "description": "Total time per patch since their commit box was checked.", "percentile_50": 223.26259, "min": 191.31495, "max": 271.32364, "percentile_90": 264.574512, "sample_size": 5, "percentile_25": 222.58316, "percentile_95": 267.949076, "mean": 232.587032, "percentile_75": 254.45082, "percentile_10": 203.822234, "percentile_99": 270.6487272, "type": "list", "unit": "seconds", "name": "patchset-total-wall-time-durations" } ] }, ], "more": true };
bsd-3-clause
MiddlewareICS/MiddlewareICS-2.0
app/edu/pc3/sensoract/vpds/model/TaskletModel.java
3141
/* * Copyright (c) 2012, Indraprastha Institute of Information Technology, * Delhi (IIIT-D) and The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 3. Neither the names of the Indraprastha Institute of Information * Technology, Delhi and the University of California nor the names * of their contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE IIIT-D, THE REGENTS, AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE IIITD-D, THE REGENTS * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * Name: TaskletModel.java * Project: SensorAct-VPDS * Version: 1.0 * Date: 2012-07-20 * Author: Pandarasamy Arjunan */ package edu.pc3.sensoract.vpds.model; import java.util.HashMap; import java.util.Map; import play.modules.morphia.Model; import com.google.code.morphia.annotations.Entity; import edu.pc3.sensoract.vpds.api.request.TaskletAddFormat; /** * Model class for tasklet script management. * * @author Pandarasamy Arjunan * @version 1.0 */ @Entity(value = "Tasklet", noClassnameStored = true) public class TaskletModel extends Model { public String secretkey = null; public String taskletname = null; public String desc = null; public Map<String, String> param = null; public Map<String, NotifyEmailModel> email = null; public Map<String, String> input = null; public String when = null; public String execute = null; // Internal use public String source = null; public TaskletType tasklet_type; public String taskletId; public TaskletModel(final TaskletAddFormat tasklet) { if (null == tasklet) { return; } secretkey = tasklet.secretkey; taskletname = tasklet.taskletname; desc = tasklet.desc; param = tasklet.param; input = tasklet.input; email = tasklet.email; when = tasklet.when; execute = tasklet.execute; tasklet_type = tasklet.tasklet_type; } TaskletModel() { } }
bsd-3-clause
Bysmyyr/chromium-crosswalk
chrome/common/extensions/feature_switch_unittest.cc
7130
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/common/feature_switch.h" #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "testing/gtest/include/gtest/gtest.h" using extensions::FeatureSwitch; namespace { const char kSwitchName[] = "test-switch"; const char kFieldTrialName[] = "field-trial"; // Create and register a field trial that will always return the given // |group_name|. scoped_refptr<base::FieldTrial> CreateFieldTrial( const std::string& group_name) { const int kTotalProbability = 10; // Note: This code will probably fail in the year 5000. But all the cycles we // save in the next 3000 years by not determining the current year will be // worth it. scoped_refptr<base::FieldTrial> trial = base::FieldTrialList::FactoryGetFieldTrial( kFieldTrialName, kTotalProbability, "default", 5000, 1, 1, base::FieldTrial::SESSION_RANDOMIZED, nullptr); trial->AppendGroup(group_name, kTotalProbability); return trial; } template<FeatureSwitch::DefaultValue T> class FeatureSwitchTest : public testing::Test { public: FeatureSwitchTest() : command_line_(base::CommandLine::NO_PROGRAM), feature_(&command_line_, kSwitchName, T) {} protected: base::CommandLine command_line_; FeatureSwitch feature_; }; typedef FeatureSwitchTest<FeatureSwitch::DEFAULT_DISABLED> FeatureSwitchDisabledTest; typedef FeatureSwitchTest<FeatureSwitch::DEFAULT_ENABLED> FeatureSwitchEnabledTest; } // namespace TEST_F(FeatureSwitchDisabledTest, NoSwitchValue) { EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchDisabledTest, FalseSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "0"); EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchDisabledTest, GibberishSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "monkey"); EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchDisabledTest, Override) { { FeatureSwitch::ScopedOverride override(&feature_, false); EXPECT_FALSE(feature_.IsEnabled()); } EXPECT_FALSE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, true); EXPECT_TRUE(feature_.IsEnabled()); } EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchDisabledTest, TrueSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "1"); EXPECT_TRUE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, false); EXPECT_FALSE(feature_.IsEnabled()); } EXPECT_TRUE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, true); EXPECT_TRUE(feature_.IsEnabled()); } EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchDisabledTest, TrimSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, " \t 1\n "); EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, NoSwitchValue) { EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, TrueSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "1"); EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, GibberishSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "monkey"); EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, Override) { { FeatureSwitch::ScopedOverride override(&feature_, true); EXPECT_TRUE(feature_.IsEnabled()); } EXPECT_TRUE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, false); EXPECT_FALSE(feature_.IsEnabled()); } EXPECT_TRUE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, FalseSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "0"); EXPECT_FALSE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, true); EXPECT_TRUE(feature_.IsEnabled()); } EXPECT_FALSE(feature_.IsEnabled()); { FeatureSwitch::ScopedOverride override(&feature_, false); EXPECT_FALSE(feature_.IsEnabled()); } EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, TrimSwitchValue) { command_line_.AppendSwitchASCII(kSwitchName, "\t\t 0 \n"); EXPECT_FALSE(feature_.IsEnabled()); } TEST_F(FeatureSwitchEnabledTest, TrueFieldTrialValue) { // Construct a fake field trial that defaults to the group "Enabled". base::FieldTrialList field_trials(nullptr); scoped_refptr<base::FieldTrial> enabled_trial = CreateFieldTrial("Enabled"); { // A default-enabled switch should be enabled (naturally). FeatureSwitch default_enabled_switch(&command_line_, kSwitchName, kFieldTrialName, FeatureSwitch::DEFAULT_ENABLED); EXPECT_TRUE(default_enabled_switch.IsEnabled()); // Scoped overrides override everything. FeatureSwitch::ScopedOverride scoped_override(&default_enabled_switch, false); EXPECT_FALSE(default_enabled_switch.IsEnabled()); } { // A default-disabled switch should be enabled because of the field trial. FeatureSwitch default_disabled_switch(&command_line_, kSwitchName, kFieldTrialName, FeatureSwitch::DEFAULT_DISABLED); EXPECT_TRUE(default_disabled_switch.IsEnabled()); // Scoped overrides override everything. FeatureSwitch::ScopedOverride scoped_override(&default_disabled_switch, false); EXPECT_FALSE(default_disabled_switch.IsEnabled()); } } TEST_F(FeatureSwitchEnabledTest, FalseFieldTrialValue) { // Construct a fake field trial that defaults to the group "Disabled". base::FieldTrialList field_trials(nullptr); scoped_refptr<base::FieldTrial> disabled_trial = CreateFieldTrial("Disabled"); { // A default-enabled switch should be disabled because of the field trial. FeatureSwitch default_enabled_switch(&command_line_, kSwitchName, kFieldTrialName, FeatureSwitch::DEFAULT_ENABLED); EXPECT_FALSE(default_enabled_switch.IsEnabled()); // Scoped overrides override everything. FeatureSwitch::ScopedOverride scoped_override(&default_enabled_switch, true); EXPECT_TRUE(default_enabled_switch.IsEnabled()); } { // A default-disabled switch should remain disabled. FeatureSwitch default_disabled_switch(&command_line_, kSwitchName, kFieldTrialName, FeatureSwitch::DEFAULT_DISABLED); EXPECT_FALSE(default_disabled_switch.IsEnabled()); // Scoped overrides override everything. FeatureSwitch::ScopedOverride scoped_override(&default_disabled_switch, true); EXPECT_TRUE(default_disabled_switch.IsEnabled()); } }
bsd-3-clause
endlessm/chromium-browser
ash/highlighter/highlighter_gesture_util_unittest.cc
6355
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/highlighter/highlighter_gesture_util.h" #include "ash/fast_ink/fast_ink_points.h" #include "ash/test/ash_test_base.h" #include "ui/gfx/geometry/rect_conversions.h" namespace ash { namespace { constexpr float kLength = 400; constexpr gfx::RectF kFrame(50, 50, 300, 200); constexpr gfx::SizeF kPenTipSize(4.0, 14); constexpr int kPointsPerLine = 10; float LinearInterpolate(float from, float to, int position, int range) { return from + ((to - from) * position) / range; } class HighlighterGestureUtilTest : public AshTestBase { public: HighlighterGestureUtilTest() : points_(base::TimeDelta()) {} ~HighlighterGestureUtilTest() override = default; protected: fast_ink::FastInkPoints points_; void MoveTo(float x, float y) { AddPoint(x, y); } void LineTo(float x, float y) { const gfx::PointF origin = points_.GetNewest().location; for (int i = 1; i <= kPointsPerLine; i++) { AddPoint(LinearInterpolate(origin.x(), x, i, kPointsPerLine), LinearInterpolate(origin.y(), y, i, kPointsPerLine)); } } void TraceLine(float x0, float y0, float x1, float y1) { MoveTo(x0, y0); LineTo(x1, y1); } void TraceRect(const gfx::RectF& rect, float tilt) { MoveTo(rect.x() + tilt, rect.y()); LineTo(rect.right(), rect.y() + tilt); LineTo(rect.right() - tilt, rect.bottom()); LineTo(rect.x(), rect.bottom() - tilt); LineTo(rect.x() + tilt, rect.y()); } void TraceZigZag(float w, float h) { MoveTo(0, 0); LineTo(w / 4, h); LineTo(w / 2, 0); LineTo(w * 3 / 4, h); LineTo(w, 0); } HighlighterGestureType DetectGesture() { return DetectHighlighterGesture(points_.GetBoundingBoxF(), kPenTipSize, points_); } private: void AddPoint(float x, float y) { points_.AddPoint(gfx::PointF(x, y), base::TimeTicks()); } DISALLOW_COPY_AND_ASSIGN(HighlighterGestureUtilTest); }; } // namespace TEST_F(HighlighterGestureUtilTest, HorizontalStrokeTooShort) { TraceLine(0, 0, 1, 0); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeFlat) { TraceLine(0, 0, kLength, 0); EXPECT_EQ(HighlighterGestureType::kHorizontalStroke, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeTiltedLeftSlightly) { const float kTilt = kLength / 20; TraceLine(0, kTilt, kLength, 0); EXPECT_EQ(HighlighterGestureType::kHorizontalStroke, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeTiltedRightSlightly) { const float kTilt = kLength / 20; TraceLine(0, 0, kLength, kTilt); EXPECT_EQ(HighlighterGestureType::kHorizontalStroke, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeTiltedLeftTooMuch) { const float kTilt = kLength / 5; TraceLine(0, kTilt, kLength, 0); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeTiltedRightTooMuch) { const float kTilt = kLength / 5; TraceLine(0, 0, kLength, kTilt); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeZigZagSlightly) { const float kHeight = kLength / 20; TraceZigZag(kLength, kHeight); EXPECT_EQ(HighlighterGestureType::kHorizontalStroke, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, HorizontalStrokeZigZagTooMuch) { const float kHeight = kLength / 5; TraceZigZag(kLength, kHeight); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeRectangle) { TraceRect(kFrame, 0); EXPECT_EQ(HighlighterGestureType::kClosedShape, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeRectangleThin) { TraceRect(gfx::RectF(0, 0, kLength, kLength / 20), 0); EXPECT_EQ(HighlighterGestureType::kHorizontalStroke, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeRectangleTilted) { TraceRect(kFrame, 10.0); EXPECT_EQ(HighlighterGestureType::kClosedShape, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeWithOverlap) { // 1/4 overlap MoveTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); EXPECT_EQ(HighlighterGestureType::kClosedShape, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeLikeU) { // 1/4 open shape MoveTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.y()); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeLikeG) { // 1/8 open shape MoveTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.CenterPoint().y()); EXPECT_EQ(HighlighterGestureType::kClosedShape, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeWithLittleBackAndForth) { MoveTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); // Go back one pixel, then go forward again. MoveTo(kFrame.x() + 1, kFrame.y()); MoveTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.CenterPoint().y()); EXPECT_EQ(HighlighterGestureType::kClosedShape, DetectGesture()); } TEST_F(HighlighterGestureUtilTest, ClosedShapeWithTooMuchBackAndForth) { MoveTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); LineTo(kFrame.right(), kFrame.y()); LineTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.x(), kFrame.y()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.x(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.bottom()); LineTo(kFrame.right(), kFrame.CenterPoint().y()); EXPECT_EQ(HighlighterGestureType::kNotRecognized, DetectGesture()); } } // namespace ash
bsd-3-clause
hlzz/dotfiles
graphics/cgal/Convex_hull_3/test/Convex_hull_3/ch3_dual_test_less_signed_distance_to_plane_3.cpp
1558
#include <cassert> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Convex_hull_3/dual/Convex_hull_traits_dual_3.h> #include <CGAL/Convex_hull_traits_3.h> #include "include/to_dual.h" typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef K::Plane_3 Plane; typedef CGAL::Convex_hull_3::Plane_dual<K> Plane_dual; typedef CGAL::Convex_hull_3::Convex_hull_traits_dual_3<K> Hull_traits_dual; typedef Hull_traits_dual::Less_signed_distance_to_plane_3 Less_signed_distance_to_plane_3_dual; typedef CGAL::Convex_hull_traits_3<K> Hull_traits; typedef Hull_traits::Less_signed_distance_to_plane_3 Less_signed_distance_to_plane_3; int main () { Hull_traits_dual traits_dual; Hull_traits traits; Less_signed_distance_to_plane_3 less_signed_distance = traits.less_signed_distance_to_plane_3_object(); Less_signed_distance_to_plane_3_dual less_signed_distance_dual = traits_dual.less_signed_distance_to_plane_3_object(); // dual plane : x = 1 Plane a(1, 1, 0, -1), b(1, 2, 1, -1), c(1, 3, 0, -1); Plane_dual p(a,b,c); Plane q(2, 0, 0, -1), r(3, 0, 0, -1) , rr(0.5, 0, 0, -1); // False assert(less_signed_distance_dual(p, q, r) == false); assert(less_signed_distance_dual(p, q, r) == less_signed_distance(to_dual_plane<K>(p), to_dual<K>(q), to_dual<K>(r))); // True assert(less_signed_distance_dual(p, q, rr) == true); assert(less_signed_distance_dual(p, q, rr) == less_signed_distance(to_dual_plane<K>(p), to_dual<K>(q), to_dual<K>(rr))); return 0; }
bsd-3-clause
rtucker-mozilla/mozpackager
vendor-local/lib/python/kombu/transport/virtual/__init__.py
25672
""" kombu.transport.virtual ======================= Virtual transport implementation. Emulates the AMQ API for non-AMQ transports. """ from __future__ import absolute_import import base64 import socket import warnings from itertools import count from time import sleep, time from Queue import Empty from kombu.exceptions import StdChannelError from kombu.utils import emergency_dump_state, say, uuid from kombu.utils.compat import OrderedDict from kombu.utils.encoding import str_to_bytes, bytes_to_str from kombu.utils.finalize import Finalize from kombu.transport import base from .scheduling import FairCycle from .exchange import STANDARD_EXCHANGE_TYPES UNDELIVERABLE_FMT = """\ Message could not be delivered: No queues bound to exchange %(exchange)r using binding key %(routing_key)r """ class Base64(object): def encode(self, s): return bytes_to_str(base64.b64encode(str_to_bytes(s))) def decode(self, s): return base64.b64decode(str_to_bytes(s)) class NotEquivalentError(Exception): """Entity declaration is not equivalent to the previous declaration.""" pass class UndeliverableWarning(UserWarning): """The message could not be delivered to a queue.""" pass class BrokerState(object): #: exchange declarations. exchanges = None #: active bindings. bindings = None def __init__(self, exchanges=None, bindings=None): self.exchanges = {} if exchanges is None else exchanges self.bindings = {} if bindings is None else bindings def clear(self): self.exchanges.clear() self.bindings.clear() class QoS(object): """Quality of Service guarantees. Only supports `prefetch_count` at this point. :param channel: AMQ Channel. :keyword prefetch_count: Initial prefetch count (defaults to 0). """ #: current prefetch count value prefetch_count = 0 #: :class:`~collections.OrderedDict` of active messages. #: *NOTE*: Can only be modified by the consuming thread. _delivered = None #: acks can be done by other threads than the consuming thread. #: Instead of a mutex, which doesn't perform well here, we mark #: the delivery tags as dirty, so subsequent calls to append() can remove #: them. _dirty = None #: If disabled, unacked messages won't be restored at shutdown. restore_at_shutdown = True def __init__(self, channel, prefetch_count=0): self.channel = channel self.prefetch_count = prefetch_count or 0 self._delivered = OrderedDict() self._delivered.restored = False self._dirty = set() self._on_collect = Finalize(self, self.restore_unacked_once, exitpriority=1) def can_consume(self): """Returns true if the channel can be consumed from. Used to ensure the client adhers to currently active prefetch limits. """ pcount = self.prefetch_count return not pcount or len(self._delivered) - len(self._dirty) < pcount def append(self, message, delivery_tag): """Append message to transactional state.""" self._delivered[delivery_tag] = message if self._dirty: self._flush() def get(self, delivery_tag): return self._delivered[delivery_tag] def _flush(self): """Flush dirty (acked/rejected) tags from.""" dirty = self._dirty delivered = self._delivered while 1: try: dirty_tag = dirty.pop() except KeyError: break delivered.pop(dirty_tag, None) def ack(self, delivery_tag): """Acknowledge message and remove from transactional state.""" self._dirty.add(delivery_tag) def reject(self, delivery_tag, requeue=False): """Remove from transactional state and requeue message.""" if requeue: self.channel._restore(self._delivered[delivery_tag]) self._dirty.add(delivery_tag) def restore_unacked(self): """Restore all unacknowledged messages.""" self._flush() delivered = self._delivered errors = [] while delivered: try: _, message = delivered.popitem() except KeyError: # pragma: no cover break try: self.channel._restore(message) except BaseException, exc: errors.append((exc, message)) delivered.clear() return errors def restore_unacked_once(self): """Restores all unacknowledged message at shutdown/gc collect. Will only be done once for each instance. """ self._on_collect.cancel() self._flush() state = self._delivered if not self.restore_at_shutdown: return elif not self.channel.do_restore or getattr(state, 'restored', None): assert not state return try: if state: say('Restoring %r unacknowledged message(s).', len(self._delivered)) unrestored = self.restore_unacked() if unrestored: errors, messages = zip(*unrestored) say('UNABLE TO RESTORE %s MESSAGES: %s', len(errors), errors) emergency_dump_state(messages) finally: state.restored = True class Message(base.Message): def __init__(self, channel, payload, **kwargs): self._raw = payload properties = payload['properties'] body = payload.get('body') if body: body = channel.decode_body(body, properties.get('body_encoding')) fields = {'body': body, 'delivery_tag': properties['delivery_tag'], 'content_type': payload.get('content-type'), 'content_encoding': payload.get('content-encoding'), 'headers': payload.get('headers'), 'properties': properties, 'delivery_info': properties.get('delivery_info'), 'postencode': 'utf-8'} super(Message, self).__init__(channel, **dict(kwargs, **fields)) def serializable(self): props = self.properties body, _ = self.channel.encode_body(self.body, props.get('body_encoding')) headers = dict(self.headers) # remove compression header headers.pop('compression', None) return {'body': body, 'properties': props, 'content-type': self.content_type, 'content-encoding': self.content_encoding, 'headers': self.headers} class AbstractChannel(object): """This is an abstract class defining the channel methods you'd usually want to implement in a virtual channel. Do not subclass directly, but rather inherit from :class:`Channel` instead. """ def _get(self, queue, timeout=None): """Get next message from `queue`.""" raise NotImplementedError('Virtual channels must implement _get') def _put(self, queue, message): """Put `message` onto `queue`.""" raise NotImplementedError('Virtual channels must implement _put') def _purge(self, queue): """Remove all messages from `queue`.""" raise NotImplementedError('Virtual channels must implement _purge') def _size(self, queue): """Return the number of messages in `queue` as an :class:`int`.""" return 0 def _delete(self, queue, *args, **kwargs): """Delete `queue`. This just purges the queue, if you need to do more you can override this method. """ self._purge(queue) def _new_queue(self, queue, **kwargs): """Create new queue. Some implementations needs to do additional actions when the queue is created. You can do so by overriding this method. """ pass def _has_queue(self, queue, **kwargs): """Verify that queue exists. Should return :const:`True` if the queue exists or :const:`False` otherwise. """ return True def _poll(self, cycle, timeout=None): """Poll a list of queues for available messages.""" return cycle.get() class Channel(AbstractChannel, base.StdChannel): """Virtual channel. :param connection: The transport instance this channel is part of. """ #: message class used. Message = Message #: QoS class used. QoS = QoS #: flag to restore unacked messages when channel #: goes out of scope. do_restore = True #: mapping of exchange types and corresponding classes. exchange_types = dict(STANDARD_EXCHANGE_TYPES) #: flag set if the channel supports fanout exchanges. supports_fanout = False #: Binary <-> ASCII codecs. codecs = {'base64': Base64()} #: Default body encoding. #: NOTE: ``transport_options['body_encoding']`` will override this value. body_encoding = 'base64' #: counter used to generate delivery tags for this channel. _next_delivery_tag = count(1).next #: Optional queue where messages with no route is delivered. #: Set by ``transport_options['deadletter_queue']``. deadletter_queue = None # List of options to transfer from :attr:`transport_options`. from_transport_options = ('body_encoding', 'deadletter_queue') def __init__(self, connection, **kwargs): self.connection = connection self._consumers = set() self._cycle = None self._tag_to_queue = {} self._active_queues = [] self._qos = None self.closed = False # instantiate exchange types self.exchange_types = dict((typ, cls(self)) for typ, cls in self.exchange_types.items()) self.channel_id = self.connection._next_channel_id() topts = self.connection.client.transport_options for opt_name in self.from_transport_options: try: setattr(self, opt_name, topts[opt_name]) except KeyError: pass def exchange_declare(self, exchange=None, type='direct', durable=False, auto_delete=False, arguments=None, nowait=False, passive=False): """Declare exchange.""" type = type or 'direct' exchange = exchange or 'amq.%s' % (type, ) if passive: if exchange not in self.state.exchanges: raise StdChannelError('404', u'NOT_FOUND - no exchange %r in vhost %r' % ( exchange, self.connection.client.virtual_host or '/'), (50, 10), 'Channel.exchange_declare') return try: prev = self.state.exchanges[exchange] if not self.typeof(exchange).equivalent(prev, exchange, type, durable, auto_delete, arguments): raise NotEquivalentError( 'Cannot redeclare exchange %r in vhost %r with ' 'different type, durable or autodelete value' % ( exchange, self.connection.client.virtual_host or '/')) except KeyError: self.state.exchanges[exchange] = { 'type': type, 'durable': durable, 'auto_delete': auto_delete, 'arguments': arguments or {}, 'table': [], } def exchange_delete(self, exchange, if_unused=False, nowait=False): """Delete `exchange` and all its bindings.""" for rkey, _, queue in self.get_table(exchange): self.queue_delete(queue, if_unused=True, if_empty=True) self.state.exchanges.pop(exchange, None) def queue_declare(self, queue=None, passive=False, **kwargs): """Declare queue.""" queue = queue or 'amq.gen-%s' % uuid() if passive and not self._has_queue(queue, **kwargs): raise StdChannelError('404', u'NOT_FOUND - no queue %r in vhost %r' % ( queue, self.connection.client.virtual_host or '/'), (50, 10), 'Channel.queue_declare') else: self._new_queue(queue, **kwargs) return queue, self._size(queue), 0 def queue_delete(self, queue, if_unusued=False, if_empty=False, **kwargs): """Delete queue.""" if if_empty and self._size(queue): return try: exchange, routing_key, arguments = self.state.bindings[queue] except KeyError: return meta = self.typeof(exchange).prepare_bind(queue, exchange, routing_key, arguments) self._delete(queue, exchange, *meta) self.state.bindings.pop(queue, None) def after_reply_message_received(self, queue): self.queue_delete(queue) def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): raise NotImplementedError('transport does not support exchange_bind') def exchange_unbind(self, destination, source='', routing_key='', nowait=False, arguments=None): raise NotImplementedError('transport does not support exchange_unbind') def queue_bind(self, queue, exchange=None, routing_key='', arguments=None, **kwargs): """Bind `queue` to `exchange` with `routing key`.""" if queue in self.state.bindings: return exchange = exchange or 'amq.direct' table = self.state.exchanges[exchange].setdefault('table', []) self.state.bindings[queue] = exchange, routing_key, arguments meta = self.typeof(exchange).prepare_bind(queue, exchange, routing_key, arguments) table.append(meta) if self.supports_fanout: self._queue_bind(exchange, *meta) def queue_unbind(self, queue, exchange=None, routing_key='', arguments=None, **kwargs): raise NotImplementedError('transport does not support queue_unbind') def list_bindings(self): for exchange in self.state.exchanges: table = self.get_table(exchange) for routing_key, pattern, queue in table: yield queue, exchange, routing_key def queue_purge(self, queue, **kwargs): """Remove all ready messages from queue.""" return self._purge(queue) def basic_publish(self, message, exchange, routing_key, **kwargs): """Publish message.""" props = message['properties'] message['body'], props['body_encoding'] = \ self.encode_body(message['body'], self.body_encoding) props['delivery_info']['exchange'] = exchange props['delivery_info']['routing_key'] = routing_key props['delivery_tag'] = self._next_delivery_tag() self.typeof(exchange).deliver(message, exchange, routing_key, **kwargs) def basic_consume(self, queue, no_ack, callback, consumer_tag, **kwargs): """Consume from `queue`""" self._tag_to_queue[consumer_tag] = queue self._active_queues.append(queue) def _callback(raw_message): message = self.Message(self, raw_message) if not no_ack: self.qos.append(message, message.delivery_tag) return callback(message) self.connection._callbacks[queue] = _callback self._consumers.add(consumer_tag) self._reset_cycle() def basic_cancel(self, consumer_tag): """Cancel consumer by consumer tag.""" if consumer_tag in self._consumers: self._consumers.remove(consumer_tag) self._reset_cycle() queue = self._tag_to_queue.pop(consumer_tag, None) try: self._active_queues.remove(queue) except ValueError: pass self.connection._callbacks.pop(queue, None) def basic_get(self, queue, **kwargs): """Get message by direct access (synchronous).""" try: return self._get(queue) except Empty: pass def basic_ack(self, delivery_tag): """Acknowledge message.""" self.qos.ack(delivery_tag) def basic_recover(self, requeue=False): """Recover unacked messages.""" if requeue: return self.qos.restore_unacked() raise NotImplementedError('Does not support recover(requeue=False)') def basic_reject(self, delivery_tag, requeue=False): """Reject message.""" self.qos.reject(delivery_tag, requeue=requeue) def basic_qos(self, prefetch_size=0, prefetch_count=0, apply_global=False): """Change QoS settings for this channel. Only `prefetch_count` is supported. """ self.qos.prefetch_count = prefetch_count def get_exchanges(self): return list(self.state.exchanges) def get_table(self, exchange): """Get table of bindings for `exchange`.""" return self.state.exchanges[exchange]['table'] def typeof(self, exchange, default='direct'): """Get the exchange type instance for `exchange`.""" try: type = self.state.exchanges[exchange]['type'] except KeyError: type = default return self.exchange_types[type] def _lookup(self, exchange, routing_key, default=None): """Find all queues matching `routing_key` for the given `exchange`. Returns `default` if no queues matched. """ if default is None: default = self.deadletter_queue try: R = self.typeof(exchange).lookup(self.get_table(exchange), exchange, routing_key, default) except KeyError: R = [] if not R and default is not None: warnings.warn(UndeliverableWarning(UNDELIVERABLE_FMT % { 'exchange': exchange, 'routing_key': routing_key})) self._new_queue(default) R = [default] return R def _restore(self, message): """Redeliver message to its original destination.""" delivery_info = message.delivery_info message = message.serializable() message['redelivered'] = True for queue in self._lookup(delivery_info['exchange'], delivery_info['routing_key']): self._put(queue, message) def drain_events(self, timeout=None): if self._consumers and self.qos.can_consume(): if hasattr(self, '_get_many'): return self._get_many(self._active_queues, timeout=timeout) return self._poll(self.cycle, timeout=timeout) raise Empty() def message_to_python(self, raw_message): """Convert raw message to :class:`Message` instance.""" if not isinstance(raw_message, self.Message): return self.Message(self, payload=raw_message) return raw_message def prepare_message(self, body, priority=None, content_type=None, content_encoding=None, headers=None, properties=None): """Prepare message data.""" properties = properties or {} info = properties.setdefault('delivery_info', {}) info['priority'] = priority or 0 return {'body': body, 'content-encoding': content_encoding, 'content-type': content_type, 'headers': headers or {}, 'properties': properties or {}} def flow(self, active=True): """Enable/disable message flow. :raises NotImplementedError: as flow is not implemented by the base virtual implementation. """ raise NotImplementedError('virtual channels does not support flow.') def close(self): """Close channel, cancel all consumers, and requeue unacked messages.""" if not self.closed: self.closed = True for consumer in list(self._consumers): self.basic_cancel(consumer) if self._qos: self._qos.restore_unacked_once() if self._cycle is not None: self._cycle.close() self._cycle = None if self.connection is not None: self.connection.close_channel(self) self.exchange_types = None def encode_body(self, body, encoding=None): if encoding: return self.codecs.get(encoding).encode(body), encoding return body, encoding def decode_body(self, body, encoding=None): if encoding: return self.codecs.get(encoding).decode(body) return body def _reset_cycle(self): self._cycle = FairCycle(self._get, self._active_queues, Empty) def __enter__(self): return self def __exit__(self, *exc_info): self.close() @property def state(self): """Broker state containing exchanges and bindings.""" return self.connection.state @property def qos(self): """:class:`QoS` manager for this channel.""" if self._qos is None: self._qos = self.QoS(self) return self._qos @property def cycle(self): if self._cycle is None: self._reset_cycle() return self._cycle class Management(base.Management): def __init__(self, transport): super(Management, self).__init__(transport) self.channel = transport.client.channel() def get_bindings(self): return [dict(destination=q, source=e, routing_key=r) for q, e, r in self.channel.list_bindings()] def close(self): self.channel.close() class Transport(base.Transport): """Virtual transport. :param client: :class:`~kombu.Connection` instance """ Channel = Channel Cycle = FairCycle Management = Management #: :class:`BrokerState` containing declared exchanges and #: bindings (set by constructor). state = BrokerState() #: :class:`~kombu.transport.virtual.scheduling.FairCycle` instance #: used to fairly drain events from channels (set by constructor). cycle = None #: port number used when no port is specified. default_port = None #: active channels. channels = None #: queue/callback map. _callbacks = None #: Time to sleep between unsuccessful polls. polling_interval = 1.0 def __init__(self, client, **kwargs): self.client = client self.channels = [] self._avail_channels = [] self._callbacks = {} self.cycle = self.Cycle(self._drain_channel, self.channels, Empty) self._next_channel_id = count(1).next polling_interval = client.transport_options.get('polling_interval') if polling_interval is not None: self.polling_interval = polling_interval def create_channel(self, connection): try: return self._avail_channels.pop() except IndexError: channel = self.Channel(connection) self.channels.append(channel) return channel def close_channel(self, channel): try: try: self.channels.remove(channel) except ValueError: pass finally: channel.connection = None def establish_connection(self): # creates channel to verify connection. # this channel is then used as the next requested channel. # (returned by ``create_channel``). self._avail_channels.append(self.create_channel(self)) return self # for drain events def close_connection(self, connection): self.cycle.close() for l in self._avail_channels, self.channels: while l: try: channel = l.pop() except (IndexError, KeyError): # pragma: no cover pass else: channel.close() def drain_events(self, connection, timeout=None): loop = 0 time_start = time() get = self.cycle.get polling_interval = self.polling_interval while 1: try: item, channel = get(timeout=timeout) except Empty: if timeout and time() - time_start >= timeout: raise socket.timeout() loop += 1 if polling_interval is not None: sleep(polling_interval) else: break message, queue = item if not queue or queue not in self._callbacks: raise KeyError( "Received message for queue '%s' without consumers: %s" % ( queue, message)) self._callbacks[queue](message) def _drain_channel(self, channel, timeout=None): return channel.drain_events(timeout=timeout) @property def default_connection_params(self): return {'port': self.default_port, 'hostname': 'localhost'}
bsd-3-clause
takeflight/wagtail
wagtail/contrib/search_promotions/tests.py
17166
from django.test import TestCase from django.urls import reverse from wagtail.contrib.search_promotions.models import SearchPromotion from wagtail.contrib.search_promotions.templatetags.wagtailsearchpromotions_tags import \ get_search_promotions from wagtail.search.models import Query from wagtail.tests.utils import WagtailTestUtils class TestSearchPromotions(TestCase): def test_search_pick_create(self): # Create a search pick to the root page SearchPromotion.objects.create( query=Query.get("root page"), page_id=1, sort_order=0, description="First search promotion", ) # Check self.assertEqual(Query.get("root page").editors_picks.count(), 1) self.assertEqual(Query.get("root page").editors_picks.first().page_id, 1) def test_search_pick_ordering(self): # Add 3 search picks in a different order to their sort_order values # They should be ordered by their sort order values and not their insertion order SearchPromotion.objects.create( query=Query.get("root page"), page_id=1, sort_order=0, description="First search pick", ) SearchPromotion.objects.create( query=Query.get("root page"), page_id=1, sort_order=2, description="Last search pick", ) SearchPromotion.objects.create( query=Query.get("root page"), page_id=1, sort_order=1, description="Middle search pick", ) # Check self.assertEqual(Query.get("root page").editors_picks.count(), 3) self.assertEqual(Query.get("root page").editors_picks.first().description, "First search pick") self.assertEqual(Query.get("root page").editors_picks.last().description, "Last search pick") class TestGetSearchPromotionsTemplateTag(TestCase): def test_get_search_promotions_template_tag(self): # Create a search pick to the root page pick = SearchPromotion.objects.create( query=Query.get("root page"), page_id=1, sort_order=0, description="First search pick", ) # Create another search pick against a different query SearchPromotion.objects.create( query=Query.get("root page again"), page_id=1, sort_order=0, description="Second search pick", ) # Check search_picks = list(get_search_promotions("root page")) self.assertEqual(search_picks, [pick]) def test_get_search_promotions_with_none_query_string(self): search_picks = list(get_search_promotions(None)) self.assertEqual(search_picks, []) class TestSearchPromotionsIndexView(TestCase, WagtailTestUtils): def setUp(self): self.login() def test_simple(self): response = self.client.get(reverse('wagtailsearchpromotions:index')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/index.html') def test_search(self): response = self.client.get(reverse('wagtailsearchpromotions:index'), {'q': "Hello"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['query_string'], "Hello") def make_search_picks(self): for i in range(50): SearchPromotion.objects.create( query=Query.get("query " + str(i)), page_id=1, sort_order=0, description="First search pick", ) def test_pagination(self): self.make_search_picks() response = self.client.get(reverse('wagtailsearchpromotions:index'), {'p': 2}) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/index.html') # Check that we got the correct page self.assertEqual(response.context['queries'].number, 2) def test_pagination_invalid(self): self.make_search_picks() response = self.client.get(reverse('wagtailsearchpromotions:index'), {'p': 'Hello World!'}) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/index.html') # Check that we got page one self.assertEqual(response.context['queries'].number, 1) def test_pagination_out_of_range(self): self.make_search_picks() response = self.client.get(reverse('wagtailsearchpromotions:index'), {'p': 99999}) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/index.html') # Check that we got the last page self.assertEqual(response.context['queries'].number, response.context['queries'].paginator.num_pages) def test_results_are_ordered_alphabetically(self): self.make_search_picks() SearchPromotion.objects.create( query=Query.get("aaargh snake"), page_id=1, sort_order=0, description="ooh, it's a snake", ) response = self.client.get(reverse('wagtailsearchpromotions:index')) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/index.html') # "aargh snake" should be the first result alphabetically self.assertEqual(response.context['queries'][0].query_string, "aaargh snake") def test_results_ordering(self): self.make_search_picks() url = reverse('wagtailsearchpromotions:index') SearchPromotion.objects.create( query=Query.get("zyzzyvas"), page_id=1, sort_order=0, description="no definition found, this is a valid scrabble word though", ) SearchPromotion.objects.create( query=Query.get("aardwolf"), page_id=1, sort_order=22, description="Striped hyena of southeast Africa that feeds chiefly on insects", ) popularQuery = Query.get("optimal") for i in range(50): popularQuery.add_hit() SearchPromotion.objects.create( query=popularQuery, page_id=1, sort_order=15, description="An odly popular search term?", ) popularQuery = Query.get("suboptimal") for i in range(25): popularQuery.add_hit() SearchPromotion.objects.create( query=popularQuery, page_id=1, sort_order=15, description="Not as popular", ) # ordered by querystring (reversed) response = self.client.get(url + '?ordering=-query_string') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['queries'][0].query_string, "zyzzyvas") # last page, still ordered by query string (reversed) response = self.client.get(url + '?ordering=-query_string&p=3') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['queries'][-1].query_string, "aardwolf") # ordered by querystring (not reversed) response = self.client.get(url + '?ordering=query_string') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['queries'][0].query_string, "aardwolf") # ordered by sum of daily hits (reversed) response = self.client.get(url + '?ordering=-views') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['queries'][0].query_string, "optimal") self.assertEqual(response.context['queries'][1].query_string, "suboptimal") # ordered by sum of daily hits, last page (not reversed) response = self.client.get(url + '?ordering=views&p=3') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['queries'][-1].query_string, "optimal") self.assertEqual(response.context['queries'][-2].query_string, "suboptimal") class TestSearchPromotionsAddView(TestCase, WagtailTestUtils): def setUp(self): self.login() def test_simple(self): response = self.client.get(reverse('wagtailsearchpromotions:add')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/add.html') def test_post(self): # Submit post_data = { 'query_string': "test", 'editors_picks-TOTAL_FORMS': 1, 'editors_picks-INITIAL_FORMS': 0, 'editors_picks-MAX_NUM_FORMS': 1000, 'editors_picks-0-DELETE': '', 'editors_picks-0-ORDER': 0, 'editors_picks-0-page': 1, 'editors_picks-0-description': "Hello", } response = self.client.post(reverse('wagtailsearchpromotions:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailsearchpromotions:index')) # Check that the search pick was created self.assertTrue(Query.get('test').editors_picks.filter(page_id=1).exists()) def test_post_without_recommendations(self): # Submit post_data = { 'query_string': "test", 'editors_picks-TOTAL_FORMS': 0, 'editors_picks-INITIAL_FORMS': 0, 'editors_picks-MAX_NUM_FORMS': 1000, } response = self.client.post(reverse('wagtailsearchpromotions:add'), post_data) # User should be given an error self.assertEqual(response.status_code, 200) self.assertFormsetError( response, 'searchpicks_formset', None, None, "Please specify at least one recommendation for this search term." ) class TestSearchPromotionsEditView(TestCase, WagtailTestUtils): def setUp(self): self.login() # Create an search pick to edit self.query = Query.get("Hello") self.search_pick = self.query.editors_picks.create(page_id=1, description="Root page") self.search_pick_2 = self.query.editors_picks.create(page_id=2, description="Homepage") def test_simple(self): response = self.client.get(reverse('wagtailsearchpromotions:edit', args=(self.query.id, ))) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/edit.html') def test_post(self): # Submit post_data = { 'query_string': "Hello", 'editors_picks-TOTAL_FORMS': 2, 'editors_picks-INITIAL_FORMS': 2, 'editors_picks-MAX_NUM_FORMS': 1000, 'editors_picks-0-id': self.search_pick.id, 'editors_picks-0-DELETE': '', 'editors_picks-0-ORDER': 0, 'editors_picks-0-page': 1, 'editors_picks-0-description': "Description has changed", # Change 'editors_picks-1-id': self.search_pick_2.id, 'editors_picks-1-DELETE': '', 'editors_picks-1-ORDER': 1, 'editors_picks-1-page': 2, 'editors_picks-1-description': "Homepage", } response = self.client.post(reverse('wagtailsearchpromotions:edit', args=(self.query.id, )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailsearchpromotions:index')) # Check that the search pick description was edited self.assertEqual(SearchPromotion.objects.get(id=self.search_pick.id).description, "Description has changed") def test_post_reorder(self): # Check order before reordering self.assertEqual(Query.get("Hello").editors_picks.all()[0], self.search_pick) self.assertEqual(Query.get("Hello").editors_picks.all()[1], self.search_pick_2) # Submit post_data = { 'query_string': "Hello", 'editors_picks-TOTAL_FORMS': 2, 'editors_picks-INITIAL_FORMS': 2, 'editors_picks-MAX_NUM_FORMS': 1000, 'editors_picks-0-id': self.search_pick.id, 'editors_picks-0-DELETE': '', 'editors_picks-0-ORDER': 1, # Change 'editors_picks-0-page': 1, 'editors_picks-0-description': "Root page", 'editors_picks-1-id': self.search_pick_2.id, 'editors_picks-1-DELETE': '', 'editors_picks-1-ORDER': 0, # Change 'editors_picks-1-page': 2, 'editors_picks-1-description': "Homepage", } response = self.client.post(reverse('wagtailsearchpromotions:edit', args=(self.query.id, )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailsearchpromotions:index')) # Check that the ordering has been saved correctly self.assertEqual(SearchPromotion.objects.get(id=self.search_pick.id).sort_order, 1) self.assertEqual(SearchPromotion.objects.get(id=self.search_pick_2.id).sort_order, 0) # Check that the recommendations were reordered self.assertEqual(Query.get("Hello").editors_picks.all()[0], self.search_pick_2) self.assertEqual(Query.get("Hello").editors_picks.all()[1], self.search_pick) def test_post_delete_recommendation(self): # Submit post_data = { 'query_string': "Hello", 'editors_picks-TOTAL_FORMS': 2, 'editors_picks-INITIAL_FORMS': 2, 'editors_picks-MAX_NUM_FORMS': 1000, 'editors_picks-0-id': self.search_pick.id, 'editors_picks-0-DELETE': '', 'editors_picks-0-ORDER': 0, 'editors_picks-0-page': 1, 'editors_picks-0-description': "Root page", 'editors_picks-1-id': self.search_pick_2.id, 'editors_picks-1-DELETE': 1, 'editors_picks-1-ORDER': 1, 'editors_picks-1-page': 2, 'editors_picks-1-description': "Homepage", } response = self.client.post(reverse('wagtailsearchpromotions:edit', args=(self.query.id, )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailsearchpromotions:index')) # Check that the recommendation was deleted self.assertFalse(SearchPromotion.objects.filter(id=self.search_pick_2.id).exists()) # The other recommendation should still exist self.assertTrue(SearchPromotion.objects.filter(id=self.search_pick.id).exists()) def test_post_without_recommendations(self): # Submit post_data = { 'query_string': "Hello", 'editors_picks-TOTAL_FORMS': 2, 'editors_picks-INITIAL_FORMS': 2, 'editors_picks-MAX_NUM_FORMS': 1000, 'editors_picks-0-id': self.search_pick.id, 'editors_picks-0-DELETE': 1, 'editors_picks-0-ORDER': 0, 'editors_picks-0-page': 1, 'editors_picks-0-description': "Description has changed", # Change 'editors_picks-1-id': self.search_pick_2.id, 'editors_picks-1-DELETE': 1, 'editors_picks-1-ORDER': 1, 'editors_picks-1-page': 2, 'editors_picks-1-description': "Homepage", } response = self.client.post(reverse('wagtailsearchpromotions:edit', args=(self.query.id, )), post_data) # User should be given an error self.assertEqual(response.status_code, 200) self.assertFormsetError( response, 'searchpicks_formset', None, None, "Please specify at least one recommendation for this search term." ) class TestSearchPromotionsDeleteView(TestCase, WagtailTestUtils): def setUp(self): self.login() # Create an search pick to delete self.query = Query.get("Hello") self.search_pick = self.query.editors_picks.create(page_id=1, description="Root page") self.search_pick_2 = self.query.editors_picks.create(page_id=2, description="Homepage") def test_simple(self): response = self.client.get(reverse('wagtailsearchpromotions:delete', args=(self.query.id, ))) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailsearchpromotions/confirm_delete.html') def test_post(self): # Submit response = self.client.post(reverse('wagtailsearchpromotions:delete', args=(self.query.id, ))) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailsearchpromotions:index')) # Check that both recommendations were deleted self.assertFalse(SearchPromotion.objects.filter(id=self.search_pick_2.id).exists()) # The other recommendation should still exist self.assertFalse(SearchPromotion.objects.filter(id=self.search_pick.id).exists())
bsd-3-clause
patrickm/chromium.src
chrome/browser/extensions/convert_web_app.cc
6340
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/convert_web_app.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "base/base64.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/web_application_info.h" #include "crypto/sha2.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "url/gurl.h" namespace extensions { namespace keys = manifest_keys; using base::Time; namespace { const char kIconsDirName[] = "icons"; // Create the public key for the converted web app. // // Web apps are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A web app's unique identity // is its manifest URL, so we hash that to create a public key. There will be // no corresponding private key, which means that these extensions cannot be // auto-updated using ExtensionUpdater. std::string GenerateKey(const GURL& app_url) { char raw[crypto::kSHA256Length] = {0}; std::string key; crypto::SHA256HashString(app_url.spec().c_str(), raw, crypto::kSHA256Length); base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key); return key; } } // namespace // Generates a version for the converted app using the current date. This isn't // really needed, but it seems like useful information. std::string ConvertTimeToExtensionVersion(const Time& create_time) { Time::Exploded create_time_exploded; create_time.UTCExplode(&create_time_exploded); double micros = static_cast<double>( (create_time_exploded.millisecond * Time::kMicrosecondsPerMillisecond) + (create_time_exploded.second * Time::kMicrosecondsPerSecond) + (create_time_exploded.minute * Time::kMicrosecondsPerMinute) + (create_time_exploded.hour * Time::kMicrosecondsPerHour)); double day_fraction = micros / Time::kMicrosecondsPerDay; double stamp = day_fraction * std::numeric_limits<uint16>::max(); // Ghetto-round, since VC++ doesn't have round(). stamp = stamp >= (floor(stamp) + 0.5) ? (stamp + 1) : stamp; return base::StringPrintf("%i.%i.%i.%i", create_time_exploded.year, create_time_exploded.month, create_time_exploded.day_of_month, static_cast<uint16>(stamp)); } scoped_refptr<Extension> ConvertWebAppToExtension( const WebApplicationInfo& web_app, const Time& create_time, const base::FilePath& extensions_dir) { base::FilePath install_temp_dir = extension_file_util::GetInstallTempDir(extensions_dir); if (install_temp_dir.empty()) { LOG(ERROR) << "Could not get path to profile temporary directory."; return NULL; } base::ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDirUnderPath(install_temp_dir)) { LOG(ERROR) << "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<base::DictionaryValue> root(new base::DictionaryValue); root->SetString(keys::kPublicKey, GenerateKey(web_app.app_url)); root->SetString(keys::kName, base::UTF16ToUTF8(web_app.title)); root->SetString(keys::kVersion, ConvertTimeToExtensionVersion(create_time)); root->SetString(keys::kDescription, base::UTF16ToUTF8(web_app.description)); root->SetString(keys::kLaunchWebURL, web_app.app_url.spec()); // Add the icons. base::DictionaryValue* icons = new base::DictionaryValue(); root->Set(keys::kIcons, icons); for (size_t i = 0; i < web_app.icons.size(); ++i) { std::string size = base::StringPrintf("%i", web_app.icons[i].width); std::string icon_path = base::StringPrintf("%s/%s.png", kIconsDirName, size.c_str()); icons->SetString(size, icon_path); } // Write the manifest. base::FilePath manifest_path = temp_dir.path().Append(kManifestFilename); JSONFileValueSerializer serializer(manifest_path); if (!serializer.Serialize(*root)) { LOG(ERROR) << "Could not serialize manifest."; return NULL; } // Write the icon files. base::FilePath icons_dir = temp_dir.path().AppendASCII(kIconsDirName); if (!base::CreateDirectory(icons_dir)) { LOG(ERROR) << "Could not create icons directory."; return NULL; } for (size_t i = 0; i < web_app.icons.size(); ++i) { // Skip unfetched bitmaps. if (web_app.icons[i].data.config() == SkBitmap::kNo_Config) continue; base::FilePath icon_file = icons_dir.AppendASCII( base::StringPrintf("%i.png", web_app.icons[i].width)); std::vector<unsigned char> image_data; if (!gfx::PNGCodec::EncodeBGRASkBitmap(web_app.icons[i].data, false, &image_data)) { LOG(ERROR) << "Could not create icon file."; return NULL; } const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); int size = base::checked_cast<int>(image_data.size()); if (base::WriteFile(icon_file, image_data_ptr, size) != size) { LOG(ERROR) << "Could not write icon file."; return NULL; } } // Finally, create the extension object to represent the unpacked directory. std::string error; scoped_refptr<Extension> extension = Extension::Create( temp_dir.path(), Manifest::INTERNAL, *root, Extension::FROM_BOOKMARK, &error); if (!extension.get()) { LOG(ERROR) << error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension; } } // namespace extensions
bsd-3-clause
armon/pypred
pypred/__init__.py
336
__version__ = "0.3.6" from .ast import Undefined from .merge import RefactorSettings from .predicate import Predicate, InvalidPredicate from .set import PredicateSet, OptimizedPredicateSet __all__ = [ "Predicate", "InvalidPredicate", "PredicateSet", "OptimizedPredicateSet", "RefactorSettings", "Undefined" ]
bsd-3-clause
espadrine/opera
chromium/src/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.cpp
4423
/* * Copyright (C) 2010 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/accessibility/AccessibilityMenuListPopup.h" #include "core/accessibility/AXObjectCache.h" #include "core/accessibility/AccessibilityMenuListOption.h" #include "core/html/HTMLSelectElement.h" namespace WebCore { using namespace HTMLNames; AccessibilityMenuListPopup::AccessibilityMenuListPopup() { } bool AccessibilityMenuListPopup::isVisible() const { return false; } bool AccessibilityMenuListPopup::isOffScreen() const { if (!m_parent) return true; return m_parent->isCollapsed(); } bool AccessibilityMenuListPopup::isEnabled() const { if (!m_parent) return false; return m_parent->isEnabled(); } bool AccessibilityMenuListPopup::computeAccessibilityIsIgnored() const { return accessibilityIsIgnoredByDefault(); } AccessibilityMenuListOption* AccessibilityMenuListPopup::menuListOptionAccessibilityObject(HTMLElement* element) const { if (!element || !element->hasTagName(optionTag)) return 0; AccessibilityObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole); ASSERT_WITH_SECURITY_IMPLICATION(object->isMenuListOption()); AccessibilityMenuListOption* option = static_cast<AccessibilityMenuListOption*>(object); option->setElement(element); return option; } bool AccessibilityMenuListPopup::press() const { if (!m_parent) return false; m_parent->press(); return true; } void AccessibilityMenuListPopup::addChildren() { if (!m_parent) return; Node* selectNode = m_parent->node(); if (!selectNode) return; m_haveChildren = true; const Vector<HTMLElement*>& listItems = toHTMLSelectElement(selectNode)->listItems(); unsigned length = listItems.size(); for (unsigned i = 0; i < length; i++) { AccessibilityMenuListOption* option = menuListOptionAccessibilityObject(listItems[i]); if (option) { option->setParent(this); m_children.append(option); } } } void AccessibilityMenuListPopup::childrenChanged() { AXObjectCache* cache = axObjectCache(); for (size_t i = m_children.size(); i > 0 ; --i) { AccessibilityObject* child = m_children[i - 1].get(); if (child->actionElement() && !child->actionElement()->attached()) { child->detachFromParent(); cache->remove(child->axObjectID()); } } m_children.clear(); m_haveChildren = false; addChildren(); } void AccessibilityMenuListPopup::didUpdateActiveOption(int optionIndex) { ASSERT_ARG(optionIndex, optionIndex >= 0); ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size())); AXObjectCache* cache = axObjectCache(); RefPtr<AccessibilityObject> child = m_children[optionIndex].get(); cache->postNotification(child.get(), document(), AXObjectCache::AXFocusedUIElementChanged, true, PostSynchronously); cache->postNotification(child.get(), document(), AXObjectCache::AXMenuListItemSelected, true, PostSynchronously); } } // namespace WebCore
bsd-3-clause
irobayna/stupidedi
lib/stupidedi/versions/003050/segment_defs/W04.rb
1626
# frozen_string_literal: true module Stupidedi module Versions module ThirtyFifty module SegmentDefs s = Schema e = ElementDefs r = ElementReqs W04 = s::SegmentDef.build(:W04, "Item Detail Total", "To designate those line items that were shipped", e::E382 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)), e::E355 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)), e::E438 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E235 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E234 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E235 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E234 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E59 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E121 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E23 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E22 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E416 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E844 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E235 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E234 .simple_use(r::Relational, s::RepeatCount.bounded(1)), SyntaxNotes::R.build( 3, 4), SyntaxNotes::P.build( 4, 5), SyntaxNotes::P.build( 6, 7), SyntaxNotes::P.build(10, 11), SyntaxNotes::P.build(14, 15)) end end end end
bsd-3-clause
andrewseidl/chrono
src/chrono_vehicle/wheeled_vehicle/tire/ANCFToroidalTire.cpp
5047
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Antonio Recuero // ============================================================================= // // ANCF toroidal tire. // This is a concrete ANCF tire class which uses a semi-toroidal tire mesh // composed of single-layer ANCF shell elements. // // ============================================================================= #include "chrono_vehicle/wheeled_vehicle/tire/ANCFToroidalTire.h" using namespace chrono::fea; namespace chrono { namespace vehicle { ANCFToroidalTire::ANCFToroidalTire(const std::string& name) : ChANCFTire(name), m_rim_radius(0.35), m_height(0.195), m_thickness(0.014), m_div_circumference(60), m_div_width(12), m_default_pressure(320.0e3), m_alpha(0.15) {} void ANCFToroidalTire::CreateMesh(const ChFrameMoving<>& wheel_frame, VehicleSide side) { // Create an isotropic material (shared by all elements) auto mat = std::make_shared<ChMaterialShellANCF>(500, 9.0e7, 0.3); // Create the mesh nodes. // The nodes are first created in the wheel local frame, assuming Y as the tire axis, // and are then transformed to the global frame. for (int i = 0; i < m_div_circumference; i++) { double phi = (CH_C_2PI * i) / m_div_circumference; for (int j = 0; j <= m_div_width; j++) { double theta = -CH_C_PI_2 + (CH_C_PI * j) / m_div_width; double x = (m_rim_radius + m_height * cos(theta)) * cos(phi); double y = m_height * sin(theta); double z = (m_rim_radius + m_height * cos(theta)) * sin(phi); ChVector<> loc = wheel_frame.TransformPointLocalToParent(ChVector<>(x, y, z)); double nx = cos(theta) * cos(phi); double ny = sin(theta); double nz = cos(theta) * sin(phi); ChVector<> dir = wheel_frame.TransformDirectionLocalToParent(ChVector<>(nx, ny, nz)); auto node = std::make_shared<ChNodeFEAxyzD>(loc, dir); node->SetMass(0); m_mesh->AddNode(node); } } // Element dimensions double dz = m_thickness; double dx = CH_C_2PI * (m_rim_radius + m_height) / (2 * m_div_circumference); double dy = CH_C_PI * m_height / m_div_width; // Create the ANCF shell elements for (int i = 0; i < m_div_circumference; i++) { for (int j = 0; j < m_div_width; j++) { // Adjacent nodes int inode0, inode1, inode2, inode3; inode1 = j + i * (m_div_width + 1); inode2 = j + 1 + i * (m_div_width + 1); if (i == m_div_circumference - 1) { inode0 = j; inode3 = j + 1; } else { inode0 = j + (i + 1) * (m_div_width + 1); inode3 = j + 1 + (i + 1) * (m_div_width + 1); } auto node0 = std::dynamic_pointer_cast<ChNodeFEAxyzD>(m_mesh->GetNode(inode0)); auto node1 = std::dynamic_pointer_cast<ChNodeFEAxyzD>(m_mesh->GetNode(inode1)); auto node2 = std::dynamic_pointer_cast<ChNodeFEAxyzD>(m_mesh->GetNode(inode2)); auto node3 = std::dynamic_pointer_cast<ChNodeFEAxyzD>(m_mesh->GetNode(inode3)); // Create the element and set its nodes. auto element = std::make_shared<ChElementShellANCF>(); element->SetNodes(node0, node1, node2, node3); // Set element dimensions element->SetDimensions(dx, dy); // Add a single layers with a fiber angle of 0 degrees. element->AddLayer(dz, 0 * CH_C_DEG_TO_RAD, mat); // Set other element properties element->SetAlphaDamp(m_alpha); element->SetGravityOn(true); // Add element to mesh m_mesh->AddElement(element); } } // Switch off automatic gravity m_mesh->SetAutomaticGravity(false); } std::vector<std::shared_ptr<ChNodeFEAbase>> ANCFToroidalTire::GetConnectedNodes() const { std::vector<std::shared_ptr<fea::ChNodeFEAbase>> nodes; for (int i = 0; i < m_div_circumference; i++) { for (int j = 0; j <= m_div_width; j++) { int index = j + i * (m_div_width + 1); if (index % (m_div_width + 1) == 0) { nodes.push_back(std::dynamic_pointer_cast<ChNodeFEAbase>(m_mesh->GetNode(index))); nodes.push_back(std::dynamic_pointer_cast<ChNodeFEAbase>(m_mesh->GetNode(index + m_div_width))); } } } return nodes; } } // end namespace vehicle } // end namespace chrono
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts
test_scripts/MobileProjection/Phase2/smoke/013_two_apps_interaction.lua
6620
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/smartdevicelink/sdl_core/issues/2129 --------------------------------------------------------------------------------------------------- -- Description: -- In case: -- 1) Mobile app1 is registered and activated -- 2) Mobile app2 is registered -- 3) Mobile app1 is deactivated -- 4) Mobile app2 is activated -- SDL must: -- 1) Send 'OnHMIStatus' notification to app1 with appropriate values for 'audioStreamingState' -- and 'videoStreamingState' parameters when app1 is deactivated -- 2) Send 'OnHMIStatus' notification to app1 and app2 with appropriate values for 'audioStreamingState' -- and 'videoStreamingState' parameters when app2 is activated -- Particular values depends on app's 'appHMIType' and described in 'testCases' table below --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/MobileProjection/Phase2/common') local runner = require('user_modules/script_runner') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false config.defaultProtocolVersion = 3 --[[ Local Variables ]] local testCases = { [001] = { [1] = { t = "PROJECTION", m = true }, [2] = { t = "PROJECTION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" } }, [002] = { [1] = { t = "PROJECTION", m = true }, [2] = { t = "NAVIGATION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } }, [003] = { [1] = { t = "PROJECTION", m = false }, [2] = { t = "PROJECTION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "BACKGROUND", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" } }, [004] = { [1] = { t = "PROJECTION", m = false }, [2] = { t = "PROJECTION", m = true }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "BACKGROUND", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } }, [005] = { [1] = { t = "PROJECTION", m = false }, [2] = { t = "NAVIGATION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "BACKGROUND", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } }, [006] = { [1] = { t = "NAVIGATION", m = false }, [2] = { t = "PROJECTION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "STREAMABLE" } }, [007] = { [1] = { t = "NAVIGATION", m = false }, [2] = { t = "PROJECTION", m = true }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } }, [008] = { [1] = { t = "PROJECTION", m = true }, [2] = { t = "PROJECTION", m = true }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "BACKGROUND", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } }, [009] = { [1] = { t = "NAVIGATION", m = false }, [2] = { t = "NAVIGATION", m = false }, ohs1_1 = { l = "LIMITED", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" }, ohs1_2 = { l = "BACKGROUND", sc = "MAIN", aSS = "NOT_AUDIBLE", vSS = "NOT_STREAMABLE" }, ohs2_1 = { l = "FULL", sc = "MAIN", aSS = "AUDIBLE", vSS = "STREAMABLE" } } } --[[ Local Functions ]] local function deactivateApp(pApp1OHS) common.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated", { appID = common.getHMIAppId(1) }) common.getMobileSession(1):ExpectNotification("OnHMIStatus", { hmiLevel = pApp1OHS.l, systemContext = pApp1OHS.sc, audioStreamingState = pApp1OHS.aSS, videoStreamingState = pApp1OHS.vSS }) end local function activateApp(pApp1OHS, pApp2OHS) local requestId = common.getHMIConnection():SendRequest("SDL.ActivateApp", { appID = common.getHMIAppId(2) }) common.getHMIConnection():ExpectResponse(requestId) common.getMobileSession(2):ExpectNotification("OnHMIStatus", { hmiLevel = pApp2OHS.l, systemContext = pApp2OHS.sc, audioStreamingState = pApp2OHS.aSS, videoStreamingState = pApp2OHS.vSS }) common.getMobileSession(1):ExpectNotification("OnHMIStatus", { hmiLevel = pApp1OHS.l, systemContext = pApp1OHS.sc, audioStreamingState = pApp1OHS.aSS, videoStreamingState = pApp1OHS.vSS }) end --[[ Scenario ]] for n, tc in common.spairs(testCases) do runner.Title("TC[" .. string.format("%03d", n) .. "]: " .. "App1[hmiType:" .. tc[1].t .. ", isMedia:" .. tostring(tc[1].m) .. "], " .. "App2[hmiType:" .. tc[2].t .. ", isMedia:" .. tostring(tc[2].m) .. "]") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Set App 1 Config", common.setAppConfig, { 1, tc[1].t, tc[1].m }) runner.Step("Set App 2 Config", common.setAppConfig, { 2, tc[2].t, tc[2].m }) runner.Step("Register App 1", common.registerApp, { 1 }) runner.Step("Activate App 1", common.activateApp, { 1 }) runner.Step("Register App 2", common.registerApp, { 2 }) runner.Step("Deactivate App 1", deactivateApp, { tc.ohs1_1 }) runner.Step("Activate App 2", activateApp, { tc.ohs1_2, tc.ohs2_1 }) runner.Step("Clean sessions", common.cleanSessions) runner.Step("Stop SDL", common.postconditions) end
bsd-3-clause
teasim/helpers
source/transitionEnd.js
1004
import transition from "./transitionProps"; import directStyle from "./directStyle"; function parseDuration(node) { const str = directStyle(node, transition.duration); const mult = str.indexOf("ms") === -1 ? 1000 : 1; return parseFloat(str) * mult; } function transitionEnd(node, handler, duration) { const fakeEvent = { target: node, currentTarget: node }; if (!transition.end) { duration = 0; } else if (duration == null) { duration = parseDuration(node) || 0; } let backup; if (transition.end) { node.addEventListener(transition.end, done, false); backup = setTimeout(() => done(fakeEvent), (duration || 100) * 1.5); } else { setTimeout(done.bind(null, fakeEvent), 0); } function done(event) { if (event.target !== event.currentTarget) return; clearTimeout(backup); event.target.removeEventListener(transition.end, done); handler.call(this); } } transitionEnd.parseDuration = parseDuration; export default transitionEnd;
bsd-3-clause
elektropay/Cachet
app/Bus/Commands/IncidentUpdate/CreateIncidentUpdateCommand.php
1705
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Bus\Commands\IncidentUpdate; use CachetHQ\Cachet\Models\Incident; use CachetHQ\Cachet\Models\User; /** * This is the report incident update command. * * @author James Brooks <james@alt-three.com> */ final class CreateIncidentUpdateCommand { /** * The incident. * * @var \CachetHQ\Cachet\Models\Incident */ public $incident; /** * The incident status. * * @var int */ public $status; /** * The incident message. * * @var string */ public $message; /** * The user. * * @var \CachetHQ\Cachet\Models\User */ public $user; /** * The validation rules. * * @var string[] */ public $rules = [ 'incident' => 'required', 'status' => 'required|int|min:1|max:4', 'message' => 'required|string', 'user' => 'required', ]; /** * Create a new report incident update command instance. * * @param \CachetHQ\Cachet\Models\Incident $incident * @param string $status * @param string $message * @param \CachetHQ\Cachet\Models\User $user * * @return void */ public function __construct(Incident $incident, $status, $message, User $user) { $this->incident = $incident; $this->status = $status; $this->message = $message; $this->user = $user; } }
bsd-3-clause
gbhorwood/Clibelt
doxygen/docs/html/search/functions_a.js
238
var searchData= [ ['wraptoterminalwidth',['wrapToTerminalWidth',['../class_clibelt.html#af3d68df8f32f9dc3045bbf7e89f724bf',1,'Clibelt']]], ['write',['write',['../class_clibelt.html#ae2bf9f3d3d56241108d9d2c46728b95a',1,'Clibelt']]] ];
bsd-3-clause
yidashi/yii
plugins/prettify/Plugin.php
860
<?php /** * Created by PhpStorm. * User: yidashi * Date: 16/7/4 * Time: 下午1:46 */ namespace plugins\prettify; use yii\base\BootstrapInterface; use yii\web\View; use yii\base\Event; class Plugin extends \plugins\Plugin implements BootstrapInterface { public $info = [ 'author' => '易大师', 'version' => 'v1.0', 'id' => 'prettify', 'name' => '代码高亮', 'description' => '代码高亮模块' ]; public function bootstrap($app) { Event::on(View::className(), 'afterComment', [$this, 'run']); Event::on(View::className(), 'afterArticleView', [$this, 'run']); } public function run() { PrettifyAsset::register($this->view); $script = "$('pre').addClass('prettyprint linenums');prettyPrint();"; $this->view->registerJs($script); } }
bsd-3-clause
jcai19/smm_gem5
src/cpu/simple/base.cc
16710
/* * Copyright (c) 2010-2012 ARM Limited * Copyright (c) 2013 Advanced Micro Devices, Inc. * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt */ #include "arch/kernel_stats.hh" #include "arch/stacktrace.hh" #include "arch/tlb.hh" #include "arch/utility.hh" #include "arch/vtophys.hh" #include "base/loader/symtab.hh" #include "base/cp_annotate.hh" #include "base/cprintf.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/pollevent.hh" #include "base/trace.hh" #include "base/types.hh" #include "config/the_isa.hh" #include "cpu/simple/base.hh" #include "cpu/base.hh" #include "cpu/checker/cpu.hh" #include "cpu/checker/thread_context.hh" #include "cpu/exetrace.hh" #include "cpu/pred/bpred_unit.hh" #include "cpu/profile.hh" #include "cpu/simple_thread.hh" #include "cpu/smt.hh" #include "cpu/static_inst.hh" #include "cpu/thread_context.hh" #include "debug/Decode.hh" #include "debug/Fetch.hh" #include "debug/Quiesce.hh" #include "mem/mem_object.hh" #include "mem/packet.hh" #include "mem/request.hh" #include "params/BaseSimpleCPU.hh" #include "sim/byteswap.hh" #include "sim/debug.hh" #include "sim/faults.hh" #include "sim/full_system.hh" #include "sim/sim_events.hh" #include "sim/sim_object.hh" #include "sim/stats.hh" #include "sim/system.hh" using namespace std; using namespace TheISA; BaseSimpleCPU::BaseSimpleCPU(BaseSimpleCPUParams *p) : BaseCPU(p), branchPred(p->branchPred), traceData(NULL), thread(NULL) { if (FullSystem) thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb, p->isa[0]); else thread = new SimpleThread(this, /* thread_num */ 0, p->system, p->workload[0], p->itb, p->dtb, p->isa[0]); thread->setStatus(ThreadContext::Halted); tc = thread->getTC(); if (p->checker) { BaseCPU *temp_checker = p->checker; checker = dynamic_cast<CheckerCPU *>(temp_checker); checker->setSystem(p->system); // Manipulate thread context ThreadContext *cpu_tc = tc; tc = new CheckerThreadContext<ThreadContext>(cpu_tc, this->checker); } else { checker = NULL; } numInst = 0; startNumInst = 0; numOp = 0; startNumOp = 0; numLoad = 0; startNumLoad = 0; lastIcacheStall = 0; lastDcacheStall = 0; threadContexts.push_back(tc); fetchOffset = 0; stayAtPC = false; } BaseSimpleCPU::~BaseSimpleCPU() { } void BaseSimpleCPU::haltContext(ThreadID thread_num) { // for now, these are equivalent suspendContext(thread_num); } void BaseSimpleCPU::regStats() { using namespace Stats; BaseCPU::regStats(); numInsts .name(name() + ".committedInsts") .desc("Number of instructions committed") ; numOps .name(name() + ".committedOps") .desc("Number of ops (including micro ops) committed") ; numIntAluAccesses .name(name() + ".num_int_alu_accesses") .desc("Number of integer alu accesses") ; numFpAluAccesses .name(name() + ".num_fp_alu_accesses") .desc("Number of float alu accesses") ; numCallsReturns .name(name() + ".num_func_calls") .desc("number of times a function call or return occured") ; numCondCtrlInsts .name(name() + ".num_conditional_control_insts") .desc("number of instructions that are conditional controls") ; numIntInsts .name(name() + ".num_int_insts") .desc("number of integer instructions") ; numFpInsts .name(name() + ".num_fp_insts") .desc("number of float instructions") ; numIntRegReads .name(name() + ".num_int_register_reads") .desc("number of times the integer registers were read") ; numIntRegWrites .name(name() + ".num_int_register_writes") .desc("number of times the integer registers were written") ; numFpRegReads .name(name() + ".num_fp_register_reads") .desc("number of times the floating registers were read") ; numFpRegWrites .name(name() + ".num_fp_register_writes") .desc("number of times the floating registers were written") ; numCCRegReads .name(name() + ".num_cc_register_reads") .desc("number of times the CC registers were read") .flags(nozero) ; numCCRegWrites .name(name() + ".num_cc_register_writes") .desc("number of times the CC registers were written") .flags(nozero) ; numMemRefs .name(name()+".num_mem_refs") .desc("number of memory refs") ; numStoreInsts .name(name() + ".num_store_insts") .desc("Number of store instructions") ; numLoadInsts .name(name() + ".num_load_insts") .desc("Number of load instructions") ; notIdleFraction .name(name() + ".not_idle_fraction") .desc("Percentage of non-idle cycles") ; idleFraction .name(name() + ".idle_fraction") .desc("Percentage of idle cycles") ; numBusyCycles .name(name() + ".num_busy_cycles") .desc("Number of busy cycles") ; numIdleCycles .name(name()+".num_idle_cycles") .desc("Number of idle cycles") ; icacheStallCycles .name(name() + ".icache_stall_cycles") .desc("ICache total stall cycles") .prereq(icacheStallCycles) ; dcacheStallCycles .name(name() + ".dcache_stall_cycles") .desc("DCache total stall cycles") .prereq(dcacheStallCycles) ; icacheRetryCycles .name(name() + ".icache_retry_cycles") .desc("ICache total retry cycles") .prereq(icacheRetryCycles) ; dcacheRetryCycles .name(name() + ".dcache_retry_cycles") .desc("DCache total retry cycles") .prereq(dcacheRetryCycles) ; statExecutedInstType .init(Enums::Num_OpClass) .name(name() + ".op_class") .desc("Class of executed instruction") .flags(total | pdf | dist) ; for (unsigned i = 0; i < Num_OpClasses; ++i) { statExecutedInstType.subname(i, Enums::OpClassStrings[i]); } idleFraction = constant(1.0) - notIdleFraction; numIdleCycles = idleFraction * numCycles; numBusyCycles = (notIdleFraction)*numCycles; numBranches .name(name() + ".Branches") .desc("Number of branches fetched") .prereq(numBranches); numPredictedBranches .name(name() + ".predictedBranches") .desc("Number of branches predicted as taken") .prereq(numPredictedBranches); numBranchMispred .name(name() + ".BranchMispred") .desc("Number of branch mispredictions") .prereq(numBranchMispred); } void BaseSimpleCPU::resetStats() { // startNumInst = numInst; notIdleFraction = (_status != Idle); } void BaseSimpleCPU::serializeThread(ostream &os, ThreadID tid) { assert(_status == Idle || _status == Running); assert(tid == 0); thread->serialize(os); } void BaseSimpleCPU::unserializeThread(Checkpoint *cp, const string &section, ThreadID tid) { if (tid != 0) fatal("Trying to load more than one thread into a SimpleCPU\n"); thread->unserialize(cp, section); } void change_thread_state(ThreadID tid, int activate, int priority) { } Addr BaseSimpleCPU::dbg_vtophys(Addr addr) { return vtophys(tc, addr); } void BaseSimpleCPU::wakeup() { if (thread->status() != ThreadContext::Suspended) return; DPRINTF(Quiesce,"Suspended Processor awoke\n"); thread->activate(); } void BaseSimpleCPU::checkForInterrupts() { if (checkInterrupts(tc)) { Fault interrupt = interrupts->getInterrupt(tc); if (interrupt != NoFault) { fetchOffset = 0; interrupts->updateIntrInfo(tc); interrupt->invoke(tc); thread->decoder.reset(); } } } void BaseSimpleCPU::setupFetchRequest(Request *req) { Addr instAddr = thread->instAddr(); // set up memory request for instruction fetch DPRINTF(Fetch, "Fetch: PC:%08p\n", instAddr); Addr fetchPC = (instAddr & PCMask) + fetchOffset; req->setVirt(0, fetchPC, sizeof(MachInst), Request::INST_FETCH, instMasterId(), instAddr); } void BaseSimpleCPU::preExecute() { // maintain $r0 semantics thread->setIntReg(ZeroReg, 0); #if THE_ISA == ALPHA_ISA thread->setFloatReg(ZeroReg, 0.0); #endif // ALPHA_ISA // check for instruction-count-based events comInstEventQueue[0]->serviceEvents(numInst); system->instEventQueue.serviceEvents(system->totalNumInsts); // decode the instruction inst = gtoh(inst); TheISA::PCState pcState = thread->pcState(); if (isRomMicroPC(pcState.microPC())) { stayAtPC = false; curStaticInst = microcodeRom.fetchMicroop(pcState.microPC(), curMacroStaticInst); } else if (!curMacroStaticInst) { //We're not in the middle of a macro instruction StaticInstPtr instPtr = NULL; TheISA::Decoder *decoder = &(thread->decoder); //Predecode, ie bundle up an ExtMachInst //If more fetch data is needed, pass it in. Addr fetchPC = (pcState.instAddr() & PCMask) + fetchOffset; //if(decoder->needMoreBytes()) decoder->moreBytes(pcState, fetchPC, inst); //else // decoder->process(); //Decode an instruction if one is ready. Otherwise, we'll have to //fetch beyond the MachInst at the current pc. instPtr = decoder->decode(pcState); if (instPtr) { stayAtPC = false; thread->pcState(pcState); } else { stayAtPC = true; fetchOffset += sizeof(MachInst); } //If we decoded an instruction and it's microcoded, start pulling //out micro ops if (instPtr && instPtr->isMacroop()) { curMacroStaticInst = instPtr; curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC()); } else { curStaticInst = instPtr; } } else { //Read the next micro op from the macro op curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC()); } //If we decoded an instruction this "tick", record information about it. if (curStaticInst) { #if TRACING_ON traceData = tracer->getInstRecord(curTick(), tc, curStaticInst, thread->pcState(), curMacroStaticInst); DPRINTF(Decode,"Decode: Decoded %s instruction: %#x\n", curStaticInst->getName(), curStaticInst->machInst); #endif // TRACING_ON } if (branchPred && curStaticInst && curStaticInst->isControl()) { // Use a fake sequence number since we only have one // instruction in flight at the same time. const InstSeqNum cur_sn(0); const ThreadID tid(0); pred_pc = thread->pcState(); const bool predict_taken( branchPred->predict(curStaticInst, cur_sn, pred_pc, tid)); if (predict_taken) ++numPredictedBranches; } } void BaseSimpleCPU::postExecute() { assert(curStaticInst); TheISA::PCState pc = tc->pcState(); Addr instAddr = pc.instAddr(); if (FullSystem && thread->profile) { bool usermode = TheISA::inUserMode(tc); thread->profilePC = usermode ? 1 : instAddr; ProfileNode *node = thread->profile->consume(tc, curStaticInst); if (node) thread->profileNode = node; } if (curStaticInst->isMemRef()) { numMemRefs++; } if (curStaticInst->isLoad()) { ++numLoad; comLoadEventQueue[0]->serviceEvents(numLoad); } if (CPA::available()) { CPA::cpa()->swAutoBegin(tc, pc.nextInstAddr()); } if (curStaticInst->isControl()) { ++numBranches; } /* Power model statistics */ //integer alu accesses if (curStaticInst->isInteger()){ numIntAluAccesses++; numIntInsts++; } //float alu accesses if (curStaticInst->isFloating()){ numFpAluAccesses++; numFpInsts++; } //number of function calls/returns to get window accesses if (curStaticInst->isCall() || curStaticInst->isReturn()){ numCallsReturns++; } //the number of branch predictions that will be made if (curStaticInst->isCondCtrl()){ numCondCtrlInsts++; } //result bus acceses if (curStaticInst->isLoad()){ numLoadInsts++; } if (curStaticInst->isStore()){ numStoreInsts++; } /* End power model statistics */ statExecutedInstType[curStaticInst->opClass()]++; if (FullSystem) traceFunctions(instAddr); if (traceData) { traceData->dump(); delete traceData; traceData = NULL; } // Call CPU instruction commit probes probeInstCommit(curStaticInst); } void BaseSimpleCPU::advancePC(const Fault &fault) { const bool branching(thread->pcState().branching()); //Since we're moving to a new pc, zero out the offset fetchOffset = 0; if (fault != NoFault) { curMacroStaticInst = StaticInst::nullStaticInstPtr; fault->invoke(tc, curStaticInst); thread->decoder.reset(); } else { if (curStaticInst) { if (curStaticInst->isLastMicroop()) curMacroStaticInst = StaticInst::nullStaticInstPtr; TheISA::PCState pcState = thread->pcState(); TheISA::advancePC(pcState, curStaticInst); thread->pcState(pcState); } } if (branchPred && curStaticInst && curStaticInst->isControl()) { // Use a fake sequence number since we only have one // instruction in flight at the same time. const InstSeqNum cur_sn(0); const ThreadID tid(0); if (pred_pc == thread->pcState()) { // Correctly predicted branch branchPred->update(cur_sn, tid); } else { // Mis-predicted branch branchPred->squash(cur_sn, pcState(), branching, tid); ++numBranchMispred; } } } void BaseSimpleCPU::startup() { BaseCPU::startup(); thread->startup(); }
bsd-3-clause
aadsm/react-devtools
frontend/SearchPane.js
4283
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * $FLowFixMe * - thinks all react component classes must inherit from React.Component */ 'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var SettingsPane = require('./SettingsPane'); var TreeView = require('./TreeView'); var {PropTypes} = React; var decorate = require('./decorate'); type EventLike = { keyCode: number, preventDefault: () => void, stopPropagation: () => void, }; class SearchPane extends React.Component { input: ?HTMLElement; _key: (evt: EventLike) => void; constructor(props) { super(props); this.state = {focused: false}; } componentDidMount() { this._key = this.onDocumentKeyDown.bind(this); var doc = ReactDOM.findDOMNode(this).ownerDocument; // capture=true is needed to prevent chrome devtools console popping up doc.addEventListener('keydown', this._key, true); } componentWillUnmount() { var doc = ReactDOM.findDOMNode(this).ownerDocument; doc.removeEventListener('keydown', this._key, true); } onDocumentKeyDown(e) { if (e.keyCode === 191) { // forward slash var doc = ReactDOM.findDOMNode(this).ownerDocument; if (!this.input || doc.activeElement === this.input) { return; } this.input.focus(); e.preventDefault(); } if (e.keyCode === 27) { // escape if (!this.props.searchText && !this.state.focused) { return; } e.stopPropagation(); e.preventDefault(); this.cancel(); } } cancel() { this.props.onChangeSearch(''); if (this.input) { this.input.blur(); } } onKeyDown(key) { if (key === 'Enter' && this.input) { this.props.selectFirstSearchResult(); } } render() { var inputStyle = styles.input; if (this.props.searchText || this.state.focused) { inputStyle = {...inputStyle, ...styles.highlightedInput}; } return ( <div style={styles.container}> <SettingsPane /> <TreeView reload={this.props.reload} /> <div style={styles.searchBox}> <input style={inputStyle} ref={i => this.input = i} value={this.props.searchText} onFocus={() => this.setState({focused: true})} onBlur={() => this.setState({focused: false})} onKeyDown={e => this.onKeyDown(e.key)} placeholder="Search by Component Name" onChange={e => this.props.onChangeSearch(e.target.value)} /> {!!this.props.searchText && <div onClick={this.cancel.bind(this)} style={styles.cancelButton}> &times; </div>} </div> </div> ); } } SearchPane.propTypes = { reload: PropTypes.func, searchText: PropTypes.string, onChangeSearch: PropTypes.func, selectFirstSearchResult: PropTypes.func, }; var Wrapped = decorate({ listeners(props) { return ['searchText']; }, props(store) { return { searchText: store.searchText, onChangeSearch: text => store.changeSearch(text), selectFirstSearchResult: store.selectFirstSearchResult.bind(store), }; }, }, SearchPane); var styles = { container: { flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, }, searchBox: { display: 'flex', flexShrink: 0, position: 'relative', }, cancelButton: { fontSize: '13px', padding: '0 4px', borderRadius: '10px', height: '17px', position: 'absolute', cursor: 'pointer', right: '7px', top: '8px', color: 'white', backgroundColor: 'rgb(255, 137, 137)', }, input: { flex: 1, fontSize: '18px', padding: '5px 10px', border: 'none', transition: 'border-top-color .2s ease, background-color .2s ease', borderTop: '1px solid #ccc', borderTopColor: '#ccc', outline: 'none', }, highlightedInput: { borderTopColor: 'aqua', backgroundColor: '#EEFFFE', }, }; module.exports = Wrapped;
bsd-3-clause
scheib/chromium
third_party/blink/renderer/core/paint/paint_timing.cc
15657
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/paint/paint_timing.h" #include <memory> #include <utility> #include "base/metrics/histogram_macros.h" #include "base/time/default_tick_clock.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/interactive_detector.h" #include "third_party/blink/renderer/core/loader/progress_tracker.h" #include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/timing/dom_window_performance.h" #include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/platform/graphics/paint/ignore_paint_timing_scope.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/document_resource_coordinator.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/blink/renderer/platform/wtf/wtf.h" namespace blink { namespace { WindowPerformance* GetPerformanceInstance(LocalFrame* frame) { WindowPerformance* performance = nullptr; if (frame && frame->DomWindow()) { performance = DOMWindowPerformance::performance(*frame->DomWindow()); } return performance; } } // namespace class RecodingTimeAfterBackForwardCacheRestoreFrameCallback : public FrameCallback { public: RecodingTimeAfterBackForwardCacheRestoreFrameCallback( PaintTiming* paint_timing, wtf_size_t record_index) : paint_timing_(paint_timing), record_index_(record_index) {} ~RecodingTimeAfterBackForwardCacheRestoreFrameCallback() override = default; void Invoke(double high_res_time_ms) override { // Instead of |high_res_time_ms|, use PaintTiming's |clock_->NowTicks()| for // consistency and testability. paint_timing_->SetRequestAnimationFrameAfterBackForwardCacheRestore( record_index_, count_); count_++; if (count_ == WebPerformance:: kRequestAnimationFramesToRecordAfterBackForwardCacheRestore) { paint_timing_->NotifyPaintTimingChanged(); return; } if (auto* frame = paint_timing_->GetFrame()) { if (auto* document = frame->GetDocument()) { document->RequestAnimationFrame(this); } } } void Trace(Visitor* visitor) const override { visitor->Trace(paint_timing_); FrameCallback::Trace(visitor); } private: Member<PaintTiming> paint_timing_; const wtf_size_t record_index_; size_t count_ = 0; }; // static const char PaintTiming::kSupplementName[] = "PaintTiming"; // static PaintTiming& PaintTiming::From(Document& document) { PaintTiming* timing = Supplement<Document>::From<PaintTiming>(document); if (!timing) { timing = MakeGarbageCollected<PaintTiming>(document); ProvideTo(document, timing); } return *timing; } void PaintTiming::MarkFirstPaint() { // Test that |first_paint_| is non-zero here, as well as in setFirstPaint, so // we avoid invoking monotonicallyIncreasingTime() on every call to // markFirstPaint(). if (!first_paint_.is_null()) return; DCHECK_EQ(IgnorePaintTimingScope::IgnoreDepth(), 0); SetFirstPaint(clock_->NowTicks()); } void PaintTiming::MarkFirstContentfulPaint() { // Test that |first_contentful_paint_| is non-zero here, as well as in // setFirstContentfulPaint, so we avoid invoking // monotonicallyIncreasingTime() on every call to // markFirstContentfulPaint(). if (!first_contentful_paint_.is_null()) return; if (IgnorePaintTimingScope::IgnoreDepth() > 0) return; SetFirstContentfulPaint(clock_->NowTicks()); } void PaintTiming::MarkFirstImagePaint() { if (!first_image_paint_.is_null()) return; DCHECK_EQ(IgnorePaintTimingScope::IgnoreDepth(), 0); first_image_paint_ = clock_->NowTicks(); SetFirstContentfulPaint(first_image_paint_); RegisterNotifyPresentationTime(PaintEvent::kFirstImagePaint); } void PaintTiming::MarkFirstEligibleToPaint() { if (!first_eligible_to_paint_.is_null()) return; first_eligible_to_paint_ = clock_->NowTicks(); NotifyPaintTimingChanged(); } // We deliberately use |first_paint_| here rather than // |first_paint_presentation_|, because |first_paint_presentation_| is set // asynchronously and we need to be able to rely on a synchronous check that // SetFirstPaintPresentation hasn't been scheduled or run. void PaintTiming::MarkIneligibleToPaint() { if (first_eligible_to_paint_.is_null() || !first_paint_.is_null()) return; first_eligible_to_paint_ = base::TimeTicks(); NotifyPaintTimingChanged(); } void PaintTiming::SetFirstMeaningfulPaintCandidate(base::TimeTicks timestamp) { if (!first_meaningful_paint_candidate_.is_null()) return; first_meaningful_paint_candidate_ = timestamp; if (GetFrame() && GetFrame()->View() && !GetFrame()->View()->IsAttached()) { GetFrame()->GetFrameScheduler()->OnFirstMeaningfulPaint(); } } void PaintTiming::SetFirstMeaningfulPaint( base::TimeTicks presentation_time, FirstMeaningfulPaintDetector::HadUserInput had_input) { DCHECK(first_meaningful_paint_presentation_.is_null()); DCHECK(!presentation_time.is_null()); TRACE_EVENT_MARK_WITH_TIMESTAMP2("loading,rail,devtools.timeline", "firstMeaningfulPaint", presentation_time, "frame", ToTraceValue(GetFrame()), "afterUserInput", had_input); // Notify FMP for UMA only if there's no user input before FMP, so that layout // changes caused by user interactions wouldn't be considered as FMP. if (had_input == FirstMeaningfulPaintDetector::kNoUserInput) { first_meaningful_paint_presentation_ = presentation_time; NotifyPaintTimingChanged(); } } void PaintTiming::NotifyPaint(bool is_first_paint, bool text_painted, bool image_painted) { if (IgnorePaintTimingScope::IgnoreDepth() > 0) return; if (is_first_paint) MarkFirstPaint(); if (text_painted) MarkFirstContentfulPaint(); if (image_painted) MarkFirstImagePaint(); fmp_detector_->NotifyPaint(); GetFrame()->View()->GetMobileFriendlinessChecker()->NotifyPaint(); } void PaintTiming::OnPortalActivate() { last_portal_activated_presentation_ = base::TimeTicks(); RegisterNotifyPresentationTime(PaintEvent::kPortalActivatedPaint); } void PaintTiming::SetPortalActivatedPaint(base::TimeTicks stamp) { DCHECK(last_portal_activated_presentation_.is_null()); last_portal_activated_presentation_ = stamp; NotifyPaintTimingChanged(); } void PaintTiming::SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; } void PaintTiming::Trace(Visitor* visitor) const { visitor->Trace(fmp_detector_); Supplement<Document>::Trace(visitor); } PaintTiming::PaintTiming(Document& document) : Supplement<Document>(document), fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)), clock_(base::DefaultTickClock::GetInstance()) {} LocalFrame* PaintTiming::GetFrame() const { return GetSupplementable()->GetFrame(); } void PaintTiming::NotifyPaintTimingChanged() { if (GetSupplementable()->Loader()) GetSupplementable()->Loader()->DidChangePerformanceTiming(); } void PaintTiming::SetFirstPaint(base::TimeTicks stamp) { if (!first_paint_.is_null()) return; DCHECK_EQ(IgnorePaintTimingScope::IgnoreDepth(), 0); first_paint_ = stamp; RegisterNotifyPresentationTime(PaintEvent::kFirstPaint); } void PaintTiming::SetFirstContentfulPaint(base::TimeTicks stamp) { if (!first_contentful_paint_.is_null()) return; DCHECK_EQ(IgnorePaintTimingScope::IgnoreDepth(), 0); SetFirstPaint(stamp); first_contentful_paint_ = stamp; RegisterNotifyPresentationTime(PaintEvent::kFirstContentfulPaint); // Restart commits that may have been deferred. LocalFrame* frame = GetFrame(); if (!frame || !frame->IsMainFrame()) return; frame->View()->OnFirstContentfulPaint(); if (frame->GetFrameScheduler()) frame->GetFrameScheduler()->OnFirstContentfulPaintInMainFrame(); } void PaintTiming::RegisterNotifyPresentationTime(PaintEvent event) { RegisterNotifyPresentationTime( CrossThreadBindOnce(&PaintTiming::ReportPresentationTime, WrapCrossThreadWeakPersistent(this), event)); } void PaintTiming:: RegisterNotifyFirstPaintAfterBackForwardCacheRestorePresentationTime( wtf_size_t index) { RegisterNotifyPresentationTime(CrossThreadBindOnce( &PaintTiming:: ReportFirstPaintAfterBackForwardCacheRestorePresentationTime, WrapCrossThreadWeakPersistent(this), index)); } void PaintTiming::RegisterNotifyPresentationTime(ReportTimeCallback callback) { // ReportPresentationTime will queue a presentation-promise, the callback is // called when the compositor submission of the current render frame completes // or fails to happen. if (!GetFrame() || !GetFrame()->GetPage()) return; GetFrame()->GetPage()->GetChromeClient().NotifyPresentationTime( *GetFrame(), std::move(callback)); } void PaintTiming::ReportPresentationTime(PaintEvent event, base::TimeTicks timestamp) { DCHECK(IsMainThread()); switch (event) { case PaintEvent::kFirstPaint: SetFirstPaintPresentation(timestamp); return; case PaintEvent::kFirstContentfulPaint: SetFirstContentfulPaintPresentation(timestamp); return; case PaintEvent::kFirstImagePaint: SetFirstImagePaintPresentation(timestamp); return; case PaintEvent::kPortalActivatedPaint: SetPortalActivatedPaint(timestamp); return; default: NOTREACHED(); } } void PaintTiming::ReportFirstPaintAfterBackForwardCacheRestorePresentationTime( wtf_size_t index, base::TimeTicks timestamp) { DCHECK(IsMainThread()); SetFirstPaintAfterBackForwardCacheRestorePresentation(timestamp, index); } void PaintTiming::SetFirstPaintPresentation(base::TimeTicks stamp) { DCHECK(first_paint_presentation_.is_null()); first_paint_presentation_ = stamp; probe::PaintTiming(GetSupplementable(), "firstPaint", first_paint_presentation_.since_origin().InSecondsF()); WindowPerformance* performance = GetPerformanceInstance(GetFrame()); if (performance) performance->AddFirstPaintTiming(first_paint_presentation_); NotifyPaintTimingChanged(); } void PaintTiming::SetFirstContentfulPaintPresentation(base::TimeTicks stamp) { DCHECK(first_contentful_paint_presentation_.is_null()); TRACE_EVENT_INSTANT_WITH_TIMESTAMP0("benchmark,loading", "GlobalFirstContentfulPaint", TRACE_EVENT_SCOPE_GLOBAL, stamp); first_contentful_paint_presentation_ = stamp; probe::PaintTiming( GetSupplementable(), "firstContentfulPaint", first_contentful_paint_presentation_.since_origin().InSecondsF()); WindowPerformance* performance = GetPerformanceInstance(GetFrame()); if (performance) { performance->AddFirstContentfulPaintTiming( first_contentful_paint_presentation_); } if (GetFrame()) GetFrame()->Loader().Progress().DidFirstContentfulPaint(); NotifyPaintTimingChanged(); fmp_detector_->NotifyFirstContentfulPaint( first_contentful_paint_presentation_); InteractiveDetector* interactive_detector = InteractiveDetector::From(*GetSupplementable()); if (interactive_detector) { interactive_detector->OnFirstContentfulPaint( first_contentful_paint_presentation_); } auto* coordinator = GetSupplementable()->GetResourceCoordinator(); if (coordinator && GetFrame() && GetFrame()->IsMainFrame()) { PerformanceTiming* timing = performance->timing(); base::TimeDelta fcp = stamp - timing->NavigationStartAsMonotonicTime(); coordinator->OnFirstContentfulPaint(fcp); } } void PaintTiming::SetFirstImagePaintPresentation(base::TimeTicks stamp) { DCHECK(first_image_paint_presentation_.is_null()); first_image_paint_presentation_ = stamp; probe::PaintTiming( GetSupplementable(), "firstImagePaint", first_image_paint_presentation_.since_origin().InSecondsF()); NotifyPaintTimingChanged(); } void PaintTiming::SetFirstPaintAfterBackForwardCacheRestorePresentation( base::TimeTicks stamp, wtf_size_t index) { // The elements are allocated when the page is restored from the cache. DCHECK_GE(first_paints_after_back_forward_cache_restore_presentation_.size(), index); DCHECK(first_paints_after_back_forward_cache_restore_presentation_[index] .is_null()); first_paints_after_back_forward_cache_restore_presentation_[index] = stamp; NotifyPaintTimingChanged(); } void PaintTiming::SetRequestAnimationFrameAfterBackForwardCacheRestore( wtf_size_t index, size_t count) { auto now = clock_->NowTicks(); // The elements are allocated when the page is restored from the cache. DCHECK_LT(index, request_animation_frames_after_back_forward_cache_restore_.size()); auto& current_rafs = request_animation_frames_after_back_forward_cache_restore_[index]; DCHECK_LT(count, current_rafs.size()); DCHECK_EQ(current_rafs[count], base::TimeTicks()); current_rafs[count] = now; } void PaintTiming::OnRestoredFromBackForwardCache() { // Allocate the last element with 0, which indicates that the first paint // after this navigation doesn't happen yet. wtf_size_t index = first_paints_after_back_forward_cache_restore_presentation_.size(); DCHECK_EQ(index, request_animation_frames_after_back_forward_cache_restore_.size()); first_paints_after_back_forward_cache_restore_presentation_.push_back( base::TimeTicks()); RegisterNotifyFirstPaintAfterBackForwardCacheRestorePresentationTime(index); request_animation_frames_after_back_forward_cache_restore_.push_back( RequestAnimationFrameTimesAfterBackForwardCacheRestore{}); LocalFrame* frame = GetFrame(); if (!frame->IsMainFrame()) { return; } Document* document = frame->GetDocument(); DCHECK(document); // Cancel if there is already a registered callback. if (raf_after_bfcache_restore_measurement_callback_id_) { document->CancelAnimationFrame( raf_after_bfcache_restore_measurement_callback_id_); raf_after_bfcache_restore_measurement_callback_id_ = 0; } raf_after_bfcache_restore_measurement_callback_id_ = document->RequestAnimationFrame( MakeGarbageCollected< RecodingTimeAfterBackForwardCacheRestoreFrameCallback>(this, index)); } } // namespace blink
bsd-3-clause
dustcloud/dustlink
views/web/AppsPages.py
19763
import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('AppsPages') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import random from dustWeb import web from DustLinkData import DataVaultException, \ DustLinkData from dustWeb import WebPage from dustWeb import WebPageDyn from dustWeb import WebHandler from dustWeb.viz import VizForm from dustWeb.viz import VizHtml from dustWeb.viz import VizAppFields from dustWeb.thirdparty import gviz_api #============================ object ========================================== class AppsPages(WebPageDyn.WebPageDyn): #===== web handlers (private classes) class pageApps(WebHandler.WebHandler): def getPage(self,subResource,username): global webServer global thisWebApp username = web.ctx.session.username currentPath = WebPage.WebPage.urlStringTolist(web.ctx.path) page = thisWebApp.createPage( username = username, currentPath = currentPath, visualizations = [ VizForm.VizForm( webServer = webServer, username = username, resourcePath = currentPath, subResourcePath = 'add', title = 'Add an Application', ), VizForm.VizForm( webServer = webServer, username = username, resourcePath = currentPath, subResourcePath = 'delete', title = 'Delete an Application', ), ], ) return page def getData(self,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['add']: return [ { 'name': 'appname', 'value': '', 'type': 'text', }, ] elif subResource==['delete']: appnames = dld.getAppNames(username=username) return [ { 'name': 'appname', 'value': None, 'optionDisplay': appnames, 'optionValue': appnames, 'type': 'select', 'editable': True, }, ] else: raise web.notfound() def postData(self,receivedData,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['add']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.addApp( receivedData['appname'], username=username, ) elif subResource==['delete']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.deleteApp( receivedData['appname'], username=username, ) else: raise web.notfound() class pageAppsSub(WebPageDyn.WebHandlerDyn): #==================== GET ============================================= def getPageDyn(self,dynPath,subResource,username): global webServer global thisWebApp username = web.ctx.session.username currentPath = WebPage.WebPage.urlStringTolist(web.ctx.path) page = thisWebApp.createPage( username = username, currentPath = currentPath, visualizations = [ VizAppFields.VizAppFields( webServer = webServer, username = username, resourcePath = currentPath, subResourcePath = 'appfields', forbidAutorefresh = True, autorefresh = False, title = self.getDynPath() ), ], ) return page def getDataDyn(self,dynPath,subResource,username): appname = dynPath dld = DustLinkData.DustLinkData() if subResource==['appfields']: with dld.dataLock: return { 'description': dld.getAppDescription(appname,username=username), 'transport': self._transportDbToWeb( dld.getAppTransport( appname, username=username, ) ), 'fromMote': self._fieldsDbToWeb( dld.getAppFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE, username=username, ) ), 'toMote': self._fieldsDbToWeb( dld.getAppFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, username=username, ) ), } else: raise web.notfound() #==================== POST ============================================ def postDataDyn(self,receivedData,dynPath,subResource,username): appname = dynPath dld = DustLinkData.DustLinkData() if subResource==['appfields']: with dld.dataLock: # description self._postDataDynDescription( appname, receivedData['description'], username, ) # transport self._postDataDynTransport( appname, receivedData['transport'], username, ) # fromMote self._postDataDynFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE, receivedData['fromMote'], username, ) # toMote self._postDataDynFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, receivedData['toMote'], username, ) else: raise web.notfound() def _postDataDynDescription(self,appname,description,username): dld = DustLinkData.DustLinkData() dld.setAppDescription( appname=appname, description=description, username=username, ) def _postDataDynTransport(self,appname,receivedData,username): (dbType,dbResource) = self._transportWebToDb(receivedData) dld = DustLinkData.DustLinkData() dld.setAppTransport( appname=appname, transportType=dbType, resource=dbResource, username=username, ) def _postDataDynFields(self,appname,direction,receivedData,username): updatefields = True dbFields = self._fieldsWebToDb(receivedData) dld = DustLinkData.DustLinkData() with dld.dataLock: if direction==DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE: # get the current fields setting for FROMMOTE direction (as admin) currentFromFields = dld.getAppFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE ) updatefields = (not (currentFromFields==dbFields)) if currentFromFields==dbFields: updatefields = False # update fields if updatefields: # update DustLinkData (do first) dld.setAppFields( appname=appname, direction=direction, fieldFormats=dbFields['fieldFormats'], fieldNames=dbFields['fieldNames'], username=username ) if direction==DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE: # the format of the data received from this application has # changed. This means that data already received from apps # using that application has been parsed incorrectly. It is # hard to convert old to new parsed data, so we delete the # data received from that application, on all motes. We do # this as admin for mac in dld.getMoteMacs(): try: dld.deleteData(mac,appname) except ValueError: pass # happens when app not attached to mote #==================== helpers ========================================= structToString = [ ('b', 'INT8' ), ('B', 'INT8U' ), ('h', 'INT16' ), ('H', 'INT16U'), ('l', 'INT32' ), ('L', 'INT32U'), ] @classmethod def _transportDbToWeb(self,dbTransport): ''' \brief Convert the transport description as read from DustLinkData into a format usable by the VizAppFields visualization. \param dbTransport The transport description of the app, as returned by DustLinkData.getAppTransport(), i.e. a tuple (transport,resource). \returns The same transport information, formatted as a dictionary, e.g. { 'type': 'UDP', 'resource': 61626, } ''' transportType = dbTransport[0] transportResource = dbTransport[1] if transportType: transportTypeString = transportType else: transportTypeString = '' if not transportResource: transportResourceString = '' elif isinstance(transportResource,tuple): transportResourceString = ','.join([str(r) for r in transportResource]) else: transportResourceString = str(transportResource) return { 'type': transportTypeString, 'resource': transportResourceString, } @classmethod def _fieldsDbToWeb(self,dbFields): ''' \brief Convert the field description as read from DustLinkData into a format usable by the VizAppFields visualization. \param dbFields The fields description of the app, as returned by DustLinkData.getAppFields(). \returns The same field information, formatted as a dictionary, e.g. { 'endianness': 'little-endian', 'fieldRows': [ { 'format': 'INT16', 'name': 'toMote1', }, { 'format': 'INT32', 'name': 'toMote2', }, { 'format': 'INT32U', 'name': 'toMote3', }, ], } ''' returnVal = {} fieldFormats = dbFields['fieldFormats'] fieldNames = dbFields['fieldNames'] # endianness if fieldFormats: if fieldFormats.startswith('<'): returnVal['endianness'] = 'little-endian' fieldFormats = fieldFormats[1:] elif fieldFormats.startswith('>'): returnVal['endianness'] = 'big-endian' fieldFormats = fieldFormats[1:] else: raise SystemError("No endianness specified in format \"{0}\"".format(fieldFormats)) else: returnVal['endianness'] = None # fieldRows returnVal['fieldRows'] = [] if fieldFormats: for c in fieldFormats: thisField = {} for s in self.structToString: if s[0]==c: thisField['format'] = s[1] thisField['name'] = fieldNames[len(returnVal['fieldRows'])] returnVal['fieldRows'].append(thisField) return returnVal @classmethod def _transportWebToDb(self,webTransport): # type if not webTransport['type']: dbType = None else: dbType = str(webTransport['type']) # resource if not webTransport['resource']: dbResource = None elif dbType == DustLinkData.DustLinkData.APP_TRANSPORT_OAP: dbResource = [] for c in webTransport['resource'].split(','): if c: dbResource += [int(c)] dbResource = tuple(dbResource) else: dbResource = int(webTransport['resource']) return (dbType,dbResource) @classmethod def _fieldsWebToDb(self,webFields): returnVal = {} returnVal['fieldFormats'] = '' returnVal['fieldNames'] = [] # endianness if webFields['endianness']=='little-endian': returnVal['fieldFormats'] += '<' elif webFields['endianness']=='big-endian': returnVal['fieldFormats'] += '>' elif (not webFields['endianness']): returnVal['fieldFormats'] += '>' else: raise SystemError("unexpected endianness {0}".format(webFields['endianness'])) # fieldRows for f in webFields['fieldRows']: for s in self.structToString: if s[1]==f['format']: returnVal['fieldFormats'] += str(s[0]) returnVal['fieldNames'].append(str(f['name'])) if (not returnVal['fieldFormats']) or (returnVal['fieldFormats']=='<') or (returnVal['fieldFormats']=='>'): returnVal['fieldFormats'] = None if not returnVal['fieldNames']: returnVal['fieldNames'] = None return returnVal def subPageLister(self): username = str(web.ctx.session.username) dld = DustLinkData.DustLinkData() try: return [ { 'url': u, 'title': u, } for u in dld.getAppNames(username=username) ] except DataVaultException.Unauthorized: return [] def __init__(self, webServer_param): global webServer global thisWebApp # local variables self.webServer = webServer_param # global variables webServer = self.webServer thisWebApp = self # initialize parent class WebPageDyn.WebPageDyn.__init__(self,webServer = self.webServer, url = 'apps', title = 'Apps', webHandler = self.pageApps, subPageLister = self.subPageLister, subPageHandler = self.pageAppsSub)
bsd-3-clause
eltondias/SistemaCobrancaBG
vendor/zendframework/zendframework/library/Zend/Db/RowGateway/RowGateway.php
1539
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Db\RowGateway; use Zend\Db\Adapter\Adapter; use Zend\Db\Sql\Sql; class RowGateway extends AbstractRowGateway { /** * Constructor * * @param string $primaryKeyColumn * @param string|\Zend\Db\Sql\TableIdentifier $table * @param Adapter|Sql $adapterOrSql * @throws Exception\InvalidArgumentException */ public function __construct($primaryKeyColumn, $table, $adapterOrSql = null) { // setup primary key $this->primaryKeyColumn = (array) $primaryKeyColumn; // set table $this->table = $table; // set Sql object if ($adapterOrSql instanceof Sql) { $this->sql = $adapterOrSql; } elseif ($adapterOrSql instanceof Adapter) { $this->sql = new Sql($adapterOrSql, $this->table); } else { throw new Exception\InvalidArgumentException('A valid Sql object was not provided.'); } if ($this->sql->getTable() !== $this->table) { throw new Exception\InvalidArgumentException('The Sql object provided does not have a table that matches this row object'); } $this->initialize(); } }
bsd-3-clause
uq-eresearch/gbr-cat
CRESIS/AJAX_APP/src/main/webapp/cresis/js/source/widgets/form/Checkbox.js
4473
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Checkbox * @extends Ext.form.Field * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields. * @constructor * Creates a new Checkbox * @param {Object} config Configuration options */ Ext.form.Checkbox = Ext.extend(Ext.form.Field, { /** * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined) */ focusClass : undefined, /** * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field") */ fieldClass: "x-form-field", /** * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false) */ checked: false, /** * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to * {tag: "input", type: "checkbox", autocomplete: "off"}) */ defaultAutoCreate : { tag: "input", type: 'checkbox', autocomplete: "off"}, /** * @cfg {String} boxLabel The text that appears beside the checkbox */ /** * @cfg {String} inputValue The value that should go into the generated input element's value attribute */ // private initComponent : function(){ Ext.form.Checkbox.superclass.initComponent.call(this); this.addEvents( /** * @event check * Fires when the checkbox is checked or unchecked. * @param {Ext.form.Checkbox} this This checkbox * @param {Boolean} checked The new checked value */ 'check' ); }, // private onResize : function(){ Ext.form.Checkbox.superclass.onResize.apply(this, arguments); if(!this.boxLabel){ this.el.alignTo(this.wrap, 'c-c'); } }, // private initEvents : function(){ Ext.form.Checkbox.superclass.initEvents.call(this); this.el.on("click", this.onClick, this); this.el.on("change", this.onClick, this); }, // private getResizeEl : function(){ return this.wrap; }, // private getPositionEl : function(){ return this.wrap; }, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ markInvalid : Ext.emptyFn, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ clearInvalid : Ext.emptyFn, // private onRender : function(ct, position){ Ext.form.Checkbox.superclass.onRender.call(this, ct, position); if(this.inputValue !== undefined){ this.el.dom.value = this.inputValue; } this.wrap = this.el.wrap({cls: "x-form-check-wrap"}); if(this.boxLabel){ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel}); } if(this.checked){ this.setValue(true); }else{ this.checked = this.el.dom.checked; } }, // private onDestroy : function(){ if(this.wrap){ this.wrap.remove(); } Ext.form.Checkbox.superclass.onDestroy.call(this); }, // private initValue : Ext.emptyFn, /** * Returns the checked state of the checkbox. * @return {Boolean} True if checked, else false */ getValue : function(){ if(this.rendered){ return this.el.dom.checked; } return false; }, // private onClick : function(){ if(this.el.dom.checked != this.checked){ this.setValue(this.el.dom.checked); } }, /** * Sets the checked state of the checkbox. * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it. */ setValue : function(v){ this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on'); if(this.el && this.el.dom){ this.el.dom.checked = this.checked; this.el.dom.defaultChecked = this.checked; } this.fireEvent("check", this, this.checked); } }); Ext.reg('checkbox', Ext.form.Checkbox);
bsd-3-clause
uniqna/uniqna
user/migrations/0004_auto_20170627_2322.py
903
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-27 17:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0003_student_notification_emails'), ] operations = [ migrations.RemoveField( model_name='student', name='course', ), migrations.RemoveField( model_name='student', name='grad_year', ), migrations.RemoveField( model_name='student', name='school', ), migrations.RemoveField( model_name='student', name='university', ), migrations.AlterField( model_name='student', name='bio', field=models.CharField(blank=True, default='', max_length=256), ), ]
bsd-3-clause
keishi/chromium
content/browser/android/browser_jni_registrar.cc
2069
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/android/browser_jni_registrar.h" #include "base/android/jni_android.h" #include "base/android/jni_registrar.h" #include "content/browser/android/android_browser_process.h" #include "content/browser/android/content_settings.h" #include "content/browser/android/content_video_view.h" #include "content/browser/android/content_view_client.h" #include "content/browser/android/content_view_core_impl.h" #include "content/browser/android/content_view_statics.h" #include "content/browser/android/download_controller.h" #include "content/browser/android/sandboxed_process_launcher.h" #include "content/browser/android/touch_point.h" #include "content/browser/geolocation/location_api_adapter_android.h" #include "content/common/android/device_info.h" namespace { base::android::RegistrationMethod kContentRegisteredMethods[] = { { "AndroidLocationApiAdapter", AndroidLocationApiAdapter::RegisterGeolocationService }, { "AndroidBrowserProcess", content::RegisterAndroidBrowserProcess }, { "ContentSettings", content::ContentSettings::RegisterContentSettings }, { "ContentVideoView", content::ContentVideoView::RegisterContentVideoView }, { "ContentViewClient", content::RegisterContentViewClient }, { "ContentViewCore", content::RegisterContentViewCore }, { "DeviceInfo", content::RegisterDeviceInfo }, { "DownloadController", content::DownloadController::RegisterDownloadController }, { "SandboxedProcessLauncher", content::RegisterSandboxedProcessLauncher }, { "TouchPoint", content::RegisterTouchPoint }, { "WebViewStatics", content::RegisterWebViewStatics }, }; } // namespace namespace content { namespace android { bool RegisterBrowserJni(JNIEnv* env) { return RegisterNativeMethods(env, kContentRegisteredMethods, arraysize(kContentRegisteredMethods)); } } // namespace android } // namespace content
bsd-3-clause
lukehutch/gribbit-rox
attic/src/com/flat502/rox/marshal/xmlrpc/XmlRpcSaxParserFactory.java
1357
package com.flat502.rox.marshal.xmlrpc; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; /** * SAXParserFactory for instantiating XmlRpcSaxParser's */ public class XmlRpcSaxParserFactory extends SAXParserFactory { @Override public SAXParser newSAXParser() throws ParserConfigurationException, SAXException { if (isValidating()) { throw new ParserConfigurationException("No support for validation."); } if (isNamespaceAware()) { throw new ParserConfigurationException("No support for namespaces."); } // now that we've got all that off our chest return new XmlRpcSaxParser(); } @Override public void setFeature(String name, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { throw new SAXNotRecognizedException("No feature support (and specifically no support for \"" + name + "\")"); } @Override public boolean getFeature(String name) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { throw new SAXNotRecognizedException("No feature support (and specifically no support for \"" + name + "\")"); } }
bsd-3-clause
timsnyder/bokeh
bokehjs/examples/burtin/burtin.ts
5910
import * as Bokeh from "bokehjs" export namespace Burtin { import plt = Bokeh.Plotting const {range, values} = Bokeh.LinAlg console.log(`Bokeh ${Bokeh.version}`) Bokeh.set_log_level("info") Bokeh.settings.dev = true type Gram = "negative" | "positive" const antibiotics: [string, number, number, number, Gram][] = [ ["Mycobacterium tuberculosis", 800, 5, 2, "negative"], ["Salmonella schottmuelleri", 10, 0.8, 0.09, "negative"], ["Proteus vulgaris", 3, 0.1, 0.1, "negative"], ["Klebsiella pneumoniae", 850, 1.2, 1, "negative"], ["Brucella abortus", 1, 2, 0.02, "negative"], ["Pseudomonas aeruginosa", 850, 2, 0.4, "negative"], ["Escherichia coli", 100, 0.4, 0.1, "negative"], ["Salmonella (Eberthella) typhosa", 1, 0.4, 0.008, "negative"], ["Aerobacter aerogenes", 870, 1, 1.6, "negative"], ["Brucella antracis", 0.001, 0.01, 0.007, "positive"], ["Streptococcus fecalis", 1, 1, 0.1, "positive"], ["Staphylococcus aureus", 0.03, 0.03, 0.001, "positive"], ["Staphylococcus albus", 0.007, 0.1, 0.001, "positive"], ["Streptococcus hemolyticus", 0.001, 14, 10, "positive"], ["Streptococcus viridans", 0.005, 10, 40, "positive"], ["Diplococcus pneumoniae", 0.005, 11, 10, "positive"], ] interface Antibiotics { index: number[] length: number bacteria: string[] penicillin: number[] streptomycin: number[] neomycin: number[] gram: Gram[] } const df: Antibiotics = { index: antibiotics.map((_, i) => i), length: antibiotics.length, bacteria: antibiotics.map((row) => row[0]), penicillin: antibiotics.map((row) => row[1]), streptomycin: antibiotics.map((row) => row[2]), neomycin: antibiotics.map((row) => row[3]), gram: antibiotics.map((row) => row[4]), } const drug_color = { Penicillin: "#0d3362", Streptomycin: "#c64737", Neomycin: "black" , } const gram_color = { positive: "#aeaeb8", negative: "#e69584", } const width = 800 const height = 800 const inner_radius = 90 const outer_radius = 300 - 10 const minr = Math.sqrt(Math.log(.001 * 1E4)) const maxr = Math.sqrt(Math.log(1000 * 1E4)) const a = (outer_radius - inner_radius) / (minr - maxr) const b = inner_radius - a * maxr function rad(mic: number[]): number[] { return mic.map((v) => a * Math.sqrt(Math.log(v * 1E4)) + b) } const big_angle = 2.0 * Math.PI / (df.length + 1) const small_angle = big_angle / 7 const p = plt.figure({ title: null, plot_width: width, plot_height: height, x_axis_type: null, y_axis_type: null, x_range: [-420, 420], y_range: [-420, 420], min_border: 0, outline_line_color: "black", background_fill_color: "#f0e1d2", }) // annular wedges const angles = df.index.map((i) => Math.PI/2 - big_angle/2 - i*big_angle) const colors = df.gram.map((gram) => gram_color[gram]) p.annular_wedge(0, 0, inner_radius, outer_radius, angles.map((angle) => -big_angle + angle), angles, {color: colors}) // small wedges p.annular_wedge(0, 0, inner_radius, rad(df.penicillin), angles.map((angle) => -big_angle+angle+5*small_angle), angles.map((angle) => -big_angle+angle+6*small_angle), {color: drug_color.Penicillin}) p.annular_wedge(0, 0, inner_radius, rad(df.streptomycin), angles.map((angle) => -big_angle+angle+3*small_angle), angles.map((angle) => -big_angle+angle+4*small_angle), {color: drug_color.Streptomycin}) p.annular_wedge(0, 0, inner_radius, rad(df.neomycin), angles.map((angle) => -big_angle+angle+1*small_angle), angles.map((angle) => -big_angle+angle+2*small_angle), {color: drug_color.Neomycin}) // circular axes and lables const labels = range(-3, 4).map((v) => 10**v) const radii = labels.map((label) => a * Math.sqrt(Math.log(label * 1E4)) + b) p.circle(0, 0, {radius: radii, fill_color: null, line_color: "white"}) p.text(0, radii.slice(0, -1), labels.slice(0, -1).map((label) => label.toString()), {text_font_size: "8pt", text_align: "center", text_baseline: "middle"}) // radial axes p.annular_wedge(0, 0, inner_radius-10, outer_radius+10, angles.map((angle) => -big_angle+angle), angles.map((angle) => -big_angle+angle), {color: "black"}) // bacteria labels const xr = angles.map((angle) => radii[0]*Math.cos(-big_angle/2 + angle)) const yr = angles.map((angle) => radii[0]*Math.sin(-big_angle/2 + angle)) const label_angle = angles.map((angle) => -big_angle/2 + angle) .map((angle) => (angle < -Math.PI/2) ? angle + Math.PI : angle) p.text(xr, yr, df.bacteria, {angle: label_angle, text_font_size: "9pt", text_align: "center", text_baseline: "middle"}) // OK, these hand drawn legends are pretty clunky, will be improved in future release p.circle([-40, -40], [-370, -390], {color: values(gram_color), radius: 5}) p.text([-30, -30], [-370, -390], Object.keys(gram_color).map((gram) => `Gram-${gram}`), {text_font_size: "7pt", text_align: "left", text_baseline: "middle"}) p.rect([-40, -40, -40], [18, 0, -18], 30, 13, {color: values(drug_color)}) p.text([-15, -15, -15], [18, 0, -18], Object.keys(drug_color), {text_font_size: "9pt", text_align: "left", text_baseline: "middle"}) plt.show(p) }
bsd-3-clause
Clashsoft/Dyvil
library/src/main/java/dyvilx/tools/asm/MethodWriter.java
75239
/*** * ASM: a very small and fast Java bytecode manipulation framework Copyright (c) 2000-2011 INRIA, France Telecom All * rights reserved. * <p> * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the * distribution. 3. Neither the name of the copyright holders nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * <p> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dyvilx.tools.asm; class MethodWriter implements MethodVisitor { static final int ACC_CONSTRUCTOR = 0x80000; static final int SAME_FRAME = 0; static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; static final int RESERVED = 128; static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; static final int CHOP_FRAME = 248; static final int SAME_FRAME_EXTENDED = 251; static final int APPEND_FRAME = 252; static final int FULL_FRAME = 255; private static final int FRAMES = 0; private static final int MAXS = 1; private static final int NOTHING = 2; final ClassWriter cw; private int access; private final int name; private final int desc; private final String descriptor; String signature; int classReaderOffset; int classReaderLength; int exceptionCount; int[] exceptions; private ByteVector annd; private AnnotationWriter anns; private AnnotationWriter ianns; private AnnotationWriter tanns; private AnnotationWriter itanns; private AnnotationWriter[] panns; private AnnotationWriter[] ipanns; private int synthetics; private Attribute attrs; private ByteVector code = new ByteVector(); private int maxStack; private int maxLocals; private int currentLocals; private int frameCount; private ByteVector stackMap; private int previousFrameOffset; private int[] previousFrame; private int[] frame; private int handlerCount; private Handler firstHandler; private Handler lastHandler; private int methodParametersCount; private ByteVector methodParameters; private int localVarCount; private ByteVector localVar; private int localVarTypeCount; private ByteVector localVarType; private int lineNumberCount; private ByteVector lineNumber; private int lastCodeOffset; private AnnotationWriter ctanns; private AnnotationWriter ictanns; private Attribute cattrs; private boolean resize; private int subroutines; private final int compute; private Label labels; private Label previousBlock; private Label currentBlock; private int stackSize; private int maxStackSize; MethodWriter next; MethodWriter(final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean computeMaxs, final boolean computeFrames) { if (cw.firstMethod == null) { cw.firstMethod = this; } else { cw.lastMethod.next = this; } cw.lastMethod = this; this.cw = cw; this.access = access; if ("<init>".equals(name)) { this.access |= ACC_CONSTRUCTOR; } this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); this.descriptor = desc; this.signature = signature; if (exceptions != null && exceptions.length > 0) { this.exceptionCount = exceptions.length; this.exceptions = new int[this.exceptionCount]; for (int i = 0; i < this.exceptionCount; ++i) { this.exceptions[i] = cw.newClass(exceptions[i]); } } this.compute = computeFrames ? FRAMES : computeMaxs ? MAXS : NOTHING; if (computeMaxs || computeFrames) { // updates maxLocals int size = Type.getArgumentsAndReturnSizes(this.descriptor) >> 2; if ((access & ASMConstants.ACC_STATIC) != 0) { --size; } this.maxLocals = size; this.currentLocals = size; // creates and visits the label for the first basic block this.labels = new Label(); this.labels.status |= Label.PUSHED; this.visitLabel(this.labels); } } @Override public void visitParameter(String name, int access) { if (this.methodParameters == null) { this.methodParameters = new ByteVector(); } ++this.methodParametersCount; this.methodParameters.putShort(name == null ? 0 : this.cw.newUTF8(name)).putShort(access); } @Override public AnnotationVisitor visitAnnotationDefault() { this.annd = new ByteVector(); return new AnnotationWriter(this.cw, false, this.annd, null, 0); } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, 2); if (visible) { aw.next = this.anns; this.anns = aw; } else { aw.next = this.ianns; this.ianns = aw; } return aw; } @Override public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { ByteVector bv = new ByteVector(); // write target_type and target_info AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = this.tanns; this.tanns = aw; } else { aw.next = this.itanns; this.itanns = aw; } return aw; } @Override public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { ByteVector bv = new ByteVector(); if ("Ljava/lang/Synthetic;".equals(desc)) { // workaround for a bug in javac with synthetic parameters // see ClassReader.readParameterAnnotations this.synthetics = Math.max(this.synthetics, parameter + 1); return new AnnotationWriter(this.cw, false, bv, null, 0); } // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, 2); if (visible) { if (this.panns == null) { this.panns = new AnnotationWriter[Type.getArgumentTypes(this.descriptor).length]; } aw.next = this.panns[parameter]; this.panns[parameter] = aw; } else { if (this.ipanns == null) { this.ipanns = new AnnotationWriter[Type.getArgumentTypes(this.descriptor).length]; } aw.next = this.ipanns[parameter]; this.ipanns[parameter] = aw; } return aw; } @Override public void visitAttribute(final Attribute attr) { if (attr.isCodeAttribute()) { attr.next = this.cattrs; this.cattrs = attr; } else { attr.next = this.attrs; this.attrs = attr; } } @Override public boolean visitCode() { return true; } @Override public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { if (this.compute == FRAMES) { return; } if (type == ASMConstants.F_NEW) { if (this.previousFrame == null) { this.visitImplicitFirstFrame(); } this.currentLocals = nLocal; int frameIndex = this.startFrame(this.code.length, nLocal, nStack); for (int i = 0; i < nLocal; ++i) { if (local[i] instanceof String) { this.frame[frameIndex++] = Frame.OBJECT | this.cw.addType((String) local[i]); } else if (local[i] instanceof Integer) { this.frame[frameIndex++] = (Integer) local[i]; } else { this.frame[frameIndex++] = Frame.UNINITIALIZED | this.cw.addUninitializedType("", ((Label) local[i]).position); } } for (int i = 0; i < nStack; ++i) { if (stack[i] instanceof String) { this.frame[frameIndex++] = Frame.OBJECT | this.cw.addType((String) stack[i]); } else if (stack[i] instanceof Integer) { this.frame[frameIndex++] = (Integer) stack[i]; } else { this.frame[frameIndex++] = Frame.UNINITIALIZED | this.cw.addUninitializedType("", ((Label) stack[i]).position); } } this.endFrame(); } else { int delta; if (this.stackMap == null) { this.stackMap = new ByteVector(); delta = this.code.length; } else { delta = this.code.length - this.previousFrameOffset - 1; if (delta < 0) { if (type == ASMConstants.F_SAME) { return; } throw new IllegalStateException(); } } switch (type) { case ASMConstants.F_FULL: this.currentLocals = nLocal; this.stackMap.putByte(FULL_FRAME).putShort(delta).putShort(nLocal); for (int i = 0; i < nLocal; ++i) { this.writeFrameType(local[i]); } this.stackMap.putShort(nStack); for (int i = 0; i < nStack; ++i) { this.writeFrameType(stack[i]); } break; case ASMConstants.F_APPEND: this.currentLocals += nLocal; this.stackMap.putByte(SAME_FRAME_EXTENDED + nLocal).putShort(delta); for (int i = 0; i < nLocal; ++i) { this.writeFrameType(local[i]); } break; case ASMConstants.F_CHOP: this.currentLocals -= nLocal; this.stackMap.putByte(SAME_FRAME_EXTENDED - nLocal).putShort(delta); break; case ASMConstants.F_SAME: if (delta < 64) { this.stackMap.putByte(delta); } else { this.stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); } break; case ASMConstants.F_SAME1: if (delta < 64) { this.stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); } else { this.stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(delta); } this.writeFrameType(stack[0]); break; } this.previousFrameOffset = this.code.length; ++this.frameCount; } this.maxStack = Math.max(this.maxStack, nStack); this.maxLocals = Math.max(this.maxLocals, this.currentLocals); } @Override public void visitInsn(final int opcode) { this.lastCodeOffset = this.code.length; // adds the instruction to the bytecode of the method this.code.putByte(opcode); // update currentBlock // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, 0, null, null); } else { // updates current and max stack sizes int size = this.stackSize + Frame.SIZE[opcode]; if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } // if opcode == ATHROW or xRETURN, ends current block (no successor) if (opcode >= ASMConstants.IRETURN && opcode <= ASMConstants.RETURN || opcode == ASMConstants.ATHROW) { this.noSuccessor(); } } } @Override public void visitIntInsn(final int opcode, final int operand) { this.lastCodeOffset = this.code.length; // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, operand, null, null); } else if (opcode != ASMConstants.NEWARRAY) { // updates current and max stack sizes only for NEWARRAY // (stack size variation = 0 for BIPUSH or SIPUSH) int size = this.stackSize + 1; if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method if (opcode == ASMConstants.SIPUSH) { this.code.put12(opcode, operand); } else { // BIPUSH or NEWARRAY this.code.put11(opcode, operand); } } @Override public void visitVarInsn(final int opcode, final int var) { this.lastCodeOffset = this.code.length; // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, var, null, null); } else { // updates current and max stack sizes if (opcode == ASMConstants.RET) { // no stack change, but end of current block (no successor) this.currentBlock.status |= Label.RET; // save 'stackSize' here for future use // (see {@link #findSubroutineSuccessors}) this.currentBlock.inputStackTop = this.stackSize; this.noSuccessor(); } else { // xLOAD or xSTORE int size = this.stackSize + Frame.SIZE[opcode]; if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } } if (this.compute != NOTHING) { // updates max locals int n; if (opcode == ASMConstants.LLOAD || opcode == ASMConstants.DLOAD || opcode == ASMConstants.LSTORE || opcode == ASMConstants.DSTORE) { n = var + 2; } else { n = var + 1; } if (n > this.maxLocals) { this.maxLocals = n; } } // adds the instruction to the bytecode of the method if (var < 4 && opcode != ASMConstants.RET) { int opt; if (opcode < ASMConstants.ISTORE) { /* ILOAD_0 */ opt = 26 + (opcode - ASMConstants.ILOAD << 2) + var; } else { /* ISTORE_0 */ opt = 59 + (opcode - ASMConstants.ISTORE << 2) + var; } this.code.putByte(opt); } else if (var >= 256) { this.code.putByte(196 /* WIDE */).put12(opcode, var); } else { this.code.put11(opcode, var); } if (opcode >= ASMConstants.ISTORE && this.compute == FRAMES && this.handlerCount > 0) { this.visitLabel(new Label()); } } @Override public void visitTypeInsn(final int opcode, final String type) { this.lastCodeOffset = this.code.length; Item i = this.cw.newClassItem(type); // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, this.code.length, this.cw, i); } else if (opcode == ASMConstants.NEW) { // updates current and max stack sizes only if opcode == NEW // (no stack change for ANEWARRAY, CHECKCAST, INSTANCEOF) int size = this.stackSize + 1; if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method this.code.put12(opcode, i.index); } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { this.lastCodeOffset = this.code.length; Item i = this.cw.newFieldItem(owner, name, desc); // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, 0, this.cw, i); } else { int size; // computes the stack size variation char c = desc.charAt(0); switch (opcode) { case ASMConstants.GETSTATIC: size = this.stackSize + (c == 'D' || c == 'J' ? 2 : 1); break; case ASMConstants.PUTSTATIC: size = this.stackSize + (c == 'D' || c == 'J' ? -2 : -1); break; case ASMConstants.GETFIELD: size = this.stackSize + (c == 'D' || c == 'J' ? 1 : 0); break; // case Constants.PUTFIELD: default: size = this.stackSize + (c == 'D' || c == 'J' ? -3 : -2); break; } // updates current and max stack sizes if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method this.code.put12(opcode, i.index); } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) { this.lastCodeOffset = this.code.length; Item i = this.cw.newMethodItem(owner, name, desc, itf); int argSize = i.intVal; // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, 0, this.cw, i); } else { /* * computes the stack size variation. In order not to recompute * several times this variation for the same Item, we use the * intVal field of this item to store this variation, once it * has been computed. More precisely this intVal field stores * the sizes of the arguments and of the return value * corresponding to desc. */ if (argSize == 0) { // the above sizes have not been computed yet, // so we compute them... argSize = Type.getArgumentsAndReturnSizes(desc); // ... and we save them in order // not to recompute them in the future i.intVal = argSize; } int size; if (opcode == ASMConstants.INVOKESTATIC) { size = this.stackSize - (argSize >> 2) + (argSize & 0x03) + 1; } else { size = this.stackSize - (argSize >> 2) + (argSize & 0x03); } // updates current and max stack sizes if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method if (opcode == ASMConstants.INVOKEINTERFACE) { if (argSize == 0) { argSize = Type.getArgumentsAndReturnSizes(desc); i.intVal = argSize; } this.code.put12(ASMConstants.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0); } else { this.code.put12(opcode, i.index); } } @Override public void visitInvokeDynamicInsn(final String name, final String desc, final Handle bsm, final Object... bsmArgs) { this.lastCodeOffset = this.code.length; Item i = this.cw.newInvokeDynamicItem(name, desc, bsm, bsmArgs); int argSize = i.intVal; // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(ASMConstants.INVOKEDYNAMIC, 0, this.cw, i); } else { /* * computes the stack size variation. In order not to recompute * several times this variation for the same Item, we use the * intVal field of this item to store this variation, once it * has been computed. More precisely this intVal field stores * the sizes of the arguments and of the return value * corresponding to desc. */ if (argSize == 0) { // the above sizes have not been computed yet, // so we compute them... argSize = Type.getArgumentsAndReturnSizes(desc); // ... and we save them in order // not to recompute them in the future i.intVal = argSize; } int size = this.stackSize - (argSize >> 2) + (argSize & 0x03) + 1; // updates current and max stack sizes if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method this.code.put12(ASMConstants.INVOKEDYNAMIC, i.index); this.code.putShort(0); } @Override public void visitJumpInsn(final int opcode, final Label label) { this.lastCodeOffset = this.code.length; Label nextInsn = null; // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(opcode, 0, null, null); // 'label' is the target of a jump instruction label.getFirst().status |= Label.TARGET; // adds 'label' as a successor of this basic block this.addSuccessor(Edge.NORMAL, label); if (opcode != ASMConstants.GOTO) { // creates a Label for the next basic block nextInsn = new Label(); } } else { if (opcode == ASMConstants.JSR) { if ((label.status & Label.SUBROUTINE) == 0) { label.status |= Label.SUBROUTINE; ++this.subroutines; } this.currentBlock.status |= Label.JSR; this.addSuccessor(this.stackSize + 1, label); // creates a Label for the next basic block nextInsn = new Label(); /* * note that, by construction in this method, a JSR block * has at least two successors in the control flow graph: * the first one leads the next instruction after the JSR, * while the second one leads to the JSR target. */ } else { // updates current stack size (max stack size unchanged // because stack size variation always negative in this // case) this.stackSize += Frame.SIZE[opcode]; this.addSuccessor(this.stackSize, label); } } } // adds the instruction to the bytecode of the method if ((label.status & Label.RESOLVED) != 0 && label.position - this.code.length < Short.MIN_VALUE) { /* * case of a backward jump with an offset < -32768. In this case we * automatically replace GOTO with GOTO_W, JSR with JSR_W and IFxxx * <l> with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the * "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) and where <l'> * designates the instruction just after the GOTO_W. */ if (opcode == ASMConstants.GOTO) { this.code.putByte(200); // GOTO_W } else if (opcode == ASMConstants.JSR) { this.code.putByte(201); // JSR_W } else { // if the IF instruction is transformed into IFNOT GOTO_W the // next instruction becomes the target of the IFNOT instruction if (nextInsn != null) { nextInsn.status |= Label.TARGET; } this.code.putByte(opcode <= 166 ? (opcode + 1 ^ 1) - 1 : opcode ^ 1); this.code.putShort(8); // jump offset this.code.putByte(200); // GOTO_W } label.put(this, this.code, this.code.length - 1, true); } else { /* * case of a backward jump with an offset >= -32768, or of a forward * jump with, of course, an unknown offset. In these cases we store * the offset in 2 bytes (which will be increased in * resizeInstructions, if needed). */ this.code.putByte(opcode); label.put(this, this.code, this.code.length - 1, false); } if (this.currentBlock != null) { if (nextInsn != null) { // if the jump instruction is not a GOTO, the next instruction // is also a successor of this instruction. Calling visitLabel // adds the label of this next instruction as a successor of the // current block, and starts a new basic block this.visitLabel(nextInsn); } if (opcode == ASMConstants.GOTO) { this.noSuccessor(); } } } @Override public void visitLabel(final Label label) { // resolves previous forward references to label, if any this.resize |= label.resolve(this, this.code.length, this.code.data); // updates currentBlock if ((label.status & Label.DEBUG) != 0) { return; } if (this.compute == FRAMES) { if (this.currentBlock != null) { if (label.position == this.currentBlock.position) { // successive labels, do not start a new basic block this.currentBlock.status |= label.status & Label.TARGET; label.frame = this.currentBlock.frame; return; } // ends current block (with one new successor) this.addSuccessor(Edge.NORMAL, label); } // begins a new current block this.currentBlock = label; if (label.frame == null) { label.frame = new Frame(); label.frame.owner = label; } // updates the basic block list if (this.previousBlock != null) { if (label.position == this.previousBlock.position) { this.previousBlock.status |= label.status & Label.TARGET; label.frame = this.previousBlock.frame; this.currentBlock = this.previousBlock; return; } this.previousBlock.successor = label; } this.previousBlock = label; } else if (this.compute == MAXS) { if (this.currentBlock != null) { // ends current block (with one new successor) this.currentBlock.outputStackMax = this.maxStackSize; this.addSuccessor(this.stackSize, label); } // begins a new current block this.currentBlock = label; // resets the relative current and max stack sizes this.stackSize = 0; this.maxStackSize = 0; // updates the basic block list if (this.previousBlock != null) { this.previousBlock.successor = label; } this.previousBlock = label; } } @Override public void visitLdcInsn(final Object cst) { this.lastCodeOffset = this.code.length; Item i = this.cw.newConstItem(cst); // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(ASMConstants.LDC, 0, this.cw, i); } else { int size; // computes the stack size variation if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { size = this.stackSize + 2; } else { size = this.stackSize + 1; } // updates current and max stack sizes if (size > this.maxStackSize) { this.maxStackSize = size; } this.stackSize = size; } } // adds the instruction to the bytecode of the method int index = i.index; if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { this.code.put12(20 /* LDC2_W */, index); } else if (index >= 256) { this.code.put12(19 /* LDC_W */, index); } else { this.code.put11(ASMConstants.LDC, index); } } @Override public void visitIincInsn(final int var, final int increment) { this.lastCodeOffset = this.code.length; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(ASMConstants.IINC, var, null, null); } } if (this.compute != NOTHING) { // updates max locals int n = var + 1; if (n > this.maxLocals) { this.maxLocals = n; } } // adds the instruction to the bytecode of the method if (var > 255 || increment > 127 || increment < -128) { this.code.putByte(196 /* WIDE */).put12(ASMConstants.IINC, var).putShort(increment); } else { this.code.putByte(ASMConstants.IINC).put11(var, increment); } } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { this.lastCodeOffset = this.code.length; // adds the instruction to the bytecode of the method int source = this.code.length; this.code.putByte(ASMConstants.TABLESWITCH); this.code.putByteArray(null, 0, (4 - this.code.length % 4) % 4); dflt.put(this, this.code, source, true); this.code.putInt(min).putInt(max); for (Label label : labels) { label.put(this, this.code, source, true); } // updates currentBlock this.visitSwitchInsn(dflt, labels); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { this.lastCodeOffset = this.code.length; // adds the instruction to the bytecode of the method int source = this.code.length; this.code.putByte(ASMConstants.LOOKUPSWITCH); this.code.putByteArray(null, 0, (4 - this.code.length % 4) % 4); dflt.put(this, this.code, source, true); this.code.putInt(labels.length); for (int i = 0; i < labels.length; ++i) { this.code.putInt(keys[i]); labels[i].put(this, this.code, source, true); } // updates currentBlock this.visitSwitchInsn(dflt, labels); } private void visitSwitchInsn(final Label dflt, final Label[] labels) { // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(ASMConstants.LOOKUPSWITCH, 0, null, null); // adds current block successors this.addSuccessor(Edge.NORMAL, dflt); dflt.getFirst().status |= Label.TARGET; for (Label label : labels) { this.addSuccessor(Edge.NORMAL, label); label.getFirst().status |= Label.TARGET; } } else { // updates current stack size (max stack size unchanged) --this.stackSize; // adds current block successors this.addSuccessor(this.stackSize, dflt); for (Label label : labels) { this.addSuccessor(this.stackSize, label); } } // ends current block this.noSuccessor(); } } @Override public void visitMultiANewArrayInsn(final String desc, final int dims) { this.lastCodeOffset = this.code.length; Item i = this.cw.newClassItem(desc); // Label currentBlock = this.currentBlock; if (this.currentBlock != null) { if (this.compute == FRAMES) { this.currentBlock.frame.execute(ASMConstants.MULTIANEWARRAY, dims, this.cw, i); } else { // updates current stack size (max stack size unchanged because // stack size variation always negative or null) this.stackSize += 1 - dims; } } // adds the instruction to the bytecode of the method this.code.put12(ASMConstants.MULTIANEWARRAY, i.index).putByte(dims); } @Override public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { ByteVector bv = new ByteVector(); // write target_type and target_info typeRef = typeRef & 0xFF0000FF | this.lastCodeOffset << 8; AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = this.ctanns; this.ctanns = aw; } else { aw.next = this.ictanns; this.ictanns = aw; } return aw; } @Override public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) { ++this.handlerCount; Handler h = new Handler(); h.start = start; h.end = end; h.handler = handler; h.desc = type; h.type = type != null ? this.cw.newClass(type) : 0; if (this.lastHandler == null) { this.firstHandler = h; } else { this.lastHandler.next = h; } this.lastHandler = h; } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { ByteVector bv = new ByteVector(); // write target_type and target_info AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = this.ctanns; this.ctanns = aw; } else { aw.next = this.ictanns; this.ictanns = aw; } return aw; } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { if (signature != null) { if (this.localVarType == null) { this.localVarType = new ByteVector(); } ++this.localVarTypeCount; this.localVarType.putShort(start.position).putShort(end.position - start.position) .putShort(this.cw.newUTF8(name)).putShort(this.cw.newUTF8(signature)).putShort(index); } if (this.localVar == null) { this.localVar = new ByteVector(); } ++this.localVarCount; this.localVar.putShort(start.position).putShort(end.position - start.position).putShort(this.cw.newUTF8(name)) .putShort(this.cw.newUTF8(desc)).putShort(index); if (this.compute != NOTHING) { // updates max locals char c = desc.charAt(0); int n = index + (c == 'J' || c == 'D' ? 2 : 1); if (n > this.maxLocals) { this.maxLocals = n; } } } @Override public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { ByteVector bv = new ByteVector(); // write target_type and target_info bv.putByte(typeRef >>> 24).putShort(start.length); for (int i = 0; i < start.length; ++i) { bv.putShort(start[i].position).putShort(end[i].position - start[i].position).putShort(index[i]); } if (typePath == null) { bv.putByte(0); } else { int length = typePath.b[typePath.offset] * 2 + 1; bv.putByteArray(typePath.b, typePath.offset, length); } // write type, and reserve space for values count bv.putShort(this.cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = this.ctanns; this.ctanns = aw; } else { aw.next = this.ictanns; this.ictanns = aw; } return aw; } @Override public void visitLineNumber(final int line, final Label start) { if (this.lineNumber == null) { this.lineNumber = new ByteVector(); } ++this.lineNumberCount; this.lineNumber.putShort(start.position); this.lineNumber.putShort(line); } @Override public void visitMaxs(final int maxStack, final int maxLocals) { if (this.resize) { // replaces the temporary jump opcodes introduced by Label.resolve. this.resizeInstructions(); } if (this.compute == FRAMES) { // completes the control flow graph with exception handler blocks Handler handler = this.firstHandler; while (handler != null) { Label l = handler.start.getFirst(); Label h = handler.handler.getFirst(); Label e = handler.end.getFirst(); // computes the kind of the edges to 'h' String t = handler.desc == null ? "java/lang/Throwable" : handler.desc; int kind = Frame.OBJECT | this.cw.addType(t); // h is an exception handler h.status |= Label.TARGET; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = kind; b.successor = h; // adds it to the successors of 'l' b.next = l.successors; l.successors = b; // goes to the next label l = l.successor; } handler = handler.next; } // creates and visits the first (implicit) frame Frame f = this.labels.frame; Type[] args = Type.getArgumentTypes(this.descriptor); f.initInputFrame(this.cw, this.access, args, this.maxLocals); this.visitFrame(f); /* * fix point algorithm: mark the first basic block as 'changed' * (i.e. put it in the 'changed' list) and, while there are changed * basic blocks, choose one, mark it as unchanged, and update its * successors (which can be changed in the process). */ int max = 0; Label changed = this.labels; while (changed != null) { // removes a basic block from the list of changed basic blocks Label l = changed; changed = changed.next; l.next = null; f = l.frame; // a reachable jump target must be stored in the stack map if ((l.status & Label.TARGET) != 0) { l.status |= Label.STORE; } // all visited labels are reachable, by definition l.status |= Label.REACHABLE; // updates the (absolute) maximum stack size int blockMax = f.inputStack.length + l.outputStackMax; if (blockMax > max) { max = blockMax; } // updates the successors of the current basic block Edge e = l.successors; while (e != null) { Label n = e.successor.getFirst(); boolean change = f.merge(this.cw, n.frame, e.info); if (change && n.next == null) { // if n has changed and is not already in the 'changed' // list, adds it to this list n.next = changed; changed = n; } e = e.next; } } // visits all the frames that must be stored in the stack map Label l = this.labels; while (l != null) { f = l.frame; if ((l.status & Label.STORE) != 0) { this.visitFrame(f); } if ((l.status & Label.REACHABLE) == 0) { // finds start and end of dead basic block Label k = l.successor; int start = l.position; int end = (k == null ? this.code.length : k.position) - 1; // if non empty basic block if (end >= start) { max = Math.max(max, 1); // replaces instructions with NOP ... NOP ATHROW for (int i = start; i < end; ++i) { this.code.data[i] = ASMConstants.NOP; } this.code.data[end] = (byte) ASMConstants.ATHROW; // emits a frame for this unreachable block int frameIndex = this.startFrame(start, 0, 1); this.frame[frameIndex] = Frame.OBJECT | this.cw.addType("java/lang/Throwable"); this.endFrame(); // removes the start-end range from the exception // handlers this.firstHandler = Handler.remove(this.firstHandler, l, k); } } l = l.successor; } handler = this.firstHandler; this.handlerCount = 0; while (handler != null) { this.handlerCount += 1; handler = handler.next; } this.maxStack = max; } else if (this.compute == MAXS) { // completes the control flow graph with exception handler blocks Handler handler = this.firstHandler; while (handler != null) { Label l = handler.start; Label h = handler.handler; Label e = handler.end; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = Edge.EXCEPTION; b.successor = h; // adds it to the successors of 'l' if ((l.status & Label.JSR) == 0) { b.next = l.successors; l.successors = b; } else { // if l is a JSR block, adds b after the first two edges // to preserve the hypothesis about JSR block successors // order (see {@link #visitJumpInsn}) b.next = l.successors.next.next; l.successors.next.next = b; } // goes to the next label l = l.successor; } handler = handler.next; } if (this.subroutines > 0) { // completes the control flow graph with the RET successors /* * first step: finds the subroutines. This step determines, for * each basic block, to which subroutine(s) it belongs. */ // finds the basic blocks that belong to the "main" subroutine int id = 0; this.labels.visitSubroutine(null, 1, this.subroutines); // finds the basic blocks that belong to the real subroutines Label l = this.labels; while (l != null) { if ((l.status & Label.JSR) != 0) { // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; // if this subroutine has not been visited yet... if ((subroutine.status & Label.VISITED) == 0) { // ...assigns it a new id and finds its basic blocks id += 1; subroutine.visitSubroutine(null, id / 32L << 32 | 1L << id % 32, this.subroutines); } } l = l.successor; } // second step: finds the successors of RET blocks l = this.labels; while (l != null) { if ((l.status & Label.JSR) != 0) { Label L = this.labels; while (L != null) { L.status &= ~Label.VISITED2; L = L.successor; } // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; subroutine.visitSubroutine(l, 0, this.subroutines); } l = l.successor; } } /* * control flow analysis algorithm: while the block stack is not * empty, pop a block from this stack, update the max stack size, * compute the true (non relative) begin stack size of the * successors of this block, and push these successors onto the * stack (unless they have already been pushed onto the stack). * Note: by hypothesis, the {@link Label#inputStackTop} of the * blocks in the block stack are the true (non relative) beginning * stack sizes of these blocks. */ int max = 0; Label stack = this.labels; while (stack != null) { // pops a block from the stack Label l = stack; stack = stack.next; // computes the true (non relative) max stack size of this block int start = l.inputStackTop; int blockMax = start + l.outputStackMax; // updates the global max stack size if (blockMax > max) { max = blockMax; } // analyzes the successors of the block Edge b = l.successors; if ((l.status & Label.JSR) != 0) { // ignores the first edge of JSR blocks (virtual successor) b = b.next; } while (b != null) { l = b.successor; // if this successor has not already been pushed... if ((l.status & Label.PUSHED) == 0) { // computes its true beginning stack size... l.inputStackTop = b.info == Edge.EXCEPTION ? 1 : start + b.info; // ...and pushes it onto the stack l.status |= Label.PUSHED; l.next = stack; stack = l; } b = b.next; } } this.maxStack = Math.max(maxStack, max); } else { this.maxStack = maxStack; this.maxLocals = maxLocals; } } @Override public void visitEnd() { } private void addSuccessor(final int info, final Label successor) { // creates and initializes an Edge object... Edge b = new Edge(); b.info = info; b.successor = successor; // ...and adds it to the successor list of the currentBlock block b.next = this.currentBlock.successors; this.currentBlock.successors = b; } private void noSuccessor() { if (this.compute == FRAMES) { Label l = new Label(); l.frame = new Frame(); l.frame.owner = l; l.resolve(this, this.code.length, this.code.data); this.previousBlock.successor = l; this.previousBlock = l; } else { this.currentBlock.outputStackMax = this.maxStackSize; } this.currentBlock = null; } private void visitFrame(final Frame f) { int i, t; int nTop = 0; int nLocal = 0; int nStack = 0; int[] locals = f.inputLocals; int[] stacks = f.inputStack; // computes the number of locals (ignores TOP types that are just after // a LONG or a DOUBLE, and all trailing TOP types) for (i = 0; i < locals.length; ++i) { t = locals[i]; if (t == Frame.TOP) { ++nTop; } else { nLocal += nTop + 1; nTop = 0; } if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // computes the stack size (ignores TOP types that are just after // a LONG or a DOUBLE) for (i = 0; i < stacks.length; ++i) { t = stacks[i]; ++nStack; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // visits the frame and its content int frameIndex = this.startFrame(f.owner.position, nLocal, nStack); for (i = 0; nLocal > 0; ++i, --nLocal) { t = locals[i]; this.frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } for (i = 0; i < stacks.length; ++i) { t = stacks[i]; this.frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } this.endFrame(); } private void visitImplicitFirstFrame() { // There can be at most descriptor.length() + 1 locals int frameIndex = this.startFrame(0, this.descriptor.length() + 1, 0); if ((this.access & ASMConstants.ACC_STATIC) == 0) { if ((this.access & ACC_CONSTRUCTOR) == 0) { this.frame[frameIndex++] = Frame.OBJECT | this.cw.addType(this.cw.thisName); } else { this.frame[frameIndex++] = 6; // Opcodes.UNINITIALIZED_THIS; } } int i = 1; loop: while (true) { int j = i; switch (this.descriptor.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': this.frame[frameIndex++] = 1; // Opcodes.INTEGER; break; case 'F': this.frame[frameIndex++] = 2; // Opcodes.FLOAT; break; case 'J': this.frame[frameIndex++] = 4; // Opcodes.LONG; break; case 'D': this.frame[frameIndex++] = 3; // Opcodes.DOUBLE; break; case '[': while (this.descriptor.charAt(i) == '[') { ++i; } if (this.descriptor.charAt(i) == 'L') { ++i; while (this.descriptor.charAt(i) != ';') { ++i; } } this.frame[frameIndex++] = Frame.OBJECT | this.cw.addType(this.descriptor.substring(j, ++i)); break; case 'L': while (this.descriptor.charAt(i) != ';') { ++i; } this.frame[frameIndex++] = Frame.OBJECT | this.cw.addType(this.descriptor.substring(j + 1, i++)); break; default: break loop; } } this.frame[1] = frameIndex - 3; this.endFrame(); } private int startFrame(final int offset, final int nLocal, final int nStack) { int n = 3 + nLocal + nStack; if (this.frame == null || this.frame.length < n) { this.frame = new int[n]; } this.frame[0] = offset; this.frame[1] = nLocal; this.frame[2] = nStack; return 3; } private void endFrame() { if (this.previousFrame != null) { // do not write the first frame if (this.stackMap == null) { this.stackMap = new ByteVector(); } this.writeFrame(); ++this.frameCount; } this.previousFrame = this.frame; this.frame = null; } private void writeFrame() { int clocalsSize = this.frame[1]; int cstackSize = this.frame[2]; if ((this.cw.version & 0xFFFF) < ASMConstants.V1_6) { this.stackMap.putShort(this.frame[0]).putShort(clocalsSize); this.writeFrameTypes(3, 3 + clocalsSize); this.stackMap.putShort(cstackSize); this.writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); return; } int localsSize = this.previousFrame[1]; int type = FULL_FRAME; int k = 0; int delta; if (this.frameCount == 0) { delta = this.frame[0]; } else { delta = this.frame[0] - this.previousFrame[0] - 1; } if (cstackSize == 0) { k = clocalsSize - localsSize; switch (k) { case -3: case -2: case -1: type = CHOP_FRAME; localsSize = clocalsSize; break; case 0: type = delta < 64 ? SAME_FRAME : SAME_FRAME_EXTENDED; break; case 1: case 2: case 3: type = APPEND_FRAME; break; } } else if (clocalsSize == localsSize && cstackSize == 1) { type = delta < 63 ? SAME_LOCALS_1_STACK_ITEM_FRAME : SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; } if (type != FULL_FRAME) { // verify if locals are the same int l = 3; for (int j = 0; j < localsSize; j++) { if (this.frame[l] != this.previousFrame[l]) { type = FULL_FRAME; break; } l++; } } switch (type) { case SAME_FRAME: this.stackMap.putByte(delta); break; case SAME_LOCALS_1_STACK_ITEM_FRAME: this.stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); this.writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: this.stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(delta); this.writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_FRAME_EXTENDED: this.stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); break; case CHOP_FRAME: this.stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); break; case APPEND_FRAME: this.stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); this.writeFrameTypes(3 + localsSize, 3 + clocalsSize); break; // case FULL_FRAME: default: this.stackMap.putByte(FULL_FRAME).putShort(delta).putShort(clocalsSize); this.writeFrameTypes(3, 3 + clocalsSize); this.stackMap.putShort(cstackSize); this.writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); } } private void writeFrameTypes(final int start, final int end) { for (int i = start; i < end; ++i) { int t = this.frame[i]; int d = t & Frame.DIM; if (d == 0) { int v = t & Frame.BASE_VALUE; switch (t & Frame.BASE_KIND) { case Frame.OBJECT: this.stackMap.putByte(7).putShort(this.cw.newClass(this.cw.typeTable[v].strVal1)); break; case Frame.UNINITIALIZED: this.stackMap.putByte(8).putShort(this.cw.typeTable[v].intVal); break; default: this.stackMap.putByte(v); } } else { StringBuilder sb = new StringBuilder(); d >>= 28; while (d-- > 0) { sb.append('['); } if ((t & Frame.BASE_KIND) == Frame.OBJECT) { sb.append('L'); sb.append(this.cw.typeTable[t & Frame.BASE_VALUE].strVal1); sb.append(';'); } else { switch (t & 0xF) { case 1: sb.append('I'); break; case 2: sb.append('F'); break; case 3: sb.append('D'); break; case 9: sb.append('Z'); break; case 10: sb.append('B'); break; case 11: sb.append('C'); break; case 12: sb.append('S'); break; default: sb.append('J'); } } this.stackMap.putByte(7).putShort(this.cw.newClass(sb.toString())); } } } private void writeFrameType(final Object type) { if (type instanceof String) { this.stackMap.putByte(7).putShort(this.cw.newClass((String) type)); } else if (type instanceof Integer) { this.stackMap.putByte((Integer) type); } else { this.stackMap.putByte(8).putShort(((Label) type).position); } } final int getSize() { if (this.classReaderOffset != 0) { return 6 + this.classReaderLength; } int size = 8; if (this.code.length > 0) { if (this.code.length > 65536) { throw new RuntimeException("Method code too large!"); } this.cw.newUTF8("Code"); size += 18 + this.code.length + 8 * this.handlerCount; if (this.localVar != null) { this.cw.newUTF8("LocalVariableTable"); size += 8 + this.localVar.length; } if (this.localVarType != null) { this.cw.newUTF8("LocalVariableTypeTable"); size += 8 + this.localVarType.length; } if (this.lineNumber != null) { this.cw.newUTF8("LineNumberTable"); size += 8 + this.lineNumber.length; } if (this.stackMap != null) { boolean zip = (this.cw.version & 0xFFFF) >= ASMConstants.V1_6; this.cw.newUTF8(zip ? "StackMapTable" : "StackMap"); size += 8 + this.stackMap.length; } if (this.ctanns != null) { this.cw.newUTF8("RuntimeVisibleTypeAnnotations"); size += 8 + this.ctanns.getSize(); } if (this.ictanns != null) { this.cw.newUTF8("RuntimeInvisibleTypeAnnotations"); size += 8 + this.ictanns.getSize(); } if (this.cattrs != null) { size += this.cattrs.getSize(this.cw, this.code.data, this.code.length, this.maxStack, this.maxLocals); } } if (this.exceptionCount > 0) { this.cw.newUTF8("Exceptions"); size += 8 + 2 * this.exceptionCount; } if ((this.access & ASMConstants.ACC_SYNTHETIC) != 0) { if ((this.cw.version & 0xFFFF) < ASMConstants.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { this.cw.newUTF8("Synthetic"); size += 6; } } if ((this.access & ASMConstants.ACC_DEPRECATED) != 0) { this.cw.newUTF8("Deprecated"); size += 6; } if (this.signature != null) { this.cw.newUTF8("Signature"); this.cw.newUTF8(this.signature); size += 8; } if (this.methodParameters != null) { this.cw.newUTF8("MethodParameters"); size += 7 + this.methodParameters.length; } if (this.annd != null) { this.cw.newUTF8("AnnotationDefault"); size += 6 + this.annd.length; } if (this.anns != null) { this.cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + this.anns.getSize(); } if (this.ianns != null) { this.cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + this.ianns.getSize(); } if (this.tanns != null) { this.cw.newUTF8("RuntimeVisibleTypeAnnotations"); size += 8 + this.tanns.getSize(); } if (this.itanns != null) { this.cw.newUTF8("RuntimeInvisibleTypeAnnotations"); size += 8 + this.itanns.getSize(); } if (this.panns != null) { this.cw.newUTF8("RuntimeVisibleParameterAnnotations"); size += 7 + 2 * (this.panns.length - this.synthetics); for (int i = this.panns.length - 1; i >= this.synthetics; --i) { size += this.panns[i] == null ? 0 : this.panns[i].getSize(); } } if (this.ipanns != null) { this.cw.newUTF8("RuntimeInvisibleParameterAnnotations"); size += 7 + 2 * (this.ipanns.length - this.synthetics); for (int i = this.ipanns.length - 1; i >= this.synthetics; --i) { size += this.ipanns[i] == null ? 0 : this.ipanns[i].getSize(); } } if (this.attrs != null) { size += this.attrs.getSize(this.cw, null, 0, -1, -1); } return size; } final void put(final ByteVector out) { final int FACTOR = ClassWriter.TO_ACC_SYNTHETIC; int mask = ACC_CONSTRUCTOR | ASMConstants.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / FACTOR; out.putShort(this.access & ~mask).putShort(this.name).putShort(this.desc); if (this.classReaderOffset != 0) { out.putByteArray(this.cw.cr.b, this.classReaderOffset, this.classReaderLength); return; } int attributeCount = 0; if (this.code.length > 0) { ++attributeCount; } if (this.exceptionCount > 0) { ++attributeCount; } if ((this.access & ASMConstants.ACC_SYNTHETIC) != 0) { if ((this.cw.version & 0xFFFF) < ASMConstants.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { ++attributeCount; } } if ((this.access & ASMConstants.ACC_DEPRECATED) != 0) { ++attributeCount; } if (this.signature != null) { ++attributeCount; } if (this.methodParameters != null) { ++attributeCount; } if (this.annd != null) { ++attributeCount; } if (this.anns != null) { ++attributeCount; } if (this.ianns != null) { ++attributeCount; } if (this.tanns != null) { ++attributeCount; } if (this.itanns != null) { ++attributeCount; } if (this.panns != null) { ++attributeCount; } if (this.ipanns != null) { ++attributeCount; } if (this.attrs != null) { attributeCount += this.attrs.getCount(); } out.putShort(attributeCount); if (this.code.length > 0) { int size = 12 + this.code.length + 8 * this.handlerCount; if (this.localVar != null) { size += 8 + this.localVar.length; } if (this.localVarType != null) { size += 8 + this.localVarType.length; } if (this.lineNumber != null) { size += 8 + this.lineNumber.length; } if (this.stackMap != null) { size += 8 + this.stackMap.length; } if (this.ctanns != null) { size += 8 + this.ctanns.getSize(); } if (this.ictanns != null) { size += 8 + this.ictanns.getSize(); } if (this.cattrs != null) { size += this.cattrs.getSize(this.cw, this.code.data, this.code.length, this.maxStack, this.maxLocals); } out.putShort(this.cw.newUTF8("Code")).putInt(size); out.putShort(this.maxStack).putShort(this.maxLocals); out.putInt(this.code.length).putByteArray(this.code.data, 0, this.code.length); out.putShort(this.handlerCount); if (this.handlerCount > 0) { Handler h = this.firstHandler; while (h != null) { out.putShort(h.start.position).putShort(h.end.position).putShort(h.handler.position) .putShort(h.type); h = h.next; } } attributeCount = 0; if (this.localVar != null) { ++attributeCount; } if (this.localVarType != null) { ++attributeCount; } if (this.lineNumber != null) { ++attributeCount; } if (this.stackMap != null) { ++attributeCount; } if (this.ctanns != null) { ++attributeCount; } if (this.ictanns != null) { ++attributeCount; } if (this.cattrs != null) { attributeCount += this.cattrs.getCount(); } out.putShort(attributeCount); if (this.localVar != null) { out.putShort(this.cw.newUTF8("LocalVariableTable")); out.putInt(this.localVar.length + 2).putShort(this.localVarCount); out.putByteArray(this.localVar.data, 0, this.localVar.length); } if (this.localVarType != null) { out.putShort(this.cw.newUTF8("LocalVariableTypeTable")); out.putInt(this.localVarType.length + 2).putShort(this.localVarTypeCount); out.putByteArray(this.localVarType.data, 0, this.localVarType.length); } if (this.lineNumber != null) { out.putShort(this.cw.newUTF8("LineNumberTable")); out.putInt(this.lineNumber.length + 2).putShort(this.lineNumberCount); out.putByteArray(this.lineNumber.data, 0, this.lineNumber.length); } if (this.stackMap != null) { boolean zip = (this.cw.version & 0xFFFF) >= ASMConstants.V1_6; out.putShort(this.cw.newUTF8(zip ? "StackMapTable" : "StackMap")); out.putInt(this.stackMap.length + 2).putShort(this.frameCount); out.putByteArray(this.stackMap.data, 0, this.stackMap.length); } if (this.ctanns != null) { out.putShort(this.cw.newUTF8("RuntimeVisibleTypeAnnotations")); this.ctanns.put(out); } if (this.ictanns != null) { out.putShort(this.cw.newUTF8("RuntimeInvisibleTypeAnnotations")); this.ictanns.put(out); } if (this.cattrs != null) { this.cattrs.put(this.cw, this.code.data, this.code.length, this.maxLocals, this.maxStack, out); } } if (this.exceptionCount > 0) { out.putShort(this.cw.newUTF8("Exceptions")).putInt(2 * this.exceptionCount + 2); out.putShort(this.exceptionCount); for (int i = 0; i < this.exceptionCount; ++i) { out.putShort(this.exceptions[i]); } } if ((this.access & ASMConstants.ACC_SYNTHETIC) != 0) { if ((this.cw.version & 0xFFFF) < ASMConstants.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { out.putShort(this.cw.newUTF8("Synthetic")).putInt(0); } } if ((this.access & ASMConstants.ACC_DEPRECATED) != 0) { out.putShort(this.cw.newUTF8("Deprecated")).putInt(0); } if (this.signature != null) { out.putShort(this.cw.newUTF8("Signature")).putInt(2).putShort(this.cw.newUTF8(this.signature)); } if (this.methodParameters != null) { out.putShort(this.cw.newUTF8("MethodParameters")); out.putInt(this.methodParameters.length + 1).putByte(this.methodParametersCount); out.putByteArray(this.methodParameters.data, 0, this.methodParameters.length); } if (this.annd != null) { out.putShort(this.cw.newUTF8("AnnotationDefault")); out.putInt(this.annd.length); out.putByteArray(this.annd.data, 0, this.annd.length); } if (this.anns != null) { out.putShort(this.cw.newUTF8("RuntimeVisibleAnnotations")); this.anns.put(out); } if (this.ianns != null) { out.putShort(this.cw.newUTF8("RuntimeInvisibleAnnotations")); this.ianns.put(out); } if (this.tanns != null) { out.putShort(this.cw.newUTF8("RuntimeVisibleTypeAnnotations")); this.tanns.put(out); } if (this.itanns != null) { out.putShort(this.cw.newUTF8("RuntimeInvisibleTypeAnnotations")); this.itanns.put(out); } if (this.panns != null) { out.putShort(this.cw.newUTF8("RuntimeVisibleParameterAnnotations")); AnnotationWriter.put(this.panns, this.synthetics, out); } if (this.ipanns != null) { out.putShort(this.cw.newUTF8("RuntimeInvisibleParameterAnnotations")); AnnotationWriter.put(this.ipanns, this.synthetics, out); } if (this.attrs != null) { this.attrs.put(this.cw, null, 0, -1, -1, out); } } private void resizeInstructions() { byte[] b = this.code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: Parse the code * to find the jump instructions whose offset will need more than 2 * bytes to be stored (the future offset is computed from the current * offset and from the number of bytes that will be inserted or removed * between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. In fact the real algorithm is * complicated by the fact that the size of TABLESWITCH and LOOKUPSWITCH * instructions depends on their position in the bytecode (because of * padding). In order to ensure the convergence of the algorithm, the * number of bytes to be added or removed from these instructions is * over estimated during the previous loop, and computed exactly only * after the loop is finished (this requires another pass to parse the * bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[this.code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == ASMConstants.GOTO || opcode == ASMConstants.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx <l> instruction with // IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where <l'> designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == ASMConstants.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(this.code.length); u = 0; while (u < this.code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // <l> with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where <l'> designates the instruction just after // the GOTO_W. if (opcode == ASMConstants.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == ASMConstants.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? (opcode + 1 ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(ASMConstants.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(ASMConstants.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == ASMConstants.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // updates the stack map frame labels if (this.compute == FRAMES) { Label l = this.labels; while (l != null) { /* * Detects the labels that are just after an IF instruction that * has been resized with the IFNOT GOTO_W pattern. These labels * are now the target of a jump instruction (the IFNOT * instruction). Note that we need the original label position * here. getNewOffset must therefore never have been called for * this label. */ u = l.position - 3; if (u >= 0 && resize[u]) { l.status |= Label.TARGET; } getNewOffset(allIndexes, allSizes, l); l = l.successor; } // Update the offsets in the uninitialized types if (this.cw.typeTable != null) { for (i = 0; i < this.cw.typeTable.length; ++i) { Item item = this.cw.typeTable[i]; if (item != null && item.type == ClassWriter.TYPE_UNINIT) { item.intVal = getNewOffset(allIndexes, allSizes, 0, item.intVal); } } } // The stack map frames are not serialized yet, so we don't need // to update them. They will be serialized in visitMaxs. } else if (this.frameCount > 0) { /* * Resizing an existing stack map frame table is really hard. Not * only the table must be parsed to update the offets, but new * frames may be needed for jump instructions that were inserted by * this method. And updating the offsets or inserting frames can * change the format of the following frames, in case of packed * frames. In practice the whole table must be recomputed. For this * the frames are marked as potentially invalid. This will cause the * whole class to be reread and rewritten with the COMPUTE_FRAMES * option (see the ClassWriter.toByteArray method). This is not very * efficient but is much easier and requires much less code than any * other method I can think of. */ this.cw.invalidFrames = true; } // updates the exception handler block labels Handler h = this.firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? this.localVar : this.localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (this.lineNumber != null) { b = this.lineNumber.data; u = 0; while (u < this.lineNumber.length) { writeShort(b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = this.cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones this.code = newCode; } static int readUnsignedShort(final byte[] b, final int index) { return (b[index] & 0xFF) << 8 | b[index + 1] & 0xFF; } static short readShort(final byte[] b, final int index) { return (short) ((b[index] & 0xFF) << 8 | b[index + 1] & 0xFF); } static int readInt(final byte[] b, final int index) { return (b[index] & 0xFF) << 24 | (b[index + 1] & 0xFF) << 16 | (b[index + 2] & 0xFF) << 8 | b[index + 3] & 0xFF; } static void writeShort(final byte[] b, final int index, final int s) { b[index] = (byte) (s >>> 8); b[index + 1] = (byte) s; } static int getNewOffset(final int[] indexes, final int[] sizes, final int begin, final int end) { int offset = end - begin; for (int i = 0; i < indexes.length; ++i) { if (begin < indexes[i] && indexes[i] <= end) { // forward jump offset += sizes[i]; } else if (end < indexes[i] && indexes[i] <= begin) { // backward jump offset -= sizes[i]; } } return offset; } static void getNewOffset(final int[] indexes, final int[] sizes, final Label label) { if ((label.status & Label.RESIZED) == 0) { label.position = getNewOffset(indexes, sizes, 0, label.position); label.status |= Label.RESIZED; } } }
bsd-3-clause
chrisglass/django-cms
cms/static/cms/js/change_list.js
15175
// some very small jquery extensions (function($) { // very simple yellow fade plugin.. $.fn.yft = function(){ this.effect("highlight", {}, 1000); }; // jquery replace plugin :) $.fn.replace = function(o) { return this.after(o).remove().end(); }; var tree; // global initTree function initTree = function(){ tree = new tree_component(); var options = { rules: { clickable: "all", renameable: "none", deletable: "all", creatable: "all", draggable: "all", dragrules: "all", droppable: "all", metadata : "mdata", use_inline: true //droppable : ["tree_drop"] }, path: false, ui: { dots: true, rtl: false, animation: 0, hover_mode: true, theme_path: false, theme_name: "default", a_class: "title" }, cookies : { prefix: "djangocms_nodes" }, callback: { beforemove : function(what, where, position) { item_id = what.id.split("page_")[1]; target_id = where.id.split("page_")[1]; old_node = what; if($(what).parent().children("li").length > 1){ if($(what).next("li").length){ old_target = $(what).next("li")[0]; old_position = "right"; } if($(what).prev("li").length){ old_target = $(what).prev("li")[0]; old_position = "left"; } }else{ if($(what).attr("rel") != "topnode"){ old_target = $(what).parent().parent()[0]; old_position = "inside"; } } addUndo(what, where, position); return true; }, onmove: function(what, where, position){ item_id = what.id.split("page_")[1]; target_id = where.id.split("page_")[1]; if (position == "before") { position = "left"; }else if (position == "after") { position = "right"; }else if(position == "inside"){ position = "last-child"; } moveTreeItem(what, item_id, target_id, position, false); }, onchange: function(node){ url = $(node).find('a.title').attr("href"); window.location = url; } } }; if (!$($("div.tree").get(0)).hasClass('root_allow_children')){ // disalow possibility for adding subnodes to main tree, user doesn't // have permissions for this options.rules.dragrules = ["node inside topnode", "topnode inside topnode", "node * node"]; } //dragrules : [ "folder * folder", "folder inside root", "tree-drop * folder" ], tree.init($("div.tree"), options); }; $(document).ready(function() { selected_page = false; action = false; var _oldAjax = $.ajax; $.ajax = function(s){ // just override ajax function, so the loader message gets displayed // always $('#loader-message').show(); callback = s.success || false; s.success = function(data, status){ if (callback) { callback(data, status); } $('#loader-message').hide(); syncCols(); }; // just for debuging!! /*s.complete = function(xhr, status) { if (status == "error" && cmsSettings.debug) { $('body').before(xhr.responseText); } }*/ // end just for debuging // TODO: add error state! return _oldAjax(s); }; function refresh(){ window.location = window.location.href; } function refreshIfChildren(pageId){ return $('#page_' + pageId).find('li[id^=page_]').length ? refresh : function(){}; } /** * Loads remote dialog to dialogs div. * * @param {String} url * @param {Object} data Data to be send over post * @param {Function} noDialogCallback Gets called when response is empty. * @param {Function} callback Standard callback function. */ function loadDialog(url, data, noDialogCallback, callback){ if (data === undefined) data = {}; $.post(url, data, function(response) { if (response == '' && noDialogCallback) noDialogCallback(); $('#dialogs').empty().append(response); if (callback) callback(response); }); } // let's start event delegation $('#changelist li').click(function(e) { // I want a link to check the class if(e.target.tagName == 'IMG' || e.target.tagName == 'SPAN') { target = e.target.parentNode; } else { target = e.target; } var jtarget = $(target); if(jtarget.hasClass("move")) { // prepare tree for move / cut paste var id = e.target.id.split("move-link-")[1]; if(id==null){ id = e.target.parentNode.id.split("move-link-")[1]; } var page_id = id; selected_page = page_id; action = "move"; $('span.move-target-container, span.line, a.move-target').show(); $('#page_'+page_id).addClass("selected"); $('#page_'+page_id+' span.move-target-container').hide(); e.stopPropagation(); return false; } if(jtarget.hasClass("copy")) { // prepare tree for copy id = e.target.id.split("copy-link-")[1]; if(id==null){ id = e.target.parentNode.id.split("copy-link-")[1]; } selected_page = id; action = mark_copy_node(id); e.stopPropagation(); return false; } if(jtarget.hasClass("viewpage")) { var view_page_url = $('#' + target.id + '-select').val(); if(view_page_url){ window.open(view_page_url); } } if(jtarget.hasClass("addlink")) { if (!/#$/g.test(jtarget.attr('href'))) { // if there is url instead of # inside href, follow this url // used if user haves add_page return true; } $("tr").removeClass("target"); $("#changelist table").removeClass("table-selected"); page_id = target.id.split("add-link-")[1]; selected_page = page_id; action = "add"; $('tr').removeClass("selected"); $('#page-row-'+page_id).addClass("selected"); $('.move-target-container').hide(); $('a.move-target, span.line, #move-target-'+page_id).show(); e.stopPropagation(); return false; } // don't assume admin site is root-level // grab base url to construct full absolute URLs admin_base_url = document.URL.split("/cms/page/")[0] + "/"; // publish if(jtarget.hasClass("publish-checkbox")) { pageId = jtarget.attr("name").split("status-")[1]; // if I don't put data in the post, django doesn't get it reloadItem(jtarget, admin_base_url + "cms/page/" + pageId + "/change-status/", { 1:1 }); e.stopPropagation(); return true; } // in navigation if(jtarget.hasClass("navigation-checkbox")) { pageId = jtarget.attr("name").split("navigation-")[1]; // if I don't put data in the post, django doesn't get it reloadItem(jtarget, admin_base_url + "cms/page/" + pageId + "/change-navigation/", { 1:1 }); e.stopPropagation(); return true; } // moderation if(jtarget.hasClass("moderator-checkbox")) { pageId = jtarget.parents('li[id^=page_]').attr('id').split('_')[1]; parent = jtarget.parents('div.col-moderator'); value = 0; parent.find('input[type=checkbox]').each(function(i, el){ value += $(el).attr("checked") ? parseInt($(el).val()) : 0; }); // just reload the page for now in callback... // TODO: this must be changed sometimes to reloading just the portion // of the tree = current node + descendants reloadItem(jtarget, admin_base_url + "cms/page/" + pageId + "/change-moderation/", { moderate: value }, refreshIfChildren(pageId)); e.stopPropagation(); return true; } // quick approve if(jtarget.hasClass("approve")) { pageId = jtarget.parents('li[id^=page_]').attr('id').split('_')[1]; // just reload the page for now in callback... // TODO: this must be changed sometimes to reloading just the portion // of the tree = current node + descendants reloadItem(jtarget, admin_base_url + "cms/page/" + pageId + "/approve/?node=1", {}, refreshIfChildren(pageId)); e.stopPropagation(); return false; } // lazy load descendants on tree open if(jtarget.hasClass("closed")) { // only load them once if(jtarget.find('ul > li').length == 0 && !jtarget.hasClass("loading")) { // keeps this event from firing multiple times before // the dom as changed. it still needs to propagate for // the other click event on this element to fire jtarget.addClass("loading"); var pageId = $(jtarget).attr("id").split("page_")[1]; $.get(admin_base_url + "cms/page/" + pageId + "/descendants/", {}, function(r, status) { jtarget.children('ul').append(r); // show move targets if needed if($('span.move-target-container:visible').length > 0) { jtarget.children('ul').find('a.move-target, span.move-target-container, span.line').show(); } }); } } if(jtarget.hasClass("move-target")) { if(jtarget.hasClass("left")){ position = "left"; } if(jtarget.hasClass("right")){ position = "right"; } if(jtarget.hasClass("last-child")){ position = "last-child"; } target_id = target.parentNode.id.split("move-target-")[1]; if(action=="move") { moveTreeItem(null, selected_page, target_id, position, tree); $('.move-target-container').hide(); }else if(action=="copy") { site = $('#site-select')[0].value; copyTreeItem(selected_page, target_id, position, site); $('.move-target-container').hide(); }else if(action=="add") { site = $('#site-select')[0].value; window.location.href = window.location.href.split("?")[0].split("#")[0] + 'add/?target='+target_id+"&amp;position="+position+"&amp;site="+site; } e.stopPropagation(); return false; } return true; }); /* Colums width sync */ $.fn.syncWidth = function(max) { $(this).each(function() { var val= $(this).width(); if(val > max){max = val;} }); $(this).each(function() { $(this).css("width",max + 'px'); }); return this; }; $("div#sitemap").show(); function syncCols(){ $('#sitemap ul .col-actions').syncWidth(0); $('#sitemap ul .col-published').syncWidth(0); $('#sitemap ul .col-navigation').syncWidth(0); $('#sitemap ul .col-softroot').syncWidth(0); $('#sitemap ul .col-template').syncWidth(0); $('#sitemap ul .col-creator').syncWidth(0); $('#sitemap ul .col-lastchange').syncWidth(0); $('#sitemap ul .col-moderator').syncWidth(68); $('#sitemap ul .col-draft').syncWidth(0); } syncCols(); /* Site Selector */ $('#site-select').change(function(event){ var id = this.value; var url = window.location.href; if(action=="copy"){ //url = insert_into_url(url, "copy", selected_page); url = CMS.API.Helpers.setUrl(document.location, { 'addParam': "copy=" + selected_page, 'removeParam': "copy" }); }else{ //url = remove_from_url(url, "copy"); url = CMS.API.Helpers.setUrl(document.location, { 'addParam': "copy", 'removeParam': "copy" }); } //url = insert_into_url(url, "site__exact", id); url = CMS.API.Helpers.setUrl(document.location, { 'addParam': "site__exact=" + id, 'removeParam': "site__exact" }); window.location.href = url; }); var copy_splits = window.location.href.split("copy="); if(copy_splits.length > 1){ var id = copy_splits[1].split("&")[0]; var action = mark_copy_node(id); selected_page = id; } // moderation checkboxes over livequery $('div.col-moderator input').livequery(function() { $(this).checkBox({addLabel:false}); }); function copyTreeItem(item_id, target_id, position, site){ if (cmsSettings.cmsPermission || cmsSettings.cmsModerator) { return loadDialog('./' + item_id + '/dialog/copy/', { position:position, target:target_id, site:site, callback: $.callbackRegister("_copyTreeItem", _copyTreeItem, item_id, target_id, position, site) }); } return _copyTreeItem(item_id, target_id, position, site); } function _copyTreeItem(item_id, target_id, position, site, options) { var data = { position:position, target:target_id, site:site }; data = $.extend(data, options); $.post("./" + item_id + "/copy-page/", data, function(html) { if(html=="ok"){ // reload tree window.location = window.location.href; }else{ moveError($('#page_'+item_id + " div.col1:eq(0)")); } }); } function mark_copy_node(id){ $('a.move-target, span.move-target-container, span.line').show(); $('#page_'+id).addClass("selected"); $('#page_'+id).parent().parent().children('div.cont').find('a.move-target.first-child, span.second').hide(); $('#page_'+id).parent().parent().children('ul').children('li').children('div.cont').find('a.move-target.left, a.move-target.right, span.first, span.second').hide(); return "copy"; } }); /** * Reloads tree item (one line). If some filtering is found, adds * filtered variable into posted data. * * @param {HTMLElement} el Any child element of tree item * @param {String} url Requested url * @param {Object} data Optional posted data * @param {Function} callback Optional calback function */ function reloadItem(el, url, data, callback, errorCallback) { if (data === undefined) data = {}; if (/\/\?/ig.test(window.location.href)) { // probably some filter here, tell backend, we need a filtered // version of item data['fitlered'] = 1; } function onSuccess(response, textStatus) { if (callback) callback(response, textStatus); if (/page_\d+/.test($(el).attr('id'))) { // one level higher target = $(el).find('div.cont:first'); } else { target = $(el).parents('div.cont:first'); } var parent = target.parent(); if (response == "NotFound") { return parent.remove(); } target.replace(response); parent.find('div.cont:first').yft(); return true; } function onError(XMLHttpRequest, textStatus, errorThrown) { if (errorCallback) errorCallback(XMLHttpRequest, textStatus, errorThrown); } $.ajax({ 'data': data, 'success': onSuccess, 'error': onError, 'type': 'POST', 'url': url, 'xhr': (window.ActiveXObject) ? function(){try {return new window.ActiveXObject("Microsoft.XMLHTTP");} catch(e) {}} : function() {return new window.XMLHttpRequest();} }); } function moveTreeItem(jtarget, item_id, target_id, position, tree){ reloadItem( jtarget, "./" + item_id + "/move-page/", { position: position, target: target_id }, // on success function(){ if (tree) { var tree_pos = {'left': 'before', 'right': 'after'}[position] || 'inside'; tree.moved("#page_" + item_id, $("#page_" + target_id + " a.title")[0], tree_pos, false, false); } else { moveSuccess($('#page_'+item_id + " div.col1:eq(0)")); } }, // on error function(){ moveError($('#page_'+item_id + " div.col1:eq(0)")); } ); } var undos = []; function addUndo(node, target, position){ undos.push({node:node, target:target, position:position}); } })(jQuery);
bsd-3-clause
rileychapman/roscopter-1
mavlink/pymavlink/build/lib.linux-x86_64-2.7/pymavlink/dialects/v10/pixhawk.py
430658
''' MAVLink protocol implementation (auto-generated by mavgen.py) Generated from: pixhawk.xml,common.xml Note: this file has been auto-generated. DO NOT EDIT ''' import struct, array, time, json from ...generator.mavcrc import x25crc WIRE_PROTOCOL_VERSION = "1.0" # some base types from mavlink_types.h MAVLINK_TYPE_CHAR = 0 MAVLINK_TYPE_UINT8_T = 1 MAVLINK_TYPE_INT8_T = 2 MAVLINK_TYPE_UINT16_T = 3 MAVLINK_TYPE_INT16_T = 4 MAVLINK_TYPE_UINT32_T = 5 MAVLINK_TYPE_INT32_T = 6 MAVLINK_TYPE_UINT64_T = 7 MAVLINK_TYPE_INT64_T = 8 MAVLINK_TYPE_FLOAT = 9 MAVLINK_TYPE_DOUBLE = 10 class MAVLink_header(object): '''MAVLink message header''' def __init__(self, msgId, mlen=0, seq=0, srcSystem=0, srcComponent=0): self.mlen = mlen self.seq = seq self.srcSystem = srcSystem self.srcComponent = srcComponent self.msgId = msgId def pack(self): return struct.pack('BBBBBB', 254, self.mlen, self.seq, self.srcSystem, self.srcComponent, self.msgId) class MAVLink_message(object): '''base MAVLink message class''' def __init__(self, msgId, name): self._header = MAVLink_header(msgId) self._payload = None self._msgbuf = None self._crc = None self._fieldnames = [] self._type = name def get_msgbuf(self): if isinstance(self._msgbuf, str): return self._msgbuf return self._msgbuf.tostring() def get_header(self): return self._header def get_payload(self): return self._payload def get_crc(self): return self._crc def get_fieldnames(self): return self._fieldnames def get_type(self): return self._type def get_msgId(self): return self._header.msgId def get_srcSystem(self): return self._header.srcSystem def get_srcComponent(self): return self._header.srcComponent def get_seq(self): return self._header.seq def __str__(self): ret = '%s {' % self._type for a in self._fieldnames: v = getattr(self, a) ret += '%s : %s, ' % (a, v) ret = ret[0:-2] + '}' return ret def to_dict(self): d = dict({}) d['mavpackettype'] = self._type for a in self._fieldnames: d[a] = getattr(self, a) return d def to_json(self): return json.dumps(self.to_dict()) def pack(self, mav, crc_extra, payload): self._payload = payload self._header = MAVLink_header(self._header.msgId, len(payload), mav.seq, mav.srcSystem, mav.srcComponent) self._msgbuf = self._header.pack() + payload crc = x25crc(self._msgbuf[1:]) if True: # using CRC extra crc.accumulate(chr(crc_extra)) self._crc = crc.crc self._msgbuf += struct.pack('<H', self._crc) return self._msgbuf # enums # DATA_TYPES DATA_TYPE_JPEG_IMAGE = 1 # DATA_TYPE_RAW_IMAGE = 2 # DATA_TYPE_KINECT = 3 # DATA_TYPES_ENUM_END = 4 # # MAV_CMD MAV_CMD_NAV_WAYPOINT = 16 # Navigate to MISSION. MAV_CMD_NAV_LOITER_UNLIM = 17 # Loiter around this MISSION an unlimited amount of time MAV_CMD_NAV_LOITER_TURNS = 18 # Loiter around this MISSION for X turns MAV_CMD_NAV_LOITER_TIME = 19 # Loiter around this MISSION for X seconds MAV_CMD_NAV_RETURN_TO_LAUNCH = 20 # Return to launch location MAV_CMD_NAV_LAND = 21 # Land at location MAV_CMD_NAV_TAKEOFF = 22 # Takeoff from ground / hand MAV_CMD_NAV_ROI = 80 # Sets the region of interest (ROI) for a sensor set or the vehicle # itself. This can then be used by the # vehicles control system to control the # vehicle attitude and the attitude of various # sensors such as cameras. MAV_CMD_NAV_PATHPLANNING = 81 # Control autonomous path planning on the MAV. MAV_CMD_NAV_LAST = 95 # NOP - This command is only used to mark the upper limit of the # NAV/ACTION commands in the enumeration MAV_CMD_CONDITION_DELAY = 112 # Delay mission state machine. MAV_CMD_CONDITION_CHANGE_ALT = 113 # Ascend/descend at rate. Delay mission state machine until desired # altitude reached. MAV_CMD_CONDITION_DISTANCE = 114 # Delay mission state machine until within desired distance of next NAV # point. MAV_CMD_CONDITION_YAW = 115 # Reach a certain target angle. MAV_CMD_CONDITION_LAST = 159 # NOP - This command is only used to mark the upper limit of the # CONDITION commands in the enumeration MAV_CMD_DO_SET_MODE = 176 # Set system mode. MAV_CMD_DO_JUMP = 177 # Jump to the desired command in the mission list. Repeat this action # only the specified number of times MAV_CMD_DO_CHANGE_SPEED = 178 # Change speed and/or throttle set points. MAV_CMD_DO_SET_HOME = 179 # Changes the home location either to the current location or a # specified location. MAV_CMD_DO_SET_PARAMETER = 180 # Set a system parameter. Caution! Use of this command requires # knowledge of the numeric enumeration value # of the parameter. MAV_CMD_DO_SET_RELAY = 181 # Set a relay to a condition. MAV_CMD_DO_REPEAT_RELAY = 182 # Cycle a relay on and off for a desired number of cyles with a desired # period. MAV_CMD_DO_SET_SERVO = 183 # Set a servo to a desired PWM value. MAV_CMD_DO_REPEAT_SERVO = 184 # Cycle a between its nominal setting and a desired PWM for a desired # number of cycles with a desired period. MAV_CMD_DO_CONTROL_VIDEO = 200 # Control onboard camera system. MAV_CMD_DO_SET_ROI = 201 # Sets the region of interest (ROI) for a sensor set or the vehicle # itself. This can then be used by the # vehicles control system to control the # vehicle attitude and the attitude of various # sensors such as cameras. MAV_CMD_DO_LAST = 240 # NOP - This command is only used to mark the upper limit of the DO # commands in the enumeration MAV_CMD_PREFLIGHT_CALIBRATION = 241 # Trigger calibration. This command will be only accepted if in pre- # flight mode. MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS = 242 # Set sensor offsets. This command will be only accepted if in pre- # flight mode. MAV_CMD_PREFLIGHT_STORAGE = 245 # Request storage of different parameter values and logs. This command # will be only accepted if in pre-flight mode. MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN = 246 # Request the reboot or shutdown of system components. MAV_CMD_OVERRIDE_GOTO = 252 # Hold / continue the current action MAV_CMD_MISSION_START = 300 # start running a mission MAV_CMD_COMPONENT_ARM_DISARM = 400 # Arms / Disarms a component MAV_CMD_START_RX_PAIR = 500 # Starts receiver pairing MAV_CMD_ENUM_END = 501 # MAV_CMD_DO_START_SEARCH = 10001 # Starts a search MAV_CMD_DO_FINISH_SEARCH = 10002 # Starts a search MAV_CMD_NAV_SWEEP = 10003 # Starts a search # MAV_AUTOPILOT MAV_AUTOPILOT_GENERIC = 0 # Generic autopilot, full support for everything MAV_AUTOPILOT_PIXHAWK = 1 # PIXHAWK autopilot, http://pixhawk.ethz.ch MAV_AUTOPILOT_SLUGS = 2 # SLUGS autopilot, http://slugsuav.soe.ucsc.edu MAV_AUTOPILOT_ARDUPILOTMEGA = 3 # ArduPilotMega / ArduCopter, http://diydrones.com MAV_AUTOPILOT_OPENPILOT = 4 # OpenPilot, http://openpilot.org MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY = 5 # Generic autopilot only supporting simple waypoints MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY = 6 # Generic autopilot supporting waypoints and other simple navigation # commands MAV_AUTOPILOT_GENERIC_MISSION_FULL = 7 # Generic autopilot supporting the full mission command set MAV_AUTOPILOT_INVALID = 8 # No valid autopilot, e.g. a GCS or other MAVLink component MAV_AUTOPILOT_PPZ = 9 # PPZ UAV - http://nongnu.org/paparazzi MAV_AUTOPILOT_UDB = 10 # UAV Dev Board MAV_AUTOPILOT_FP = 11 # FlexiPilot MAV_AUTOPILOT_PX4 = 12 # PX4 Autopilot - http://pixhawk.ethz.ch/px4/ MAV_AUTOPILOT_SMACCMPILOT = 13 # SMACCMPilot - http://smaccmpilot.org MAV_AUTOPILOT_AUTOQUAD = 14 # AutoQuad -- http://autoquad.org MAV_AUTOPILOT_ARMAZILA = 15 # Armazila -- http://armazila.com MAV_AUTOPILOT_AEROB = 16 # Aerob -- http://aerob.ru MAV_AUTOPILOT_ENUM_END = 17 # # MAV_TYPE MAV_TYPE_GENERIC = 0 # Generic micro air vehicle. MAV_TYPE_FIXED_WING = 1 # Fixed wing aircraft. MAV_TYPE_QUADROTOR = 2 # Quadrotor MAV_TYPE_COAXIAL = 3 # Coaxial helicopter MAV_TYPE_HELICOPTER = 4 # Normal helicopter with tail rotor. MAV_TYPE_ANTENNA_TRACKER = 5 # Ground installation MAV_TYPE_GCS = 6 # Operator control unit / ground control station MAV_TYPE_AIRSHIP = 7 # Airship, controlled MAV_TYPE_FREE_BALLOON = 8 # Free balloon, uncontrolled MAV_TYPE_ROCKET = 9 # Rocket MAV_TYPE_GROUND_ROVER = 10 # Ground rover MAV_TYPE_SURFACE_BOAT = 11 # Surface vessel, boat, ship MAV_TYPE_SUBMARINE = 12 # Submarine MAV_TYPE_HEXAROTOR = 13 # Hexarotor MAV_TYPE_OCTOROTOR = 14 # Octorotor MAV_TYPE_TRICOPTER = 15 # Octorotor MAV_TYPE_FLAPPING_WING = 16 # Flapping wing MAV_TYPE_KITE = 17 # Flapping wing MAV_TYPE_ENUM_END = 18 # # MAV_MODE_FLAG MAV_MODE_FLAG_CUSTOM_MODE_ENABLED = 1 # 0b00000001 Reserved for future use. MAV_MODE_FLAG_TEST_ENABLED = 2 # 0b00000010 system has a test mode enabled. This flag is intended for # temporary system tests and should not be # used for stable implementations. MAV_MODE_FLAG_AUTO_ENABLED = 4 # 0b00000100 autonomous mode enabled, system finds its own goal # positions. Guided flag can be set or not, # depends on the actual implementation. MAV_MODE_FLAG_GUIDED_ENABLED = 8 # 0b00001000 guided mode enabled, system flies MISSIONs / mission items. MAV_MODE_FLAG_STABILIZE_ENABLED = 16 # 0b00010000 system stabilizes electronically its attitude (and # optionally position). It needs however # further control inputs to move around. MAV_MODE_FLAG_HIL_ENABLED = 32 # 0b00100000 hardware in the loop simulation. All motors / actuators are # blocked, but internal software is full # operational. MAV_MODE_FLAG_MANUAL_INPUT_ENABLED = 64 # 0b01000000 remote control input is enabled. MAV_MODE_FLAG_SAFETY_ARMED = 128 # 0b10000000 MAV safety set to armed. Motors are enabled / running / can # start. Ready to fly. MAV_MODE_FLAG_ENUM_END = 129 # # MAV_MODE_FLAG_DECODE_POSITION MAV_MODE_FLAG_DECODE_POSITION_CUSTOM_MODE = 1 # Eighth bit: 00000001 MAV_MODE_FLAG_DECODE_POSITION_TEST = 2 # Seventh bit: 00000010 MAV_MODE_FLAG_DECODE_POSITION_AUTO = 4 # Sixt bit: 00000100 MAV_MODE_FLAG_DECODE_POSITION_GUIDED = 8 # Fifth bit: 00001000 MAV_MODE_FLAG_DECODE_POSITION_STABILIZE = 16 # Fourth bit: 00010000 MAV_MODE_FLAG_DECODE_POSITION_HIL = 32 # Third bit: 00100000 MAV_MODE_FLAG_DECODE_POSITION_MANUAL = 64 # Second bit: 01000000 MAV_MODE_FLAG_DECODE_POSITION_SAFETY = 128 # First bit: 10000000 MAV_MODE_FLAG_DECODE_POSITION_ENUM_END = 129 # # MAV_GOTO MAV_GOTO_DO_HOLD = 0 # Hold at the current position. MAV_GOTO_DO_CONTINUE = 1 # Continue with the next item in mission execution. MAV_GOTO_HOLD_AT_CURRENT_POSITION = 2 # Hold at the current position of the system MAV_GOTO_HOLD_AT_SPECIFIED_POSITION = 3 # Hold at the position specified in the parameters of the DO_HOLD action MAV_GOTO_ENUM_END = 4 # # MAV_MODE MAV_MODE_PREFLIGHT = 0 # System is not ready to fly, booting, calibrating, etc. No flag is set. MAV_MODE_MANUAL_DISARMED = 64 # System is allowed to be active, under manual (RC) control, no # stabilization MAV_MODE_TEST_DISARMED = 66 # UNDEFINED mode. This solely depends on the autopilot - use with # caution, intended for developers only. MAV_MODE_STABILIZE_DISARMED = 80 # System is allowed to be active, under assisted RC control. MAV_MODE_GUIDED_DISARMED = 88 # System is allowed to be active, under autonomous control, manual # setpoint MAV_MODE_AUTO_DISARMED = 92 # System is allowed to be active, under autonomous control and # navigation (the trajectory is decided # onboard and not pre-programmed by MISSIONs) MAV_MODE_MANUAL_ARMED = 192 # System is allowed to be active, under manual (RC) control, no # stabilization MAV_MODE_TEST_ARMED = 194 # UNDEFINED mode. This solely depends on the autopilot - use with # caution, intended for developers only. MAV_MODE_STABILIZE_ARMED = 208 # System is allowed to be active, under assisted RC control. MAV_MODE_GUIDED_ARMED = 216 # System is allowed to be active, under autonomous control, manual # setpoint MAV_MODE_AUTO_ARMED = 220 # System is allowed to be active, under autonomous control and # navigation (the trajectory is decided # onboard and not pre-programmed by MISSIONs) MAV_MODE_ENUM_END = 221 # # MAV_STATE MAV_STATE_UNINIT = 0 # Uninitialized system, state is unknown. MAV_STATE_BOOT = 1 # System is booting up. MAV_STATE_CALIBRATING = 2 # System is calibrating and not flight-ready. MAV_STATE_STANDBY = 3 # System is grounded and on standby. It can be launched any time. MAV_STATE_ACTIVE = 4 # System is active and might be already airborne. Motors are engaged. MAV_STATE_CRITICAL = 5 # System is in a non-normal flight mode. It can however still navigate. MAV_STATE_EMERGENCY = 6 # System is in a non-normal flight mode. It lost control over parts or # over the whole airframe. It is in mayday and # going down. MAV_STATE_POWEROFF = 7 # System just initialized its power-down sequence, will shut down now. MAV_STATE_ENUM_END = 8 # # MAV_COMPONENT MAV_COMP_ID_ALL = 0 # MAV_COMP_ID_CAMERA = 100 # MAV_COMP_ID_SERVO1 = 140 # MAV_COMP_ID_SERVO2 = 141 # MAV_COMP_ID_SERVO3 = 142 # MAV_COMP_ID_SERVO4 = 143 # MAV_COMP_ID_SERVO5 = 144 # MAV_COMP_ID_SERVO6 = 145 # MAV_COMP_ID_SERVO7 = 146 # MAV_COMP_ID_SERVO8 = 147 # MAV_COMP_ID_SERVO9 = 148 # MAV_COMP_ID_SERVO10 = 149 # MAV_COMP_ID_SERVO11 = 150 # MAV_COMP_ID_SERVO12 = 151 # MAV_COMP_ID_SERVO13 = 152 # MAV_COMP_ID_SERVO14 = 153 # MAV_COMP_ID_MAPPER = 180 # MAV_COMP_ID_MISSIONPLANNER = 190 # MAV_COMP_ID_PATHPLANNER = 195 # MAV_COMP_ID_IMU = 200 # MAV_COMP_ID_IMU_2 = 201 # MAV_COMP_ID_IMU_3 = 202 # MAV_COMP_ID_GPS = 220 # MAV_COMP_ID_UDP_BRIDGE = 240 # MAV_COMP_ID_UART_BRIDGE = 241 # MAV_COMP_ID_SYSTEM_CONTROL = 250 # MAV_COMPONENT_ENUM_END = 251 # # MAV_SYS_STATUS_SENSOR MAV_SYS_STATUS_SENSOR_3D_GYRO = 1 # 0x01 3D gyro MAV_SYS_STATUS_SENSOR_3D_ACCEL = 2 # 0x02 3D accelerometer MAV_SYS_STATUS_SENSOR_3D_MAG = 4 # 0x04 3D magnetometer MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE = 8 # 0x08 absolute pressure MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE = 16 # 0x10 differential pressure MAV_SYS_STATUS_SENSOR_GPS = 32 # 0x20 GPS MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW = 64 # 0x40 optical flow MAV_SYS_STATUS_SENSOR_VISION_POSITION = 128 # 0x80 computer vision position MAV_SYS_STATUS_SENSOR_LASER_POSITION = 256 # 0x100 laser based position MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH = 512 # 0x200 external ground truth (Vicon or Leica) MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL = 1024 # 0x400 3D angular rate control MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION = 2048 # 0x800 attitude stabilization MAV_SYS_STATUS_SENSOR_YAW_POSITION = 4096 # 0x1000 yaw position MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL = 8192 # 0x2000 z/altitude control MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL = 16384 # 0x4000 x/y position control MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS = 32768 # 0x8000 motor outputs / control MAV_SYS_STATUS_SENSOR_RC_RECEIVER = 65536 # 0x10000 rc receiver MAV_SYS_STATUS_SENSOR_3D_GYRO2 = 131072 # 0x20000 2nd 3D gyro MAV_SYS_STATUS_SENSOR_3D_ACCEL2 = 262144 # 0x40000 2nd 3D accelerometer MAV_SYS_STATUS_SENSOR_3D_MAG2 = 524288 # 0x80000 2nd 3D magnetometer MAV_SYS_STATUS_SENSOR_ENUM_END = 524289 # # MAV_FRAME MAV_FRAME_GLOBAL = 0 # Global coordinate frame, WGS84 coordinate system. First value / x: # latitude, second value / y: longitude, third # value / z: positive altitude over mean sea # level (MSL) MAV_FRAME_LOCAL_NED = 1 # Local coordinate frame, Z-up (x: north, y: east, z: down). MAV_FRAME_MISSION = 2 # NOT a coordinate frame, indicates a mission command. MAV_FRAME_GLOBAL_RELATIVE_ALT = 3 # Global coordinate frame, WGS84 coordinate system, relative altitude # over ground with respect to the home # position. First value / x: latitude, second # value / y: longitude, third value / z: # positive altitude with 0 being at the # altitude of the home location. MAV_FRAME_LOCAL_ENU = 4 # Local coordinate frame, Z-down (x: east, y: north, z: up) MAV_FRAME_ENUM_END = 5 # # MAVLINK_DATA_STREAM_TYPE MAVLINK_DATA_STREAM_IMG_JPEG = 1 # MAVLINK_DATA_STREAM_IMG_BMP = 2 # MAVLINK_DATA_STREAM_IMG_RAW8U = 3 # MAVLINK_DATA_STREAM_IMG_RAW32U = 4 # MAVLINK_DATA_STREAM_IMG_PGM = 5 # MAVLINK_DATA_STREAM_IMG_PNG = 6 # MAVLINK_DATA_STREAM_TYPE_ENUM_END = 7 # # MAV_DATA_STREAM MAV_DATA_STREAM_ALL = 0 # Enable all data streams MAV_DATA_STREAM_RAW_SENSORS = 1 # Enable IMU_RAW, GPS_RAW, GPS_STATUS packets. MAV_DATA_STREAM_EXTENDED_STATUS = 2 # Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS MAV_DATA_STREAM_RC_CHANNELS = 3 # Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW MAV_DATA_STREAM_RAW_CONTROLLER = 4 # Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, # NAV_CONTROLLER_OUTPUT. MAV_DATA_STREAM_POSITION = 6 # Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages. MAV_DATA_STREAM_EXTRA1 = 10 # Dependent on the autopilot MAV_DATA_STREAM_EXTRA2 = 11 # Dependent on the autopilot MAV_DATA_STREAM_EXTRA3 = 12 # Dependent on the autopilot MAV_DATA_STREAM_ENUM_END = 13 # # MAV_ROI MAV_ROI_NONE = 0 # No region of interest. MAV_ROI_WPNEXT = 1 # Point toward next MISSION. MAV_ROI_WPINDEX = 2 # Point toward given MISSION. MAV_ROI_LOCATION = 3 # Point toward fixed location. MAV_ROI_TARGET = 4 # Point toward of given id. MAV_ROI_ENUM_END = 5 # # MAV_CMD_ACK MAV_CMD_ACK_OK = 1 # Command / mission item is ok. MAV_CMD_ACK_ERR_FAIL = 2 # Generic error message if none of the other reasons fails or if no # detailed error reporting is implemented. MAV_CMD_ACK_ERR_ACCESS_DENIED = 3 # The system is refusing to accept this command from this source / # communication partner. MAV_CMD_ACK_ERR_NOT_SUPPORTED = 4 # Command or mission item is not supported, other commands would be # accepted. MAV_CMD_ACK_ERR_COORDINATE_FRAME_NOT_SUPPORTED = 5 # The coordinate frame of this command / mission item is not supported. MAV_CMD_ACK_ERR_COORDINATES_OUT_OF_RANGE = 6 # The coordinate frame of this command is ok, but he coordinate values # exceed the safety limits of this system. # This is a generic error, please use the more # specific error messages below if possible. MAV_CMD_ACK_ERR_X_LAT_OUT_OF_RANGE = 7 # The X or latitude value is out of range. MAV_CMD_ACK_ERR_Y_LON_OUT_OF_RANGE = 8 # The Y or longitude value is out of range. MAV_CMD_ACK_ERR_Z_ALT_OUT_OF_RANGE = 9 # The Z or altitude value is out of range. MAV_CMD_ACK_ENUM_END = 10 # # MAV_PARAM_TYPE MAV_PARAM_TYPE_UINT8 = 1 # 8-bit unsigned integer MAV_PARAM_TYPE_INT8 = 2 # 8-bit signed integer MAV_PARAM_TYPE_UINT16 = 3 # 16-bit unsigned integer MAV_PARAM_TYPE_INT16 = 4 # 16-bit signed integer MAV_PARAM_TYPE_UINT32 = 5 # 32-bit unsigned integer MAV_PARAM_TYPE_INT32 = 6 # 32-bit signed integer MAV_PARAM_TYPE_UINT64 = 7 # 64-bit unsigned integer MAV_PARAM_TYPE_INT64 = 8 # 64-bit signed integer MAV_PARAM_TYPE_REAL32 = 9 # 32-bit floating-point MAV_PARAM_TYPE_REAL64 = 10 # 64-bit floating-point MAV_PARAM_TYPE_ENUM_END = 11 # # MAV_RESULT MAV_RESULT_ACCEPTED = 0 # Command ACCEPTED and EXECUTED MAV_RESULT_TEMPORARILY_REJECTED = 1 # Command TEMPORARY REJECTED/DENIED MAV_RESULT_DENIED = 2 # Command PERMANENTLY DENIED MAV_RESULT_UNSUPPORTED = 3 # Command UNKNOWN/UNSUPPORTED MAV_RESULT_FAILED = 4 # Command executed, but failed MAV_RESULT_ENUM_END = 5 # # MAV_MISSION_RESULT MAV_MISSION_ACCEPTED = 0 # mission accepted OK MAV_MISSION_ERROR = 1 # generic error / not accepting mission commands at all right now MAV_MISSION_UNSUPPORTED_FRAME = 2 # coordinate frame is not supported MAV_MISSION_UNSUPPORTED = 3 # command is not supported MAV_MISSION_NO_SPACE = 4 # mission item exceeds storage space MAV_MISSION_INVALID = 5 # one of the parameters has an invalid value MAV_MISSION_INVALID_PARAM1 = 6 # param1 has an invalid value MAV_MISSION_INVALID_PARAM2 = 7 # param2 has an invalid value MAV_MISSION_INVALID_PARAM3 = 8 # param3 has an invalid value MAV_MISSION_INVALID_PARAM4 = 9 # param4 has an invalid value MAV_MISSION_INVALID_PARAM5_X = 10 # x/param5 has an invalid value MAV_MISSION_INVALID_PARAM6_Y = 11 # y/param6 has an invalid value MAV_MISSION_INVALID_PARAM7 = 12 # param7 has an invalid value MAV_MISSION_INVALID_SEQUENCE = 13 # received waypoint out of sequence MAV_MISSION_DENIED = 14 # not accepting any mission commands from this communication partner MAV_MISSION_RESULT_ENUM_END = 15 # # MAV_SEVERITY MAV_SEVERITY_EMERGENCY = 0 # System is unusable. This is a "panic" condition. MAV_SEVERITY_ALERT = 1 # Action should be taken immediately. Indicates error in non-critical # systems. MAV_SEVERITY_CRITICAL = 2 # Action must be taken immediately. Indicates failure in a primary # system. MAV_SEVERITY_ERROR = 3 # Indicates an error in secondary/redundant systems. MAV_SEVERITY_WARNING = 4 # Indicates about a possible future error if this is not resolved within # a given timeframe. Example would be a low # battery warning. MAV_SEVERITY_NOTICE = 5 # An unusual event has occured, though not an error condition. This # should be investigated for the root cause. MAV_SEVERITY_INFO = 6 # Normal operational messages. Useful for logging. No action is required # for these messages. MAV_SEVERITY_DEBUG = 7 # Useful non-operational messages that can assist in debugging. These # should not occur during normal operation. MAV_SEVERITY_ENUM_END = 8 # # MAV_POWER_STATUS MAV_POWER_STATUS_BRICK_VALID = 1 # main brick power supply valid MAV_POWER_STATUS_SERVO_VALID = 2 # main servo power supply valid for FMU MAV_POWER_STATUS_USB_CONNECTED = 4 # USB power is connected MAV_POWER_STATUS_PERIPH_OVERCURRENT = 8 # peripheral supply is in over-current state MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT = 16 # hi-power peripheral supply is in over-current state MAV_POWER_STATUS_CHANGED = 32 # Power status has changed since boot MAV_POWER_STATUS_ENUM_END = 33 # # message IDs MAVLINK_MSG_ID_BAD_DATA = -1 MAVLINK_MSG_ID_SET_CAM_SHUTTER = 151 MAVLINK_MSG_ID_IMAGE_TRIGGERED = 152 MAVLINK_MSG_ID_IMAGE_TRIGGER_CONTROL = 153 MAVLINK_MSG_ID_IMAGE_AVAILABLE = 154 MAVLINK_MSG_ID_SET_POSITION_CONTROL_OFFSET = 160 MAVLINK_MSG_ID_POSITION_CONTROL_SETPOINT = 170 MAVLINK_MSG_ID_MARKER = 171 MAVLINK_MSG_ID_RAW_AUX = 172 MAVLINK_MSG_ID_WATCHDOG_HEARTBEAT = 180 MAVLINK_MSG_ID_WATCHDOG_PROCESS_INFO = 181 MAVLINK_MSG_ID_WATCHDOG_PROCESS_STATUS = 182 MAVLINK_MSG_ID_WATCHDOG_COMMAND = 183 MAVLINK_MSG_ID_PATTERN_DETECTED = 190 MAVLINK_MSG_ID_POINT_OF_INTEREST = 191 MAVLINK_MSG_ID_POINT_OF_INTEREST_CONNECTION = 192 MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE = 193 MAVLINK_MSG_ID_ENCAPSULATED_DATA = 194 MAVLINK_MSG_ID_BRIEF_FEATURE = 195 MAVLINK_MSG_ID_ATTITUDE_CONTROL = 200 MAVLINK_MSG_ID_HEARTBEAT = 0 MAVLINK_MSG_ID_SYS_STATUS = 1 MAVLINK_MSG_ID_SYSTEM_TIME = 2 MAVLINK_MSG_ID_PING = 4 MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL = 5 MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK = 6 MAVLINK_MSG_ID_AUTH_KEY = 7 MAVLINK_MSG_ID_SET_MODE = 11 MAVLINK_MSG_ID_PARAM_REQUEST_READ = 20 MAVLINK_MSG_ID_PARAM_REQUEST_LIST = 21 MAVLINK_MSG_ID_PARAM_VALUE = 22 MAVLINK_MSG_ID_PARAM_SET = 23 MAVLINK_MSG_ID_GPS_RAW_INT = 24 MAVLINK_MSG_ID_GPS_STATUS = 25 MAVLINK_MSG_ID_SCALED_IMU = 26 MAVLINK_MSG_ID_RAW_IMU = 27 MAVLINK_MSG_ID_RAW_PRESSURE = 28 MAVLINK_MSG_ID_SCALED_PRESSURE = 29 MAVLINK_MSG_ID_ATTITUDE = 30 MAVLINK_MSG_ID_ATTITUDE_QUATERNION = 31 MAVLINK_MSG_ID_LOCAL_POSITION_NED = 32 MAVLINK_MSG_ID_GLOBAL_POSITION_INT = 33 MAVLINK_MSG_ID_RC_CHANNELS_SCALED = 34 MAVLINK_MSG_ID_RC_CHANNELS_RAW = 35 MAVLINK_MSG_ID_SERVO_OUTPUT_RAW = 36 MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST = 37 MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST = 38 MAVLINK_MSG_ID_MISSION_ITEM = 39 MAVLINK_MSG_ID_MISSION_REQUEST = 40 MAVLINK_MSG_ID_MISSION_SET_CURRENT = 41 MAVLINK_MSG_ID_MISSION_CURRENT = 42 MAVLINK_MSG_ID_MISSION_REQUEST_LIST = 43 MAVLINK_MSG_ID_MISSION_COUNT = 44 MAVLINK_MSG_ID_MISSION_CLEAR_ALL = 45 MAVLINK_MSG_ID_MISSION_ITEM_REACHED = 46 MAVLINK_MSG_ID_MISSION_ACK = 47 MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN = 48 MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN = 49 MAVLINK_MSG_ID_SET_LOCAL_POSITION_SETPOINT = 50 MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT = 51 MAVLINK_MSG_ID_GLOBAL_POSITION_SETPOINT_INT = 52 MAVLINK_MSG_ID_SET_GLOBAL_POSITION_SETPOINT_INT = 53 MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA = 54 MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA = 55 MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_THRUST = 56 MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_SPEED_THRUST = 57 MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT = 58 MAVLINK_MSG_ID_ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT = 59 MAVLINK_MSG_ID_SET_QUAD_MOTORS_SETPOINT = 60 MAVLINK_MSG_ID_SET_QUAD_SWARM_ROLL_PITCH_YAW_THRUST = 61 MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT = 62 MAVLINK_MSG_ID_SET_QUAD_SWARM_LED_ROLL_PITCH_YAW_THRUST = 63 MAVLINK_MSG_ID_STATE_CORRECTION = 64 MAVLINK_MSG_ID_REQUEST_DATA_STREAM = 66 MAVLINK_MSG_ID_DATA_STREAM = 67 MAVLINK_MSG_ID_MANUAL_CONTROL = 69 MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE = 70 MAVLINK_MSG_ID_VFR_HUD = 74 MAVLINK_MSG_ID_COMMAND_LONG = 76 MAVLINK_MSG_ID_COMMAND_ACK = 77 MAVLINK_MSG_ID_ROLL_PITCH_YAW_RATES_THRUST_SETPOINT = 80 MAVLINK_MSG_ID_MANUAL_SETPOINT = 81 MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET = 89 MAVLINK_MSG_ID_HIL_STATE = 90 MAVLINK_MSG_ID_HIL_CONTROLS = 91 MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW = 92 MAVLINK_MSG_ID_OPTICAL_FLOW = 100 MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE = 101 MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE = 102 MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE = 103 MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE = 104 MAVLINK_MSG_ID_HIGHRES_IMU = 105 MAVLINK_MSG_ID_OMNIDIRECTIONAL_FLOW = 106 MAVLINK_MSG_ID_HIL_SENSOR = 107 MAVLINK_MSG_ID_SIM_STATE = 108 MAVLINK_MSG_ID_RADIO_STATUS = 109 MAVLINK_MSG_ID_FILE_TRANSFER_START = 110 MAVLINK_MSG_ID_FILE_TRANSFER_DIR_LIST = 111 MAVLINK_MSG_ID_FILE_TRANSFER_RES = 112 MAVLINK_MSG_ID_HIL_GPS = 113 MAVLINK_MSG_ID_HIL_OPTICAL_FLOW = 114 MAVLINK_MSG_ID_HIL_STATE_QUATERNION = 115 MAVLINK_MSG_ID_SCALED_IMU2 = 116 MAVLINK_MSG_ID_LOG_REQUEST_LIST = 117 MAVLINK_MSG_ID_LOG_ENTRY = 118 MAVLINK_MSG_ID_LOG_REQUEST_DATA = 119 MAVLINK_MSG_ID_LOG_DATA = 120 MAVLINK_MSG_ID_LOG_ERASE = 121 MAVLINK_MSG_ID_LOG_REQUEST_END = 122 MAVLINK_MSG_ID_GPS_INJECT_DATA = 123 MAVLINK_MSG_ID_GPS2_RAW = 124 MAVLINK_MSG_ID_POWER_STATUS = 125 MAVLINK_MSG_ID_BATTERY_STATUS = 147 MAVLINK_MSG_ID_SETPOINT_8DOF = 148 MAVLINK_MSG_ID_SETPOINT_6DOF = 149 MAVLINK_MSG_ID_MEMORY_VECT = 249 MAVLINK_MSG_ID_DEBUG_VECT = 250 MAVLINK_MSG_ID_NAMED_VALUE_FLOAT = 251 MAVLINK_MSG_ID_NAMED_VALUE_INT = 252 MAVLINK_MSG_ID_STATUSTEXT = 253 MAVLINK_MSG_ID_DEBUG = 254 class MAVLink_set_cam_shutter_message(MAVLink_message): ''' ''' def __init__(self, cam_no, cam_mode, trigger_pin, interval, exposure, gain): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_CAM_SHUTTER, 'SET_CAM_SHUTTER') self._fieldnames = ['cam_no', 'cam_mode', 'trigger_pin', 'interval', 'exposure', 'gain'] self.cam_no = cam_no self.cam_mode = cam_mode self.trigger_pin = trigger_pin self.interval = interval self.exposure = exposure self.gain = gain def pack(self, mav): return MAVLink_message.pack(self, mav, 108, struct.pack('<fHHBBB', self.gain, self.interval, self.exposure, self.cam_no, self.cam_mode, self.trigger_pin)) class MAVLink_image_triggered_message(MAVLink_message): ''' ''' def __init__(self, timestamp, seq, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_IMAGE_TRIGGERED, 'IMAGE_TRIGGERED') self._fieldnames = ['timestamp', 'seq', 'roll', 'pitch', 'yaw', 'local_z', 'lat', 'lon', 'alt', 'ground_x', 'ground_y', 'ground_z'] self.timestamp = timestamp self.seq = seq self.roll = roll self.pitch = pitch self.yaw = yaw self.local_z = local_z self.lat = lat self.lon = lon self.alt = alt self.ground_x = ground_x self.ground_y = ground_y self.ground_z = ground_z def pack(self, mav): return MAVLink_message.pack(self, mav, 86, struct.pack('<QIffffffffff', self.timestamp, self.seq, self.roll, self.pitch, self.yaw, self.local_z, self.lat, self.lon, self.alt, self.ground_x, self.ground_y, self.ground_z)) class MAVLink_image_trigger_control_message(MAVLink_message): ''' ''' def __init__(self, enable): MAVLink_message.__init__(self, MAVLINK_MSG_ID_IMAGE_TRIGGER_CONTROL, 'IMAGE_TRIGGER_CONTROL') self._fieldnames = ['enable'] self.enable = enable def pack(self, mav): return MAVLink_message.pack(self, mav, 95, struct.pack('<B', self.enable)) class MAVLink_image_available_message(MAVLink_message): ''' ''' def __init__(self, cam_id, cam_no, timestamp, valid_until, img_seq, img_buf_index, width, height, depth, channels, key, exposure, gain, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_IMAGE_AVAILABLE, 'IMAGE_AVAILABLE') self._fieldnames = ['cam_id', 'cam_no', 'timestamp', 'valid_until', 'img_seq', 'img_buf_index', 'width', 'height', 'depth', 'channels', 'key', 'exposure', 'gain', 'roll', 'pitch', 'yaw', 'local_z', 'lat', 'lon', 'alt', 'ground_x', 'ground_y', 'ground_z'] self.cam_id = cam_id self.cam_no = cam_no self.timestamp = timestamp self.valid_until = valid_until self.img_seq = img_seq self.img_buf_index = img_buf_index self.width = width self.height = height self.depth = depth self.channels = channels self.key = key self.exposure = exposure self.gain = gain self.roll = roll self.pitch = pitch self.yaw = yaw self.local_z = local_z self.lat = lat self.lon = lon self.alt = alt self.ground_x = ground_x self.ground_y = ground_y self.ground_z = ground_z def pack(self, mav): return MAVLink_message.pack(self, mav, 224, struct.pack('<QQQIIIIfffffffffffHHHBB', self.cam_id, self.timestamp, self.valid_until, self.img_seq, self.img_buf_index, self.key, self.exposure, self.gain, self.roll, self.pitch, self.yaw, self.local_z, self.lat, self.lon, self.alt, self.ground_x, self.ground_y, self.ground_z, self.width, self.height, self.depth, self.cam_no, self.channels)) class MAVLink_set_position_control_offset_message(MAVLink_message): ''' Message sent to the MAV to set a new offset from the currently controlled position ''' def __init__(self, target_system, target_component, x, y, z, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_POSITION_CONTROL_OFFSET, 'SET_POSITION_CONTROL_OFFSET') self._fieldnames = ['target_system', 'target_component', 'x', 'y', 'z', 'yaw'] self.target_system = target_system self.target_component = target_component self.x = x self.y = y self.z = z self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 22, struct.pack('<ffffBB', self.x, self.y, self.z, self.yaw, self.target_system, self.target_component)) class MAVLink_position_control_setpoint_message(MAVLink_message): ''' ''' def __init__(self, id, x, y, z, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_POSITION_CONTROL_SETPOINT, 'POSITION_CONTROL_SETPOINT') self._fieldnames = ['id', 'x', 'y', 'z', 'yaw'] self.id = id self.x = x self.y = y self.z = z self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 28, struct.pack('<ffffH', self.x, self.y, self.z, self.yaw, self.id)) class MAVLink_marker_message(MAVLink_message): ''' ''' def __init__(self, id, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MARKER, 'MARKER') self._fieldnames = ['id', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] self.id = id self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 249, struct.pack('<ffffffH', self.x, self.y, self.z, self.roll, self.pitch, self.yaw, self.id)) class MAVLink_raw_aux_message(MAVLink_message): ''' ''' def __init__(self, adc1, adc2, adc3, adc4, vbat, temp, baro): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RAW_AUX, 'RAW_AUX') self._fieldnames = ['adc1', 'adc2', 'adc3', 'adc4', 'vbat', 'temp', 'baro'] self.adc1 = adc1 self.adc2 = adc2 self.adc3 = adc3 self.adc4 = adc4 self.vbat = vbat self.temp = temp self.baro = baro def pack(self, mav): return MAVLink_message.pack(self, mav, 182, struct.pack('<iHHHHHh', self.baro, self.adc1, self.adc2, self.adc3, self.adc4, self.vbat, self.temp)) class MAVLink_watchdog_heartbeat_message(MAVLink_message): ''' ''' def __init__(self, watchdog_id, process_count): MAVLink_message.__init__(self, MAVLINK_MSG_ID_WATCHDOG_HEARTBEAT, 'WATCHDOG_HEARTBEAT') self._fieldnames = ['watchdog_id', 'process_count'] self.watchdog_id = watchdog_id self.process_count = process_count def pack(self, mav): return MAVLink_message.pack(self, mav, 153, struct.pack('<HH', self.watchdog_id, self.process_count)) class MAVLink_watchdog_process_info_message(MAVLink_message): ''' ''' def __init__(self, watchdog_id, process_id, name, arguments, timeout): MAVLink_message.__init__(self, MAVLINK_MSG_ID_WATCHDOG_PROCESS_INFO, 'WATCHDOG_PROCESS_INFO') self._fieldnames = ['watchdog_id', 'process_id', 'name', 'arguments', 'timeout'] self.watchdog_id = watchdog_id self.process_id = process_id self.name = name self.arguments = arguments self.timeout = timeout def pack(self, mav): return MAVLink_message.pack(self, mav, 16, struct.pack('<iHH100s147s', self.timeout, self.watchdog_id, self.process_id, self.name, self.arguments)) class MAVLink_watchdog_process_status_message(MAVLink_message): ''' ''' def __init__(self, watchdog_id, process_id, state, muted, pid, crashes): MAVLink_message.__init__(self, MAVLINK_MSG_ID_WATCHDOG_PROCESS_STATUS, 'WATCHDOG_PROCESS_STATUS') self._fieldnames = ['watchdog_id', 'process_id', 'state', 'muted', 'pid', 'crashes'] self.watchdog_id = watchdog_id self.process_id = process_id self.state = state self.muted = muted self.pid = pid self.crashes = crashes def pack(self, mav): return MAVLink_message.pack(self, mav, 29, struct.pack('<iHHHBB', self.pid, self.watchdog_id, self.process_id, self.crashes, self.state, self.muted)) class MAVLink_watchdog_command_message(MAVLink_message): ''' ''' def __init__(self, target_system_id, watchdog_id, process_id, command_id): MAVLink_message.__init__(self, MAVLINK_MSG_ID_WATCHDOG_COMMAND, 'WATCHDOG_COMMAND') self._fieldnames = ['target_system_id', 'watchdog_id', 'process_id', 'command_id'] self.target_system_id = target_system_id self.watchdog_id = watchdog_id self.process_id = process_id self.command_id = command_id def pack(self, mav): return MAVLink_message.pack(self, mav, 162, struct.pack('<HHBB', self.watchdog_id, self.process_id, self.target_system_id, self.command_id)) class MAVLink_pattern_detected_message(MAVLink_message): ''' ''' def __init__(self, type, confidence, file, detected): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PATTERN_DETECTED, 'PATTERN_DETECTED') self._fieldnames = ['type', 'confidence', 'file', 'detected'] self.type = type self.confidence = confidence self.file = file self.detected = detected def pack(self, mav): return MAVLink_message.pack(self, mav, 90, struct.pack('<fB100sB', self.confidence, self.type, self.file, self.detected)) class MAVLink_point_of_interest_message(MAVLink_message): ''' Notifies the operator about a point of interest (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. ''' def __init__(self, type, color, coordinate_system, timeout, x, y, z, name): MAVLink_message.__init__(self, MAVLINK_MSG_ID_POINT_OF_INTEREST, 'POINT_OF_INTEREST') self._fieldnames = ['type', 'color', 'coordinate_system', 'timeout', 'x', 'y', 'z', 'name'] self.type = type self.color = color self.coordinate_system = coordinate_system self.timeout = timeout self.x = x self.y = y self.z = z self.name = name def pack(self, mav): return MAVLink_message.pack(self, mav, 95, struct.pack('<fffHBBB26s', self.x, self.y, self.z, self.timeout, self.type, self.color, self.coordinate_system, self.name)) class MAVLink_point_of_interest_connection_message(MAVLink_message): ''' Notifies the operator about the connection of two point of interests (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. ''' def __init__(self, type, color, coordinate_system, timeout, xp1, yp1, zp1, xp2, yp2, zp2, name): MAVLink_message.__init__(self, MAVLINK_MSG_ID_POINT_OF_INTEREST_CONNECTION, 'POINT_OF_INTEREST_CONNECTION') self._fieldnames = ['type', 'color', 'coordinate_system', 'timeout', 'xp1', 'yp1', 'zp1', 'xp2', 'yp2', 'zp2', 'name'] self.type = type self.color = color self.coordinate_system = coordinate_system self.timeout = timeout self.xp1 = xp1 self.yp1 = yp1 self.zp1 = zp1 self.xp2 = xp2 self.yp2 = yp2 self.zp2 = zp2 self.name = name def pack(self, mav): return MAVLink_message.pack(self, mav, 36, struct.pack('<ffffffHBBB26s', self.xp1, self.yp1, self.zp1, self.xp2, self.yp2, self.zp2, self.timeout, self.type, self.color, self.coordinate_system, self.name)) class MAVLink_data_transmission_handshake_message(MAVLink_message): ''' ''' def __init__(self, type, size, width, height, packets, payload, jpg_quality): MAVLink_message.__init__(self, MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE, 'DATA_TRANSMISSION_HANDSHAKE') self._fieldnames = ['type', 'size', 'width', 'height', 'packets', 'payload', 'jpg_quality'] self.type = type self.size = size self.width = width self.height = height self.packets = packets self.payload = payload self.jpg_quality = jpg_quality def pack(self, mav): return MAVLink_message.pack(self, mav, 23, struct.pack('<IHHBBBB', self.size, self.width, self.height, self.type, self.packets, self.payload, self.jpg_quality)) class MAVLink_encapsulated_data_message(MAVLink_message): ''' ''' def __init__(self, seqnr, data): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ENCAPSULATED_DATA, 'ENCAPSULATED_DATA') self._fieldnames = ['seqnr', 'data'] self.seqnr = seqnr self.data = data def pack(self, mav): return MAVLink_message.pack(self, mav, 223, struct.pack('<H253s', self.seqnr, self.data)) class MAVLink_brief_feature_message(MAVLink_message): ''' ''' def __init__(self, x, y, z, orientation_assignment, size, orientation, descriptor, response): MAVLink_message.__init__(self, MAVLINK_MSG_ID_BRIEF_FEATURE, 'BRIEF_FEATURE') self._fieldnames = ['x', 'y', 'z', 'orientation_assignment', 'size', 'orientation', 'descriptor', 'response'] self.x = x self.y = y self.z = z self.orientation_assignment = orientation_assignment self.size = size self.orientation = orientation self.descriptor = descriptor self.response = response def pack(self, mav): return MAVLink_message.pack(self, mav, 88, struct.pack('<ffffHHB32s', self.x, self.y, self.z, self.response, self.size, self.orientation, self.orientation_assignment, self.descriptor)) class MAVLink_attitude_control_message(MAVLink_message): ''' ''' def __init__(self, target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ATTITUDE_CONTROL, 'ATTITUDE_CONTROL') self._fieldnames = ['target', 'roll', 'pitch', 'yaw', 'thrust', 'roll_manual', 'pitch_manual', 'yaw_manual', 'thrust_manual'] self.target = target self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust self.roll_manual = roll_manual self.pitch_manual = pitch_manual self.yaw_manual = yaw_manual self.thrust_manual = thrust_manual def pack(self, mav): return MAVLink_message.pack(self, mav, 254, struct.pack('<ffffBBBBB', self.roll, self.pitch, self.yaw, self.thrust, self.target, self.roll_manual, self.pitch_manual, self.yaw_manual, self.thrust_manual)) class MAVLink_heartbeat_message(MAVLink_message): ''' The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by laying out the user interface based on the autopilot). ''' def __init__(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HEARTBEAT, 'HEARTBEAT') self._fieldnames = ['type', 'autopilot', 'base_mode', 'custom_mode', 'system_status', 'mavlink_version'] self.type = type self.autopilot = autopilot self.base_mode = base_mode self.custom_mode = custom_mode self.system_status = system_status self.mavlink_version = mavlink_version def pack(self, mav): return MAVLink_message.pack(self, mav, 50, struct.pack('<IBBBBB', self.custom_mode, self.type, self.autopilot, self.base_mode, self.system_status, self.mavlink_version)) class MAVLink_sys_status_message(MAVLink_message): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows wether the system is currently active or not and if an emergency occured. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occured it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. ''' def __init__(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SYS_STATUS, 'SYS_STATUS') self._fieldnames = ['onboard_control_sensors_present', 'onboard_control_sensors_enabled', 'onboard_control_sensors_health', 'load', 'voltage_battery', 'current_battery', 'battery_remaining', 'drop_rate_comm', 'errors_comm', 'errors_count1', 'errors_count2', 'errors_count3', 'errors_count4'] self.onboard_control_sensors_present = onboard_control_sensors_present self.onboard_control_sensors_enabled = onboard_control_sensors_enabled self.onboard_control_sensors_health = onboard_control_sensors_health self.load = load self.voltage_battery = voltage_battery self.current_battery = current_battery self.battery_remaining = battery_remaining self.drop_rate_comm = drop_rate_comm self.errors_comm = errors_comm self.errors_count1 = errors_count1 self.errors_count2 = errors_count2 self.errors_count3 = errors_count3 self.errors_count4 = errors_count4 def pack(self, mav): return MAVLink_message.pack(self, mav, 124, struct.pack('<IIIHHhHHHHHHb', self.onboard_control_sensors_present, self.onboard_control_sensors_enabled, self.onboard_control_sensors_health, self.load, self.voltage_battery, self.current_battery, self.drop_rate_comm, self.errors_comm, self.errors_count1, self.errors_count2, self.errors_count3, self.errors_count4, self.battery_remaining)) class MAVLink_system_time_message(MAVLink_message): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. ''' def __init__(self, time_unix_usec, time_boot_ms): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SYSTEM_TIME, 'SYSTEM_TIME') self._fieldnames = ['time_unix_usec', 'time_boot_ms'] self.time_unix_usec = time_unix_usec self.time_boot_ms = time_boot_ms def pack(self, mav): return MAVLink_message.pack(self, mav, 137, struct.pack('<QI', self.time_unix_usec, self.time_boot_ms)) class MAVLink_ping_message(MAVLink_message): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. ''' def __init__(self, time_usec, seq, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PING, 'PING') self._fieldnames = ['time_usec', 'seq', 'target_system', 'target_component'] self.time_usec = time_usec self.seq = seq self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 237, struct.pack('<QIBB', self.time_usec, self.seq, self.target_system, self.target_component)) class MAVLink_change_operator_control_message(MAVLink_message): ''' Request to control this MAV ''' def __init__(self, target_system, control_request, version, passkey): MAVLink_message.__init__(self, MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL, 'CHANGE_OPERATOR_CONTROL') self._fieldnames = ['target_system', 'control_request', 'version', 'passkey'] self.target_system = target_system self.control_request = control_request self.version = version self.passkey = passkey def pack(self, mav): return MAVLink_message.pack(self, mav, 217, struct.pack('<BBB25s', self.target_system, self.control_request, self.version, self.passkey)) class MAVLink_change_operator_control_ack_message(MAVLink_message): ''' Accept / deny control of this MAV ''' def __init__(self, gcs_system_id, control_request, ack): MAVLink_message.__init__(self, MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK, 'CHANGE_OPERATOR_CONTROL_ACK') self._fieldnames = ['gcs_system_id', 'control_request', 'ack'] self.gcs_system_id = gcs_system_id self.control_request = control_request self.ack = ack def pack(self, mav): return MAVLink_message.pack(self, mav, 104, struct.pack('<BBB', self.gcs_system_id, self.control_request, self.ack)) class MAVLink_auth_key_message(MAVLink_message): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. ''' def __init__(self, key): MAVLink_message.__init__(self, MAVLINK_MSG_ID_AUTH_KEY, 'AUTH_KEY') self._fieldnames = ['key'] self.key = key def pack(self, mav): return MAVLink_message.pack(self, mav, 119, struct.pack('<32s', self.key)) class MAVLink_set_mode_message(MAVLink_message): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. ''' def __init__(self, target_system, base_mode, custom_mode): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_MODE, 'SET_MODE') self._fieldnames = ['target_system', 'base_mode', 'custom_mode'] self.target_system = target_system self.base_mode = base_mode self.custom_mode = custom_mode def pack(self, mav): return MAVLink_message.pack(self, mav, 89, struct.pack('<IBB', self.custom_mode, self.target_system, self.base_mode)) class MAVLink_param_request_read_message(MAVLink_message): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also http://qgroundcontrol.org/parameter_interface for a full documentation of QGroundControl and IMU code. ''' def __init__(self, target_system, target_component, param_id, param_index): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PARAM_REQUEST_READ, 'PARAM_REQUEST_READ') self._fieldnames = ['target_system', 'target_component', 'param_id', 'param_index'] self.target_system = target_system self.target_component = target_component self.param_id = param_id self.param_index = param_index def pack(self, mav): return MAVLink_message.pack(self, mav, 214, struct.pack('<hBB16s', self.param_index, self.target_system, self.target_component, self.param_id)) class MAVLink_param_request_list_message(MAVLink_message): ''' Request all parameters of this component. After his request, all parameters are emitted. ''' def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PARAM_REQUEST_LIST, 'PARAM_REQUEST_LIST') self._fieldnames = ['target_system', 'target_component'] self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 159, struct.pack('<BB', self.target_system, self.target_component)) class MAVLink_param_value_message(MAVLink_message): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. ''' def __init__(self, param_id, param_value, param_type, param_count, param_index): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PARAM_VALUE, 'PARAM_VALUE') self._fieldnames = ['param_id', 'param_value', 'param_type', 'param_count', 'param_index'] self.param_id = param_id self.param_value = param_value self.param_type = param_type self.param_count = param_count self.param_index = param_index def pack(self, mav): return MAVLink_message.pack(self, mav, 220, struct.pack('<fHH16sB', self.param_value, self.param_count, self.param_index, self.param_id, self.param_type)) class MAVLink_param_set_message(MAVLink_message): ''' Set a parameter value TEMPORARILY to RAM. It will be reset to default on system reboot. Send the ACTION MAV_ACTION_STORAGE_WRITE to PERMANENTLY write the RAM contents to EEPROM. IMPORTANT: The receiving component should acknowledge the new parameter value by sending a param_value message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. ''' def __init__(self, target_system, target_component, param_id, param_value, param_type): MAVLink_message.__init__(self, MAVLINK_MSG_ID_PARAM_SET, 'PARAM_SET') self._fieldnames = ['target_system', 'target_component', 'param_id', 'param_value', 'param_type'] self.target_system = target_system self.target_component = target_component self.param_id = param_id self.param_value = param_value self.param_type = param_type def pack(self, mav): return MAVLink_message.pack(self, mav, 168, struct.pack('<fBB16sB', self.param_value, self.target_system, self.target_component, self.param_id, self.param_type)) class MAVLink_gps_raw_int_message(MAVLink_message): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right-handed, Z-axis up (GPS frame). ''' def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GPS_RAW_INT, 'GPS_RAW_INT') self._fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'cog', 'satellites_visible'] self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.cog = cog self.satellites_visible = satellites_visible def pack(self, mav): return MAVLink_message.pack(self, mav, 24, struct.pack('<QiiiHHHHBB', self.time_usec, self.lat, self.lon, self.alt, self.eph, self.epv, self.vel, self.cog, self.fix_type, self.satellites_visible)) class MAVLink_gps_status_message(MAVLink_message): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. ''' def __init__(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GPS_STATUS, 'GPS_STATUS') self._fieldnames = ['satellites_visible', 'satellite_prn', 'satellite_used', 'satellite_elevation', 'satellite_azimuth', 'satellite_snr'] self.satellites_visible = satellites_visible self.satellite_prn = satellite_prn self.satellite_used = satellite_used self.satellite_elevation = satellite_elevation self.satellite_azimuth = satellite_azimuth self.satellite_snr = satellite_snr def pack(self, mav): return MAVLink_message.pack(self, mav, 23, struct.pack('<B20s20s20s20s20s', self.satellites_visible, self.satellite_prn, self.satellite_used, self.satellite_elevation, self.satellite_azimuth, self.satellite_snr)) class MAVLink_scaled_imu_message(MAVLink_message): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units ''' def __init__(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SCALED_IMU, 'SCALED_IMU') self._fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag'] self.time_boot_ms = time_boot_ms self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag def pack(self, mav): return MAVLink_message.pack(self, mav, 170, struct.pack('<Ihhhhhhhhh', self.time_boot_ms, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag)) class MAVLink_raw_imu_message(MAVLink_message): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. ''' def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RAW_IMU, 'RAW_IMU') self._fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag'] self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag def pack(self, mav): return MAVLink_message.pack(self, mav, 144, struct.pack('<Qhhhhhhhhh', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag)) class MAVLink_raw_pressure_message(MAVLink_message): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. ''' def __init__(self, time_usec, press_abs, press_diff1, press_diff2, temperature): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RAW_PRESSURE, 'RAW_PRESSURE') self._fieldnames = ['time_usec', 'press_abs', 'press_diff1', 'press_diff2', 'temperature'] self.time_usec = time_usec self.press_abs = press_abs self.press_diff1 = press_diff1 self.press_diff2 = press_diff2 self.temperature = temperature def pack(self, mav): return MAVLink_message.pack(self, mav, 67, struct.pack('<Qhhhh', self.time_usec, self.press_abs, self.press_diff1, self.press_diff2, self.temperature)) class MAVLink_scaled_pressure_message(MAVLink_message): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. ''' def __init__(self, time_boot_ms, press_abs, press_diff, temperature): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SCALED_PRESSURE, 'SCALED_PRESSURE') self._fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] self.time_boot_ms = time_boot_ms self.press_abs = press_abs self.press_diff = press_diff self.temperature = temperature def pack(self, mav): return MAVLink_message.pack(self, mav, 115, struct.pack('<Iffh', self.time_boot_ms, self.press_abs, self.press_diff, self.temperature)) class MAVLink_attitude_message(MAVLink_message): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). ''' def __init__(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ATTITUDE, 'ATTITUDE') self._fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed'] self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed def pack(self, mav): return MAVLink_message.pack(self, mav, 39, struct.pack('<Iffffff', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.rollspeed, self.pitchspeed, self.yawspeed)) class MAVLink_attitude_quaternion_message(MAVLink_message): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. ''' def __init__(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ATTITUDE_QUATERNION, 'ATTITUDE_QUATERNION') self._fieldnames = ['time_boot_ms', 'q1', 'q2', 'q3', 'q4', 'rollspeed', 'pitchspeed', 'yawspeed'] self.time_boot_ms = time_boot_ms self.q1 = q1 self.q2 = q2 self.q3 = q3 self.q4 = q4 self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed def pack(self, mav): return MAVLink_message.pack(self, mav, 246, struct.pack('<Ifffffff', self.time_boot_ms, self.q1, self.q2, self.q3, self.q4, self.rollspeed, self.pitchspeed, self.yawspeed)) class MAVLink_local_position_ned_message(MAVLink_message): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) ''' def __init__(self, time_boot_ms, x, y, z, vx, vy, vz): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOCAL_POSITION_NED, 'LOCAL_POSITION_NED') self._fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'vx', 'vy', 'vz'] self.time_boot_ms = time_boot_ms self.x = x self.y = y self.z = z self.vx = vx self.vy = vy self.vz = vz def pack(self, mav): return MAVLink_message.pack(self, mav, 185, struct.pack('<Iffffff', self.time_boot_ms, self.x, self.y, self.z, self.vx, self.vy, self.vz)) class MAVLink_global_position_int_message(MAVLink_message): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. ''' def __init__(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GLOBAL_POSITION_INT, 'GLOBAL_POSITION_INT') self._fieldnames = ['time_boot_ms', 'lat', 'lon', 'alt', 'relative_alt', 'vx', 'vy', 'vz', 'hdg'] self.time_boot_ms = time_boot_ms self.lat = lat self.lon = lon self.alt = alt self.relative_alt = relative_alt self.vx = vx self.vy = vy self.vz = vz self.hdg = hdg def pack(self, mav): return MAVLink_message.pack(self, mav, 104, struct.pack('<IiiiihhhH', self.time_boot_ms, self.lat, self.lon, self.alt, self.relative_alt, self.vx, self.vy, self.vz, self.hdg)) class MAVLink_rc_channels_scaled_message(MAVLink_message): ''' The scaled values of the RC channels received. (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. ''' def __init__(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RC_CHANNELS_SCALED, 'RC_CHANNELS_SCALED') self._fieldnames = ['time_boot_ms', 'port', 'chan1_scaled', 'chan2_scaled', 'chan3_scaled', 'chan4_scaled', 'chan5_scaled', 'chan6_scaled', 'chan7_scaled', 'chan8_scaled', 'rssi'] self.time_boot_ms = time_boot_ms self.port = port self.chan1_scaled = chan1_scaled self.chan2_scaled = chan2_scaled self.chan3_scaled = chan3_scaled self.chan4_scaled = chan4_scaled self.chan5_scaled = chan5_scaled self.chan6_scaled = chan6_scaled self.chan7_scaled = chan7_scaled self.chan8_scaled = chan8_scaled self.rssi = rssi def pack(self, mav): return MAVLink_message.pack(self, mav, 237, struct.pack('<IhhhhhhhhBB', self.time_boot_ms, self.chan1_scaled, self.chan2_scaled, self.chan3_scaled, self.chan4_scaled, self.chan5_scaled, self.chan6_scaled, self.chan7_scaled, self.chan8_scaled, self.port, self.rssi)) class MAVLink_rc_channels_raw_message(MAVLink_message): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. ''' def __init__(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RC_CHANNELS_RAW, 'RC_CHANNELS_RAW') self._fieldnames = ['time_boot_ms', 'port', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'rssi'] self.time_boot_ms = time_boot_ms self.port = port self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.rssi = rssi def pack(self, mav): return MAVLink_message.pack(self, mav, 244, struct.pack('<IHHHHHHHHBB', self.time_boot_ms, self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.port, self.rssi)) class MAVLink_servo_output_raw_message(MAVLink_message): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. ''' def __init__(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SERVO_OUTPUT_RAW, 'SERVO_OUTPUT_RAW') self._fieldnames = ['time_usec', 'port', 'servo1_raw', 'servo2_raw', 'servo3_raw', 'servo4_raw', 'servo5_raw', 'servo6_raw', 'servo7_raw', 'servo8_raw'] self.time_usec = time_usec self.port = port self.servo1_raw = servo1_raw self.servo2_raw = servo2_raw self.servo3_raw = servo3_raw self.servo4_raw = servo4_raw self.servo5_raw = servo5_raw self.servo6_raw = servo6_raw self.servo7_raw = servo7_raw self.servo8_raw = servo8_raw def pack(self, mav): return MAVLink_message.pack(self, mav, 222, struct.pack('<IHHHHHHHHB', self.time_usec, self.servo1_raw, self.servo2_raw, self.servo3_raw, self.servo4_raw, self.servo5_raw, self.servo6_raw, self.servo7_raw, self.servo8_raw, self.port)) class MAVLink_mission_request_partial_list_message(MAVLink_message): ''' Request a partial list of mission items from the system/component. http://qgroundcontrol.org/mavlink/waypoint_protocol. If start and end index are the same, just send one waypoint. ''' def __init__(self, target_system, target_component, start_index, end_index): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST, 'MISSION_REQUEST_PARTIAL_LIST') self._fieldnames = ['target_system', 'target_component', 'start_index', 'end_index'] self.target_system = target_system self.target_component = target_component self.start_index = start_index self.end_index = end_index def pack(self, mav): return MAVLink_message.pack(self, mav, 212, struct.pack('<hhBB', self.start_index, self.end_index, self.target_system, self.target_component)) class MAVLink_mission_write_partial_list_message(MAVLink_message): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! ''' def __init__(self, target_system, target_component, start_index, end_index): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST, 'MISSION_WRITE_PARTIAL_LIST') self._fieldnames = ['target_system', 'target_component', 'start_index', 'end_index'] self.target_system = target_system self.target_component = target_component self.start_index = start_index self.end_index = end_index def pack(self, mav): return MAVLink_message.pack(self, mav, 9, struct.pack('<hhBB', self.start_index, self.end_index, self.target_system, self.target_component)) class MAVLink_mission_item_message(MAVLink_message): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also http://qgroundcontrol.org/mavlink/waypoint_protocol. ''' def __init__(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_ITEM, 'MISSION_ITEM') self._fieldnames = ['target_system', 'target_component', 'seq', 'frame', 'command', 'current', 'autocontinue', 'param1', 'param2', 'param3', 'param4', 'x', 'y', 'z'] self.target_system = target_system self.target_component = target_component self.seq = seq self.frame = frame self.command = command self.current = current self.autocontinue = autocontinue self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.x = x self.y = y self.z = z def pack(self, mav): return MAVLink_message.pack(self, mav, 254, struct.pack('<fffffffHHBBBBB', self.param1, self.param2, self.param3, self.param4, self.x, self.y, self.z, self.seq, self.command, self.target_system, self.target_component, self.frame, self.current, self.autocontinue)) class MAVLink_mission_request_message(MAVLink_message): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. http://qgroundcontrol.org/mavlink/waypoint_protocol ''' def __init__(self, target_system, target_component, seq): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_REQUEST, 'MISSION_REQUEST') self._fieldnames = ['target_system', 'target_component', 'seq'] self.target_system = target_system self.target_component = target_component self.seq = seq def pack(self, mav): return MAVLink_message.pack(self, mav, 230, struct.pack('<HBB', self.seq, self.target_system, self.target_component)) class MAVLink_mission_set_current_message(MAVLink_message): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in- between). ''' def __init__(self, target_system, target_component, seq): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_SET_CURRENT, 'MISSION_SET_CURRENT') self._fieldnames = ['target_system', 'target_component', 'seq'] self.target_system = target_system self.target_component = target_component self.seq = seq def pack(self, mav): return MAVLink_message.pack(self, mav, 28, struct.pack('<HBB', self.seq, self.target_system, self.target_component)) class MAVLink_mission_current_message(MAVLink_message): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. ''' def __init__(self, seq): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_CURRENT, 'MISSION_CURRENT') self._fieldnames = ['seq'] self.seq = seq def pack(self, mav): return MAVLink_message.pack(self, mav, 28, struct.pack('<H', self.seq)) class MAVLink_mission_request_list_message(MAVLink_message): ''' Request the overall list of mission items from the system/component. ''' def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_REQUEST_LIST, 'MISSION_REQUEST_LIST') self._fieldnames = ['target_system', 'target_component'] self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 132, struct.pack('<BB', self.target_system, self.target_component)) class MAVLink_mission_count_message(MAVLink_message): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of MISSIONs. ''' def __init__(self, target_system, target_component, count): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_COUNT, 'MISSION_COUNT') self._fieldnames = ['target_system', 'target_component', 'count'] self.target_system = target_system self.target_component = target_component self.count = count def pack(self, mav): return MAVLink_message.pack(self, mav, 221, struct.pack('<HBB', self.count, self.target_system, self.target_component)) class MAVLink_mission_clear_all_message(MAVLink_message): ''' Delete all mission items at once. ''' def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_CLEAR_ALL, 'MISSION_CLEAR_ALL') self._fieldnames = ['target_system', 'target_component'] self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 232, struct.pack('<BB', self.target_system, self.target_component)) class MAVLink_mission_item_reached_message(MAVLink_message): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next MISSION. ''' def __init__(self, seq): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_ITEM_REACHED, 'MISSION_ITEM_REACHED') self._fieldnames = ['seq'] self.seq = seq def pack(self, mav): return MAVLink_message.pack(self, mav, 11, struct.pack('<H', self.seq)) class MAVLink_mission_ack_message(MAVLink_message): ''' Ack message during MISSION handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). ''' def __init__(self, target_system, target_component, type): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_ACK, 'MISSION_ACK') self._fieldnames = ['target_system', 'target_component', 'type'] self.target_system = target_system self.target_component = target_component self.type = type def pack(self, mav): return MAVLink_message.pack(self, mav, 153, struct.pack('<BBB', self.target_system, self.target_component, self.type)) class MAVLink_set_gps_global_origin_message(MAVLink_message): ''' As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor. ''' def __init__(self, target_system, latitude, longitude, altitude): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN, 'SET_GPS_GLOBAL_ORIGIN') self._fieldnames = ['target_system', 'latitude', 'longitude', 'altitude'] self.target_system = target_system self.latitude = latitude self.longitude = longitude self.altitude = altitude def pack(self, mav): return MAVLink_message.pack(self, mav, 41, struct.pack('<iiiB', self.latitude, self.longitude, self.altitude, self.target_system)) class MAVLink_gps_global_origin_message(MAVLink_message): ''' Once the MAV sets a new GPS-Local correspondence, this message announces the origin (0,0,0) position ''' def __init__(self, latitude, longitude, altitude): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN, 'GPS_GLOBAL_ORIGIN') self._fieldnames = ['latitude', 'longitude', 'altitude'] self.latitude = latitude self.longitude = longitude self.altitude = altitude def pack(self, mav): return MAVLink_message.pack(self, mav, 39, struct.pack('<iii', self.latitude, self.longitude, self.altitude)) class MAVLink_set_local_position_setpoint_message(MAVLink_message): ''' Set the setpoint for a local position controller. This is the position in local coordinates the MAV should fly to. This message is sent by the path/MISSION planner to the onboard position controller. As some MAVs have a degree of freedom in yaw (e.g. all helicopters/quadrotors), the desired yaw angle is part of the message. ''' def __init__(self, target_system, target_component, coordinate_frame, x, y, z, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_LOCAL_POSITION_SETPOINT, 'SET_LOCAL_POSITION_SETPOINT') self._fieldnames = ['target_system', 'target_component', 'coordinate_frame', 'x', 'y', 'z', 'yaw'] self.target_system = target_system self.target_component = target_component self.coordinate_frame = coordinate_frame self.x = x self.y = y self.z = z self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 214, struct.pack('<ffffBBB', self.x, self.y, self.z, self.yaw, self.target_system, self.target_component, self.coordinate_frame)) class MAVLink_local_position_setpoint_message(MAVLink_message): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. ''' def __init__(self, coordinate_frame, x, y, z, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT, 'LOCAL_POSITION_SETPOINT') self._fieldnames = ['coordinate_frame', 'x', 'y', 'z', 'yaw'] self.coordinate_frame = coordinate_frame self.x = x self.y = y self.z = z self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 223, struct.pack('<ffffB', self.x, self.y, self.z, self.yaw, self.coordinate_frame)) class MAVLink_global_position_setpoint_int_message(MAVLink_message): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. ''' def __init__(self, coordinate_frame, latitude, longitude, altitude, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GLOBAL_POSITION_SETPOINT_INT, 'GLOBAL_POSITION_SETPOINT_INT') self._fieldnames = ['coordinate_frame', 'latitude', 'longitude', 'altitude', 'yaw'] self.coordinate_frame = coordinate_frame self.latitude = latitude self.longitude = longitude self.altitude = altitude self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 141, struct.pack('<iiihB', self.latitude, self.longitude, self.altitude, self.yaw, self.coordinate_frame)) class MAVLink_set_global_position_setpoint_int_message(MAVLink_message): ''' Set the current global position setpoint. ''' def __init__(self, coordinate_frame, latitude, longitude, altitude, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_GLOBAL_POSITION_SETPOINT_INT, 'SET_GLOBAL_POSITION_SETPOINT_INT') self._fieldnames = ['coordinate_frame', 'latitude', 'longitude', 'altitude', 'yaw'] self.coordinate_frame = coordinate_frame self.latitude = latitude self.longitude = longitude self.altitude = altitude self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 33, struct.pack('<iiihB', self.latitude, self.longitude, self.altitude, self.yaw, self.coordinate_frame)) class MAVLink_safety_set_allowed_area_message(MAVLink_message): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/MISSIONs to accept and which to reject. Safety areas are often enforced by national or competition regulations. ''' def __init__(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA, 'SAFETY_SET_ALLOWED_AREA') self._fieldnames = ['target_system', 'target_component', 'frame', 'p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z'] self.target_system = target_system self.target_component = target_component self.frame = frame self.p1x = p1x self.p1y = p1y self.p1z = p1z self.p2x = p2x self.p2y = p2y self.p2z = p2z def pack(self, mav): return MAVLink_message.pack(self, mav, 15, struct.pack('<ffffffBBB', self.p1x, self.p1y, self.p1z, self.p2x, self.p2y, self.p2z, self.target_system, self.target_component, self.frame)) class MAVLink_safety_allowed_area_message(MAVLink_message): ''' Read out the safety zone the MAV currently assumes. ''' def __init__(self, frame, p1x, p1y, p1z, p2x, p2y, p2z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA, 'SAFETY_ALLOWED_AREA') self._fieldnames = ['frame', 'p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z'] self.frame = frame self.p1x = p1x self.p1y = p1y self.p1z = p1z self.p2x = p2x self.p2y = p2y self.p2z = p2z def pack(self, mav): return MAVLink_message.pack(self, mav, 3, struct.pack('<ffffffB', self.p1x, self.p1y, self.p1z, self.p2x, self.p2y, self.p2z, self.frame)) class MAVLink_set_roll_pitch_yaw_thrust_message(MAVLink_message): ''' Set roll, pitch and yaw. ''' def __init__(self, target_system, target_component, roll, pitch, yaw, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_THRUST, 'SET_ROLL_PITCH_YAW_THRUST') self._fieldnames = ['target_system', 'target_component', 'roll', 'pitch', 'yaw', 'thrust'] self.target_system = target_system self.target_component = target_component self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 100, struct.pack('<ffffBB', self.roll, self.pitch, self.yaw, self.thrust, self.target_system, self.target_component)) class MAVLink_set_roll_pitch_yaw_speed_thrust_message(MAVLink_message): ''' Set roll, pitch and yaw. ''' def __init__(self, target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_SPEED_THRUST, 'SET_ROLL_PITCH_YAW_SPEED_THRUST') self._fieldnames = ['target_system', 'target_component', 'roll_speed', 'pitch_speed', 'yaw_speed', 'thrust'] self.target_system = target_system self.target_component = target_component self.roll_speed = roll_speed self.pitch_speed = pitch_speed self.yaw_speed = yaw_speed self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 24, struct.pack('<ffffBB', self.roll_speed, self.pitch_speed, self.yaw_speed, self.thrust, self.target_system, self.target_component)) class MAVLink_roll_pitch_yaw_thrust_setpoint_message(MAVLink_message): ''' Setpoint in roll, pitch, yaw currently active on the system. ''' def __init__(self, time_boot_ms, roll, pitch, yaw, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT, 'ROLL_PITCH_YAW_THRUST_SETPOINT') self._fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'thrust'] self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 239, struct.pack('<Iffff', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.thrust)) class MAVLink_roll_pitch_yaw_speed_thrust_setpoint_message(MAVLink_message): ''' Setpoint in rollspeed, pitchspeed, yawspeed currently active on the system. ''' def __init__(self, time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT, 'ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT') self._fieldnames = ['time_boot_ms', 'roll_speed', 'pitch_speed', 'yaw_speed', 'thrust'] self.time_boot_ms = time_boot_ms self.roll_speed = roll_speed self.pitch_speed = pitch_speed self.yaw_speed = yaw_speed self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 238, struct.pack('<Iffff', self.time_boot_ms, self.roll_speed, self.pitch_speed, self.yaw_speed, self.thrust)) class MAVLink_set_quad_motors_setpoint_message(MAVLink_message): ''' Setpoint in the four motor speeds ''' def __init__(self, target_system, motor_front_nw, motor_right_ne, motor_back_se, motor_left_sw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_QUAD_MOTORS_SETPOINT, 'SET_QUAD_MOTORS_SETPOINT') self._fieldnames = ['target_system', 'motor_front_nw', 'motor_right_ne', 'motor_back_se', 'motor_left_sw'] self.target_system = target_system self.motor_front_nw = motor_front_nw self.motor_right_ne = motor_right_ne self.motor_back_se = motor_back_se self.motor_left_sw = motor_left_sw def pack(self, mav): return MAVLink_message.pack(self, mav, 30, struct.pack('<HHHHB', self.motor_front_nw, self.motor_right_ne, self.motor_back_se, self.motor_left_sw, self.target_system)) class MAVLink_set_quad_swarm_roll_pitch_yaw_thrust_message(MAVLink_message): ''' Setpoint for up to four quadrotors in a group / wing ''' def __init__(self, group, mode, roll, pitch, yaw, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_QUAD_SWARM_ROLL_PITCH_YAW_THRUST, 'SET_QUAD_SWARM_ROLL_PITCH_YAW_THRUST') self._fieldnames = ['group', 'mode', 'roll', 'pitch', 'yaw', 'thrust'] self.group = group self.mode = mode self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 240, struct.pack('<4h4h4h4HBB', self.roll, self.pitch, self.yaw, self.thrust, self.group, self.mode)) class MAVLink_nav_controller_output_message(MAVLink_message): ''' Outputs of the APM navigation controller. The primary use of this message is to check the response and signs of the controller before actual flight and to assist with tuning controller parameters. ''' def __init__(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error): MAVLink_message.__init__(self, MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT, 'NAV_CONTROLLER_OUTPUT') self._fieldnames = ['nav_roll', 'nav_pitch', 'nav_bearing', 'target_bearing', 'wp_dist', 'alt_error', 'aspd_error', 'xtrack_error'] self.nav_roll = nav_roll self.nav_pitch = nav_pitch self.nav_bearing = nav_bearing self.target_bearing = target_bearing self.wp_dist = wp_dist self.alt_error = alt_error self.aspd_error = aspd_error self.xtrack_error = xtrack_error def pack(self, mav): return MAVLink_message.pack(self, mav, 183, struct.pack('<fffffhhH', self.nav_roll, self.nav_pitch, self.alt_error, self.aspd_error, self.xtrack_error, self.nav_bearing, self.target_bearing, self.wp_dist)) class MAVLink_set_quad_swarm_led_roll_pitch_yaw_thrust_message(MAVLink_message): ''' Setpoint for up to four quadrotors in a group / wing ''' def __init__(self, group, mode, led_red, led_blue, led_green, roll, pitch, yaw, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SET_QUAD_SWARM_LED_ROLL_PITCH_YAW_THRUST, 'SET_QUAD_SWARM_LED_ROLL_PITCH_YAW_THRUST') self._fieldnames = ['group', 'mode', 'led_red', 'led_blue', 'led_green', 'roll', 'pitch', 'yaw', 'thrust'] self.group = group self.mode = mode self.led_red = led_red self.led_blue = led_blue self.led_green = led_green self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 130, struct.pack('<4h4h4h4HBB4s4s4s', self.roll, self.pitch, self.yaw, self.thrust, self.group, self.mode, self.led_red, self.led_blue, self.led_green)) class MAVLink_state_correction_message(MAVLink_message): ''' Corrects the systems state by adding an error correction term to the position and velocity, and by rotating the attitude by a correction angle. ''' def __init__(self, xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr): MAVLink_message.__init__(self, MAVLINK_MSG_ID_STATE_CORRECTION, 'STATE_CORRECTION') self._fieldnames = ['xErr', 'yErr', 'zErr', 'rollErr', 'pitchErr', 'yawErr', 'vxErr', 'vyErr', 'vzErr'] self.xErr = xErr self.yErr = yErr self.zErr = zErr self.rollErr = rollErr self.pitchErr = pitchErr self.yawErr = yawErr self.vxErr = vxErr self.vyErr = vyErr self.vzErr = vzErr def pack(self, mav): return MAVLink_message.pack(self, mav, 130, struct.pack('<fffffffff', self.xErr, self.yErr, self.zErr, self.rollErr, self.pitchErr, self.yawErr, self.vxErr, self.vyErr, self.vzErr)) class MAVLink_request_data_stream_message(MAVLink_message): ''' ''' def __init__(self, target_system, target_component, req_stream_id, req_message_rate, start_stop): MAVLink_message.__init__(self, MAVLINK_MSG_ID_REQUEST_DATA_STREAM, 'REQUEST_DATA_STREAM') self._fieldnames = ['target_system', 'target_component', 'req_stream_id', 'req_message_rate', 'start_stop'] self.target_system = target_system self.target_component = target_component self.req_stream_id = req_stream_id self.req_message_rate = req_message_rate self.start_stop = start_stop def pack(self, mav): return MAVLink_message.pack(self, mav, 148, struct.pack('<HBBBB', self.req_message_rate, self.target_system, self.target_component, self.req_stream_id, self.start_stop)) class MAVLink_data_stream_message(MAVLink_message): ''' ''' def __init__(self, stream_id, message_rate, on_off): MAVLink_message.__init__(self, MAVLINK_MSG_ID_DATA_STREAM, 'DATA_STREAM') self._fieldnames = ['stream_id', 'message_rate', 'on_off'] self.stream_id = stream_id self.message_rate = message_rate self.on_off = on_off def pack(self, mav): return MAVLink_message.pack(self, mav, 21, struct.pack('<HBB', self.message_rate, self.stream_id, self.on_off)) class MAVLink_manual_control_message(MAVLink_message): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their ''' def __init__(self, target, x, y, z, r, buttons): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MANUAL_CONTROL, 'MANUAL_CONTROL') self._fieldnames = ['target', 'x', 'y', 'z', 'r', 'buttons'] self.target = target self.x = x self.y = y self.z = z self.r = r self.buttons = buttons def pack(self, mav): return MAVLink_message.pack(self, mav, 243, struct.pack('<hhhhHB', self.x, self.y, self.z, self.r, self.buttons, self.target)) class MAVLink_rc_channels_override_message(MAVLink_message): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. ''' def __init__(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE, 'RC_CHANNELS_OVERRIDE') self._fieldnames = ['target_system', 'target_component', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw'] self.target_system = target_system self.target_component = target_component self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw def pack(self, mav): return MAVLink_message.pack(self, mav, 124, struct.pack('<HHHHHHHHBB', self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.target_system, self.target_component)) class MAVLink_vfr_hud_message(MAVLink_message): ''' Metrics typically displayed on a HUD for fixed wing aircraft ''' def __init__(self, airspeed, groundspeed, heading, throttle, alt, climb): MAVLink_message.__init__(self, MAVLINK_MSG_ID_VFR_HUD, 'VFR_HUD') self._fieldnames = ['airspeed', 'groundspeed', 'heading', 'throttle', 'alt', 'climb'] self.airspeed = airspeed self.groundspeed = groundspeed self.heading = heading self.throttle = throttle self.alt = alt self.climb = climb def pack(self, mav): return MAVLink_message.pack(self, mav, 20, struct.pack('<ffffhH', self.airspeed, self.groundspeed, self.alt, self.climb, self.heading, self.throttle)) class MAVLink_command_long_message(MAVLink_message): ''' Send a command with up to seven parameters to the MAV ''' def __init__(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7): MAVLink_message.__init__(self, MAVLINK_MSG_ID_COMMAND_LONG, 'COMMAND_LONG') self._fieldnames = ['target_system', 'target_component', 'command', 'confirmation', 'param1', 'param2', 'param3', 'param4', 'param5', 'param6', 'param7'] self.target_system = target_system self.target_component = target_component self.command = command self.confirmation = confirmation self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.param5 = param5 self.param6 = param6 self.param7 = param7 def pack(self, mav): return MAVLink_message.pack(self, mav, 152, struct.pack('<fffffffHBBB', self.param1, self.param2, self.param3, self.param4, self.param5, self.param6, self.param7, self.command, self.target_system, self.target_component, self.confirmation)) class MAVLink_command_ack_message(MAVLink_message): ''' Report status of a command. Includes feedback wether the command was executed. ''' def __init__(self, command, result): MAVLink_message.__init__(self, MAVLINK_MSG_ID_COMMAND_ACK, 'COMMAND_ACK') self._fieldnames = ['command', 'result'] self.command = command self.result = result def pack(self, mav): return MAVLink_message.pack(self, mav, 143, struct.pack('<HB', self.command, self.result)) class MAVLink_roll_pitch_yaw_rates_thrust_setpoint_message(MAVLink_message): ''' Setpoint in roll, pitch, yaw rates and thrust currently active on the system. ''' def __init__(self, time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust): MAVLink_message.__init__(self, MAVLINK_MSG_ID_ROLL_PITCH_YAW_RATES_THRUST_SETPOINT, 'ROLL_PITCH_YAW_RATES_THRUST_SETPOINT') self._fieldnames = ['time_boot_ms', 'roll_rate', 'pitch_rate', 'yaw_rate', 'thrust'] self.time_boot_ms = time_boot_ms self.roll_rate = roll_rate self.pitch_rate = pitch_rate self.yaw_rate = yaw_rate self.thrust = thrust def pack(self, mav): return MAVLink_message.pack(self, mav, 127, struct.pack('<Iffff', self.time_boot_ms, self.roll_rate, self.pitch_rate, self.yaw_rate, self.thrust)) class MAVLink_manual_setpoint_message(MAVLink_message): ''' Setpoint in roll, pitch, yaw and thrust from the operator ''' def __init__(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MANUAL_SETPOINT, 'MANUAL_SETPOINT') self._fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'thrust', 'mode_switch', 'manual_override_switch'] self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust self.mode_switch = mode_switch self.manual_override_switch = manual_override_switch def pack(self, mav): return MAVLink_message.pack(self, mav, 106, struct.pack('<IffffBB', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.thrust, self.mode_switch, self.manual_override_switch)) class MAVLink_local_position_ned_system_global_offset_message(MAVLink_message): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) ''' def __init__(self, time_boot_ms, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET, 'LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET') self._fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] self.time_boot_ms = time_boot_ms self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 231, struct.pack('<Iffffff', self.time_boot_ms, self.x, self.y, self.z, self.roll, self.pitch, self.yaw)) class MAVLink_hil_state_message(MAVLink_message): ''' DEPRECATED PACKET! Suffers from missing airspeed fields and singularities due to Euler angles. Please use HIL_STATE_QUATERNION instead. Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. ''' def __init__(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_STATE, 'HIL_STATE') self._fieldnames = ['time_usec', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'xacc', 'yacc', 'zacc'] self.time_usec = time_usec self.roll = roll self.pitch = pitch self.yaw = yaw self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.lat = lat self.lon = lon self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.xacc = xacc self.yacc = yacc self.zacc = zacc def pack(self, mav): return MAVLink_message.pack(self, mav, 183, struct.pack('<Qffffffiiihhhhhh', self.time_usec, self.roll, self.pitch, self.yaw, self.rollspeed, self.pitchspeed, self.yawspeed, self.lat, self.lon, self.alt, self.vx, self.vy, self.vz, self.xacc, self.yacc, self.zacc)) class MAVLink_hil_controls_message(MAVLink_message): ''' Sent from autopilot to simulation. Hardware in the loop control outputs ''' def __init__(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_CONTROLS, 'HIL_CONTROLS') self._fieldnames = ['time_usec', 'roll_ailerons', 'pitch_elevator', 'yaw_rudder', 'throttle', 'aux1', 'aux2', 'aux3', 'aux4', 'mode', 'nav_mode'] self.time_usec = time_usec self.roll_ailerons = roll_ailerons self.pitch_elevator = pitch_elevator self.yaw_rudder = yaw_rudder self.throttle = throttle self.aux1 = aux1 self.aux2 = aux2 self.aux3 = aux3 self.aux4 = aux4 self.mode = mode self.nav_mode = nav_mode def pack(self, mav): return MAVLink_message.pack(self, mav, 63, struct.pack('<QffffffffBB', self.time_usec, self.roll_ailerons, self.pitch_elevator, self.yaw_rudder, self.throttle, self.aux1, self.aux2, self.aux3, self.aux4, self.mode, self.nav_mode)) class MAVLink_hil_rc_inputs_raw_message(MAVLink_message): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. ''' def __init__(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW, 'HIL_RC_INPUTS_RAW') self._fieldnames = ['time_usec', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'rssi'] self.time_usec = time_usec self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.chan9_raw = chan9_raw self.chan10_raw = chan10_raw self.chan11_raw = chan11_raw self.chan12_raw = chan12_raw self.rssi = rssi def pack(self, mav): return MAVLink_message.pack(self, mav, 54, struct.pack('<QHHHHHHHHHHHHB', self.time_usec, self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.chan9_raw, self.chan10_raw, self.chan11_raw, self.chan12_raw, self.rssi)) class MAVLink_optical_flow_message(MAVLink_message): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) ''' def __init__(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): MAVLink_message.__init__(self, MAVLINK_MSG_ID_OPTICAL_FLOW, 'OPTICAL_FLOW') self._fieldnames = ['time_usec', 'sensor_id', 'flow_x', 'flow_y', 'flow_comp_m_x', 'flow_comp_m_y', 'quality', 'ground_distance'] self.time_usec = time_usec self.sensor_id = sensor_id self.flow_x = flow_x self.flow_y = flow_y self.flow_comp_m_x = flow_comp_m_x self.flow_comp_m_y = flow_comp_m_y self.quality = quality self.ground_distance = ground_distance def pack(self, mav): return MAVLink_message.pack(self, mav, 175, struct.pack('<QfffhhBB', self.time_usec, self.flow_comp_m_x, self.flow_comp_m_y, self.ground_distance, self.flow_x, self.flow_y, self.sensor_id, self.quality)) class MAVLink_global_vision_position_estimate_message(MAVLink_message): ''' ''' def __init__(self, usec, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE, 'GLOBAL_VISION_POSITION_ESTIMATE') self._fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 102, struct.pack('<Qffffff', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw)) class MAVLink_vision_position_estimate_message(MAVLink_message): ''' ''' def __init__(self, usec, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE, 'VISION_POSITION_ESTIMATE') self._fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 158, struct.pack('<Qffffff', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw)) class MAVLink_vision_speed_estimate_message(MAVLink_message): ''' ''' def __init__(self, usec, x, y, z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, 'VISION_SPEED_ESTIMATE') self._fieldnames = ['usec', 'x', 'y', 'z'] self.usec = usec self.x = x self.y = y self.z = z def pack(self, mav): return MAVLink_message.pack(self, mav, 208, struct.pack('<Qfff', self.usec, self.x, self.y, self.z)) class MAVLink_vicon_position_estimate_message(MAVLink_message): ''' ''' def __init__(self, usec, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE, 'VICON_POSITION_ESTIMATE') self._fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav): return MAVLink_message.pack(self, mav, 56, struct.pack('<Qffffff', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw)) class MAVLink_highres_imu_message(MAVLink_message): ''' The IMU readings in SI units in NED body frame ''' def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIGHRES_IMU, 'HIGHRES_IMU') self._fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated'] self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.abs_pressure = abs_pressure self.diff_pressure = diff_pressure self.pressure_alt = pressure_alt self.temperature = temperature self.fields_updated = fields_updated def pack(self, mav): return MAVLink_message.pack(self, mav, 93, struct.pack('<QfffffffffffffH', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.abs_pressure, self.diff_pressure, self.pressure_alt, self.temperature, self.fields_updated)) class MAVLink_omnidirectional_flow_message(MAVLink_message): ''' Optical flow from an omnidirectional flow sensor (e.g. PX4FLOW with wide angle lens) ''' def __init__(self, time_usec, sensor_id, left, right, quality, front_distance_m): MAVLink_message.__init__(self, MAVLINK_MSG_ID_OMNIDIRECTIONAL_FLOW, 'OMNIDIRECTIONAL_FLOW') self._fieldnames = ['time_usec', 'sensor_id', 'left', 'right', 'quality', 'front_distance_m'] self.time_usec = time_usec self.sensor_id = sensor_id self.left = left self.right = right self.quality = quality self.front_distance_m = front_distance_m def pack(self, mav): return MAVLink_message.pack(self, mav, 211, struct.pack('<Qf10h10hBB', self.time_usec, self.front_distance_m, self.left, self.right, self.sensor_id, self.quality)) class MAVLink_hil_sensor_message(MAVLink_message): ''' The IMU readings in SI units in NED body frame ''' def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_SENSOR, 'HIL_SENSOR') self._fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated'] self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.abs_pressure = abs_pressure self.diff_pressure = diff_pressure self.pressure_alt = pressure_alt self.temperature = temperature self.fields_updated = fields_updated def pack(self, mav): return MAVLink_message.pack(self, mav, 108, struct.pack('<QfffffffffffffI', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.abs_pressure, self.diff_pressure, self.pressure_alt, self.temperature, self.fields_updated)) class MAVLink_sim_state_message(MAVLink_message): ''' Status of simulation environment, if used ''' def __init__(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SIM_STATE, 'SIM_STATE') self._fieldnames = ['q1', 'q2', 'q3', 'q4', 'roll', 'pitch', 'yaw', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'lat', 'lon', 'alt', 'std_dev_horz', 'std_dev_vert', 'vn', 've', 'vd'] self.q1 = q1 self.q2 = q2 self.q3 = q3 self.q4 = q4 self.roll = roll self.pitch = pitch self.yaw = yaw self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.lat = lat self.lon = lon self.alt = alt self.std_dev_horz = std_dev_horz self.std_dev_vert = std_dev_vert self.vn = vn self.ve = ve self.vd = vd def pack(self, mav): return MAVLink_message.pack(self, mav, 32, struct.pack('<fffffffffffffffffffff', self.q1, self.q2, self.q3, self.q4, self.roll, self.pitch, self.yaw, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.lat, self.lon, self.alt, self.std_dev_horz, self.std_dev_vert, self.vn, self.ve, self.vd)) class MAVLink_radio_status_message(MAVLink_message): ''' Status generated by radio ''' def __init__(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): MAVLink_message.__init__(self, MAVLINK_MSG_ID_RADIO_STATUS, 'RADIO_STATUS') self._fieldnames = ['rssi', 'remrssi', 'txbuf', 'noise', 'remnoise', 'rxerrors', 'fixed'] self.rssi = rssi self.remrssi = remrssi self.txbuf = txbuf self.noise = noise self.remnoise = remnoise self.rxerrors = rxerrors self.fixed = fixed def pack(self, mav): return MAVLink_message.pack(self, mav, 185, struct.pack('<HHBBBBB', self.rxerrors, self.fixed, self.rssi, self.remrssi, self.txbuf, self.noise, self.remnoise)) class MAVLink_file_transfer_start_message(MAVLink_message): ''' Begin file transfer ''' def __init__(self, transfer_uid, dest_path, direction, file_size, flags): MAVLink_message.__init__(self, MAVLINK_MSG_ID_FILE_TRANSFER_START, 'FILE_TRANSFER_START') self._fieldnames = ['transfer_uid', 'dest_path', 'direction', 'file_size', 'flags'] self.transfer_uid = transfer_uid self.dest_path = dest_path self.direction = direction self.file_size = file_size self.flags = flags def pack(self, mav): return MAVLink_message.pack(self, mav, 235, struct.pack('<QI240sBB', self.transfer_uid, self.file_size, self.dest_path, self.direction, self.flags)) class MAVLink_file_transfer_dir_list_message(MAVLink_message): ''' Get directory listing ''' def __init__(self, transfer_uid, dir_path, flags): MAVLink_message.__init__(self, MAVLINK_MSG_ID_FILE_TRANSFER_DIR_LIST, 'FILE_TRANSFER_DIR_LIST') self._fieldnames = ['transfer_uid', 'dir_path', 'flags'] self.transfer_uid = transfer_uid self.dir_path = dir_path self.flags = flags def pack(self, mav): return MAVLink_message.pack(self, mav, 93, struct.pack('<Q240sB', self.transfer_uid, self.dir_path, self.flags)) class MAVLink_file_transfer_res_message(MAVLink_message): ''' File transfer result ''' def __init__(self, transfer_uid, result): MAVLink_message.__init__(self, MAVLINK_MSG_ID_FILE_TRANSFER_RES, 'FILE_TRANSFER_RES') self._fieldnames = ['transfer_uid', 'result'] self.transfer_uid = transfer_uid self.result = result def pack(self, mav): return MAVLink_message.pack(self, mav, 124, struct.pack('<QB', self.transfer_uid, self.result)) class MAVLink_hil_gps_message(MAVLink_message): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right-handed, Z-axis up (GPS frame). ''' def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_GPS, 'HIL_GPS') self._fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'vn', 've', 'vd', 'cog', 'satellites_visible'] self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.vn = vn self.ve = ve self.vd = vd self.cog = cog self.satellites_visible = satellites_visible def pack(self, mav): return MAVLink_message.pack(self, mav, 124, struct.pack('<QiiiHHHhhhHBB', self.time_usec, self.lat, self.lon, self.alt, self.eph, self.epv, self.vel, self.vn, self.ve, self.vd, self.cog, self.fix_type, self.satellites_visible)) class MAVLink_hil_optical_flow_message(MAVLink_message): ''' Simulated optical flow from a flow sensor (e.g. optical mouse sensor) ''' def __init__(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, 'HIL_OPTICAL_FLOW') self._fieldnames = ['time_usec', 'sensor_id', 'flow_x', 'flow_y', 'flow_comp_m_x', 'flow_comp_m_y', 'quality', 'ground_distance'] self.time_usec = time_usec self.sensor_id = sensor_id self.flow_x = flow_x self.flow_y = flow_y self.flow_comp_m_x = flow_comp_m_x self.flow_comp_m_y = flow_comp_m_y self.quality = quality self.ground_distance = ground_distance def pack(self, mav): return MAVLink_message.pack(self, mav, 119, struct.pack('<QfffhhBB', self.time_usec, self.flow_comp_m_x, self.flow_comp_m_y, self.ground_distance, self.flow_x, self.flow_y, self.sensor_id, self.quality)) class MAVLink_hil_state_quaternion_message(MAVLink_message): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. ''' def __init__(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc): MAVLink_message.__init__(self, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, 'HIL_STATE_QUATERNION') self._fieldnames = ['time_usec', 'attitude_quaternion', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'ind_airspeed', 'true_airspeed', 'xacc', 'yacc', 'zacc'] self.time_usec = time_usec self.attitude_quaternion = attitude_quaternion self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.lat = lat self.lon = lon self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.ind_airspeed = ind_airspeed self.true_airspeed = true_airspeed self.xacc = xacc self.yacc = yacc self.zacc = zacc def pack(self, mav): return MAVLink_message.pack(self, mav, 4, struct.pack('<Q4ffffiiihhhHHhhh', self.time_usec, self.attitude_quaternion[0], self.attitude_quaternion[1], self.attitude_quaternion[2], self.attitude_quaternion[3], self.rollspeed, self.pitchspeed, self.yawspeed, self.lat, self.lon, self.alt, self.vx, self.vy, self.vz, self.ind_airspeed, self.true_airspeed, self.xacc, self.yacc, self.zacc)) class MAVLink_scaled_imu2_message(MAVLink_message): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units ''' def __init__(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SCALED_IMU2, 'SCALED_IMU2') self._fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag'] self.time_boot_ms = time_boot_ms self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag def pack(self, mav): return MAVLink_message.pack(self, mav, 76, struct.pack('<Ihhhhhhhhh', self.time_boot_ms, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag)) class MAVLink_log_request_list_message(MAVLink_message): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. ''' def __init__(self, target_system, target_component, start, end): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_REQUEST_LIST, 'LOG_REQUEST_LIST') self._fieldnames = ['target_system', 'target_component', 'start', 'end'] self.target_system = target_system self.target_component = target_component self.start = start self.end = end def pack(self, mav): return MAVLink_message.pack(self, mav, 128, struct.pack('<HHBB', self.start, self.end, self.target_system, self.target_component)) class MAVLink_log_entry_message(MAVLink_message): ''' Reply to LOG_REQUEST_LIST ''' def __init__(self, id, num_logs, last_log_num, time_utc, size): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_ENTRY, 'LOG_ENTRY') self._fieldnames = ['id', 'num_logs', 'last_log_num', 'time_utc', 'size'] self.id = id self.num_logs = num_logs self.last_log_num = last_log_num self.time_utc = time_utc self.size = size def pack(self, mav): return MAVLink_message.pack(self, mav, 56, struct.pack('<IIHHH', self.time_utc, self.size, self.id, self.num_logs, self.last_log_num)) class MAVLink_log_request_data_message(MAVLink_message): ''' Request a chunk of a log ''' def __init__(self, target_system, target_component, id, ofs, count): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_REQUEST_DATA, 'LOG_REQUEST_DATA') self._fieldnames = ['target_system', 'target_component', 'id', 'ofs', 'count'] self.target_system = target_system self.target_component = target_component self.id = id self.ofs = ofs self.count = count def pack(self, mav): return MAVLink_message.pack(self, mav, 116, struct.pack('<IIHBB', self.ofs, self.count, self.id, self.target_system, self.target_component)) class MAVLink_log_data_message(MAVLink_message): ''' Reply to LOG_REQUEST_DATA ''' def __init__(self, id, ofs, count, data): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_DATA, 'LOG_DATA') self._fieldnames = ['id', 'ofs', 'count', 'data'] self.id = id self.ofs = ofs self.count = count self.data = data def pack(self, mav): return MAVLink_message.pack(self, mav, 134, struct.pack('<IHB90s', self.ofs, self.id, self.count, self.data)) class MAVLink_log_erase_message(MAVLink_message): ''' Erase all logs ''' def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_ERASE, 'LOG_ERASE') self._fieldnames = ['target_system', 'target_component'] self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 237, struct.pack('<BB', self.target_system, self.target_component)) class MAVLink_log_request_end_message(MAVLink_message): ''' Stop log transfer and resume normal logging ''' def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLINK_MSG_ID_LOG_REQUEST_END, 'LOG_REQUEST_END') self._fieldnames = ['target_system', 'target_component'] self.target_system = target_system self.target_component = target_component def pack(self, mav): return MAVLink_message.pack(self, mav, 203, struct.pack('<BB', self.target_system, self.target_component)) class MAVLink_gps_inject_data_message(MAVLink_message): ''' data for injecting into the onboard GPS (used for DGPS) ''' def __init__(self, target_system, target_component, len, data): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GPS_INJECT_DATA, 'GPS_INJECT_DATA') self._fieldnames = ['target_system', 'target_component', 'len', 'data'] self.target_system = target_system self.target_component = target_component self.len = len self.data = data def pack(self, mav): return MAVLink_message.pack(self, mav, 250, struct.pack('<BBB110s', self.target_system, self.target_component, self.len, self.data)) class MAVLink_gps2_raw_message(MAVLink_message): ''' Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). ''' def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): MAVLink_message.__init__(self, MAVLINK_MSG_ID_GPS2_RAW, 'GPS2_RAW') self._fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'cog', 'satellites_visible', 'dgps_numch', 'dgps_age'] self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.cog = cog self.satellites_visible = satellites_visible self.dgps_numch = dgps_numch self.dgps_age = dgps_age def pack(self, mav): return MAVLink_message.pack(self, mav, 87, struct.pack('<QiiiIHHHHBBB', self.time_usec, self.lat, self.lon, self.alt, self.dgps_age, self.eph, self.epv, self.vel, self.cog, self.fix_type, self.satellites_visible, self.dgps_numch)) class MAVLink_power_status_message(MAVLink_message): ''' Power supply status ''' def __init__(self, Vcc, Vservo, flags): MAVLink_message.__init__(self, MAVLINK_MSG_ID_POWER_STATUS, 'POWER_STATUS') self._fieldnames = ['Vcc', 'Vservo', 'flags'] self.Vcc = Vcc self.Vservo = Vservo self.flags = flags def pack(self, mav): return MAVLink_message.pack(self, mav, 203, struct.pack('<HHH', self.Vcc, self.Vservo, self.flags)) class MAVLink_battery_status_message(MAVLink_message): ''' Transmitte battery informations for a accu pack. ''' def __init__(self, accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining): MAVLink_message.__init__(self, MAVLINK_MSG_ID_BATTERY_STATUS, 'BATTERY_STATUS') self._fieldnames = ['accu_id', 'voltage_cell_1', 'voltage_cell_2', 'voltage_cell_3', 'voltage_cell_4', 'voltage_cell_5', 'voltage_cell_6', 'current_battery', 'current_consumed', 'energy_consumed', 'battery_remaining'] self.accu_id = accu_id self.voltage_cell_1 = voltage_cell_1 self.voltage_cell_2 = voltage_cell_2 self.voltage_cell_3 = voltage_cell_3 self.voltage_cell_4 = voltage_cell_4 self.voltage_cell_5 = voltage_cell_5 self.voltage_cell_6 = voltage_cell_6 self.current_battery = current_battery self.current_consumed = current_consumed self.energy_consumed = energy_consumed self.battery_remaining = battery_remaining def pack(self, mav): return MAVLink_message.pack(self, mav, 177, struct.pack('<iiHHHHHHhBb', self.current_consumed, self.energy_consumed, self.voltage_cell_1, self.voltage_cell_2, self.voltage_cell_3, self.voltage_cell_4, self.voltage_cell_5, self.voltage_cell_6, self.current_battery, self.accu_id, self.battery_remaining)) class MAVLink_setpoint_8dof_message(MAVLink_message): ''' Set the 8 DOF setpoint for a controller. ''' def __init__(self, target_system, val1, val2, val3, val4, val5, val6, val7, val8): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SETPOINT_8DOF, 'SETPOINT_8DOF') self._fieldnames = ['target_system', 'val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'] self.target_system = target_system self.val1 = val1 self.val2 = val2 self.val3 = val3 self.val4 = val4 self.val5 = val5 self.val6 = val6 self.val7 = val7 self.val8 = val8 def pack(self, mav): return MAVLink_message.pack(self, mav, 241, struct.pack('<ffffffffB', self.val1, self.val2, self.val3, self.val4, self.val5, self.val6, self.val7, self.val8, self.target_system)) class MAVLink_setpoint_6dof_message(MAVLink_message): ''' Set the 6 DOF setpoint for a attitude and position controller. ''' def __init__(self, target_system, trans_x, trans_y, trans_z, rot_x, rot_y, rot_z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_SETPOINT_6DOF, 'SETPOINT_6DOF') self._fieldnames = ['target_system', 'trans_x', 'trans_y', 'trans_z', 'rot_x', 'rot_y', 'rot_z'] self.target_system = target_system self.trans_x = trans_x self.trans_y = trans_y self.trans_z = trans_z self.rot_x = rot_x self.rot_y = rot_y self.rot_z = rot_z def pack(self, mav): return MAVLink_message.pack(self, mav, 15, struct.pack('<ffffffB', self.trans_x, self.trans_y, self.trans_z, self.rot_x, self.rot_y, self.rot_z, self.target_system)) class MAVLink_memory_vect_message(MAVLink_message): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' def __init__(self, address, ver, type, value): MAVLink_message.__init__(self, MAVLINK_MSG_ID_MEMORY_VECT, 'MEMORY_VECT') self._fieldnames = ['address', 'ver', 'type', 'value'] self.address = address self.ver = ver self.type = type self.value = value def pack(self, mav): return MAVLink_message.pack(self, mav, 204, struct.pack('<HBB32s', self.address, self.ver, self.type, self.value)) class MAVLink_debug_vect_message(MAVLink_message): ''' ''' def __init__(self, name, time_usec, x, y, z): MAVLink_message.__init__(self, MAVLINK_MSG_ID_DEBUG_VECT, 'DEBUG_VECT') self._fieldnames = ['name', 'time_usec', 'x', 'y', 'z'] self.name = name self.time_usec = time_usec self.x = x self.y = y self.z = z def pack(self, mav): return MAVLink_message.pack(self, mav, 49, struct.pack('<Qfff10s', self.time_usec, self.x, self.y, self.z, self.name)) class MAVLink_named_value_float_message(MAVLink_message): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' def __init__(self, time_boot_ms, name, value): MAVLink_message.__init__(self, MAVLINK_MSG_ID_NAMED_VALUE_FLOAT, 'NAMED_VALUE_FLOAT') self._fieldnames = ['time_boot_ms', 'name', 'value'] self.time_boot_ms = time_boot_ms self.name = name self.value = value def pack(self, mav): return MAVLink_message.pack(self, mav, 170, struct.pack('<If10s', self.time_boot_ms, self.value, self.name)) class MAVLink_named_value_int_message(MAVLink_message): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' def __init__(self, time_boot_ms, name, value): MAVLink_message.__init__(self, MAVLINK_MSG_ID_NAMED_VALUE_INT, 'NAMED_VALUE_INT') self._fieldnames = ['time_boot_ms', 'name', 'value'] self.time_boot_ms = time_boot_ms self.name = name self.value = value def pack(self, mav): return MAVLink_message.pack(self, mav, 44, struct.pack('<Ii10s', self.time_boot_ms, self.value, self.name)) class MAVLink_statustext_message(MAVLink_message): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). ''' def __init__(self, severity, text): MAVLink_message.__init__(self, MAVLINK_MSG_ID_STATUSTEXT, 'STATUSTEXT') self._fieldnames = ['severity', 'text'] self.severity = severity self.text = text def pack(self, mav): return MAVLink_message.pack(self, mav, 83, struct.pack('<B50s', self.severity, self.text)) class MAVLink_debug_message(MAVLink_message): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. ''' def __init__(self, time_boot_ms, ind, value): MAVLink_message.__init__(self, MAVLINK_MSG_ID_DEBUG, 'DEBUG') self._fieldnames = ['time_boot_ms', 'ind', 'value'] self.time_boot_ms = time_boot_ms self.ind = ind self.value = value def pack(self, mav): return MAVLink_message.pack(self, mav, 46, struct.pack('<IfB', self.time_boot_ms, self.value, self.ind)) mavlink_map = { MAVLINK_MSG_ID_SET_CAM_SHUTTER : ( '<fHHBBB', MAVLink_set_cam_shutter_message, [3, 4, 5, 1, 2, 0], 108 ), MAVLINK_MSG_ID_IMAGE_TRIGGERED : ( '<QIffffffffff', MAVLink_image_triggered_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 86 ), MAVLINK_MSG_ID_IMAGE_TRIGGER_CONTROL : ( '<B', MAVLink_image_trigger_control_message, [0], 95 ), MAVLINK_MSG_ID_IMAGE_AVAILABLE : ( '<QQQIIIIfffffffffffHHHBB', MAVLink_image_available_message, [0, 21, 1, 2, 3, 4, 18, 19, 20, 22, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], 224 ), MAVLINK_MSG_ID_SET_POSITION_CONTROL_OFFSET : ( '<ffffBB', MAVLink_set_position_control_offset_message, [4, 5, 0, 1, 2, 3], 22 ), MAVLINK_MSG_ID_POSITION_CONTROL_SETPOINT : ( '<ffffH', MAVLink_position_control_setpoint_message, [4, 0, 1, 2, 3], 28 ), MAVLINK_MSG_ID_MARKER : ( '<ffffffH', MAVLink_marker_message, [6, 0, 1, 2, 3, 4, 5], 249 ), MAVLINK_MSG_ID_RAW_AUX : ( '<iHHHHHh', MAVLink_raw_aux_message, [1, 2, 3, 4, 5, 6, 0], 182 ), MAVLINK_MSG_ID_WATCHDOG_HEARTBEAT : ( '<HH', MAVLink_watchdog_heartbeat_message, [0, 1], 153 ), MAVLINK_MSG_ID_WATCHDOG_PROCESS_INFO : ( '<iHH100s147s', MAVLink_watchdog_process_info_message, [1, 2, 3, 4, 0], 16 ), MAVLINK_MSG_ID_WATCHDOG_PROCESS_STATUS : ( '<iHHHBB', MAVLink_watchdog_process_status_message, [1, 2, 4, 5, 0, 3], 29 ), MAVLINK_MSG_ID_WATCHDOG_COMMAND : ( '<HHBB', MAVLink_watchdog_command_message, [2, 0, 1, 3], 162 ), MAVLINK_MSG_ID_PATTERN_DETECTED : ( '<fB100sB', MAVLink_pattern_detected_message, [1, 0, 2, 3], 90 ), MAVLINK_MSG_ID_POINT_OF_INTEREST : ( '<fffHBBB26s', MAVLink_point_of_interest_message, [4, 5, 6, 3, 0, 1, 2, 7], 95 ), MAVLINK_MSG_ID_POINT_OF_INTEREST_CONNECTION : ( '<ffffffHBBB26s', MAVLink_point_of_interest_connection_message, [7, 8, 9, 6, 0, 1, 2, 3, 4, 5, 10], 36 ), MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE : ( '<IHHBBBB', MAVLink_data_transmission_handshake_message, [3, 0, 1, 2, 4, 5, 6], 23 ), MAVLINK_MSG_ID_ENCAPSULATED_DATA : ( '<H253s', MAVLink_encapsulated_data_message, [0, 1], 223 ), MAVLINK_MSG_ID_BRIEF_FEATURE : ( '<ffffHHB32s', MAVLink_brief_feature_message, [0, 1, 2, 6, 4, 5, 7, 3], 88 ), MAVLINK_MSG_ID_ATTITUDE_CONTROL : ( '<ffffBBBBB', MAVLink_attitude_control_message, [4, 0, 1, 2, 3, 5, 6, 7, 8], 254 ), MAVLINK_MSG_ID_HEARTBEAT : ( '<IBBBBB', MAVLink_heartbeat_message, [1, 2, 3, 0, 4, 5], 50 ), MAVLINK_MSG_ID_SYS_STATUS : ( '<IIIHHhHHHHHHb', MAVLink_sys_status_message, [0, 1, 2, 3, 4, 5, 12, 6, 7, 8, 9, 10, 11], 124 ), MAVLINK_MSG_ID_SYSTEM_TIME : ( '<QI', MAVLink_system_time_message, [0, 1], 137 ), MAVLINK_MSG_ID_PING : ( '<QIBB', MAVLink_ping_message, [0, 1, 2, 3], 237 ), MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL : ( '<BBB25s', MAVLink_change_operator_control_message, [0, 1, 2, 3], 217 ), MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK : ( '<BBB', MAVLink_change_operator_control_ack_message, [0, 1, 2], 104 ), MAVLINK_MSG_ID_AUTH_KEY : ( '<32s', MAVLink_auth_key_message, [0], 119 ), MAVLINK_MSG_ID_SET_MODE : ( '<IBB', MAVLink_set_mode_message, [1, 2, 0], 89 ), MAVLINK_MSG_ID_PARAM_REQUEST_READ : ( '<hBB16s', MAVLink_param_request_read_message, [1, 2, 3, 0], 214 ), MAVLINK_MSG_ID_PARAM_REQUEST_LIST : ( '<BB', MAVLink_param_request_list_message, [0, 1], 159 ), MAVLINK_MSG_ID_PARAM_VALUE : ( '<fHH16sB', MAVLink_param_value_message, [3, 0, 4, 1, 2], 220 ), MAVLINK_MSG_ID_PARAM_SET : ( '<fBB16sB', MAVLink_param_set_message, [1, 2, 3, 0, 4], 168 ), MAVLINK_MSG_ID_GPS_RAW_INT : ( '<QiiiHHHHBB', MAVLink_gps_raw_int_message, [0, 8, 1, 2, 3, 4, 5, 6, 7, 9], 24 ), MAVLINK_MSG_ID_GPS_STATUS : ( '<B20s20s20s20s20s', MAVLink_gps_status_message, [0, 1, 2, 3, 4, 5], 23 ), MAVLINK_MSG_ID_SCALED_IMU : ( '<Ihhhhhhhhh', MAVLink_scaled_imu_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 170 ), MAVLINK_MSG_ID_RAW_IMU : ( '<Qhhhhhhhhh', MAVLink_raw_imu_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 144 ), MAVLINK_MSG_ID_RAW_PRESSURE : ( '<Qhhhh', MAVLink_raw_pressure_message, [0, 1, 2, 3, 4], 67 ), MAVLINK_MSG_ID_SCALED_PRESSURE : ( '<Iffh', MAVLink_scaled_pressure_message, [0, 1, 2, 3], 115 ), MAVLINK_MSG_ID_ATTITUDE : ( '<Iffffff', MAVLink_attitude_message, [0, 1, 2, 3, 4, 5, 6], 39 ), MAVLINK_MSG_ID_ATTITUDE_QUATERNION : ( '<Ifffffff', MAVLink_attitude_quaternion_message, [0, 1, 2, 3, 4, 5, 6, 7], 246 ), MAVLINK_MSG_ID_LOCAL_POSITION_NED : ( '<Iffffff', MAVLink_local_position_ned_message, [0, 1, 2, 3, 4, 5, 6], 185 ), MAVLINK_MSG_ID_GLOBAL_POSITION_INT : ( '<IiiiihhhH', MAVLink_global_position_int_message, [0, 1, 2, 3, 4, 5, 6, 7, 8], 104 ), MAVLINK_MSG_ID_RC_CHANNELS_SCALED : ( '<IhhhhhhhhBB', MAVLink_rc_channels_scaled_message, [0, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10], 237 ), MAVLINK_MSG_ID_RC_CHANNELS_RAW : ( '<IHHHHHHHHBB', MAVLink_rc_channels_raw_message, [0, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10], 244 ), MAVLINK_MSG_ID_SERVO_OUTPUT_RAW : ( '<IHHHHHHHHB', MAVLink_servo_output_raw_message, [0, 9, 1, 2, 3, 4, 5, 6, 7, 8], 222 ), MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST : ( '<hhBB', MAVLink_mission_request_partial_list_message, [2, 3, 0, 1], 212 ), MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST : ( '<hhBB', MAVLink_mission_write_partial_list_message, [2, 3, 0, 1], 9 ), MAVLINK_MSG_ID_MISSION_ITEM : ( '<fffffffHHBBBBB', MAVLink_mission_item_message, [9, 10, 7, 11, 8, 12, 13, 0, 1, 2, 3, 4, 5, 6], 254 ), MAVLINK_MSG_ID_MISSION_REQUEST : ( '<HBB', MAVLink_mission_request_message, [1, 2, 0], 230 ), MAVLINK_MSG_ID_MISSION_SET_CURRENT : ( '<HBB', MAVLink_mission_set_current_message, [1, 2, 0], 28 ), MAVLINK_MSG_ID_MISSION_CURRENT : ( '<H', MAVLink_mission_current_message, [0], 28 ), MAVLINK_MSG_ID_MISSION_REQUEST_LIST : ( '<BB', MAVLink_mission_request_list_message, [0, 1], 132 ), MAVLINK_MSG_ID_MISSION_COUNT : ( '<HBB', MAVLink_mission_count_message, [1, 2, 0], 221 ), MAVLINK_MSG_ID_MISSION_CLEAR_ALL : ( '<BB', MAVLink_mission_clear_all_message, [0, 1], 232 ), MAVLINK_MSG_ID_MISSION_ITEM_REACHED : ( '<H', MAVLink_mission_item_reached_message, [0], 11 ), MAVLINK_MSG_ID_MISSION_ACK : ( '<BBB', MAVLink_mission_ack_message, [0, 1, 2], 153 ), MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN : ( '<iiiB', MAVLink_set_gps_global_origin_message, [3, 0, 1, 2], 41 ), MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN : ( '<iii', MAVLink_gps_global_origin_message, [0, 1, 2], 39 ), MAVLINK_MSG_ID_SET_LOCAL_POSITION_SETPOINT : ( '<ffffBBB', MAVLink_set_local_position_setpoint_message, [4, 5, 6, 0, 1, 2, 3], 214 ), MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT : ( '<ffffB', MAVLink_local_position_setpoint_message, [4, 0, 1, 2, 3], 223 ), MAVLINK_MSG_ID_GLOBAL_POSITION_SETPOINT_INT : ( '<iiihB', MAVLink_global_position_setpoint_int_message, [4, 0, 1, 2, 3], 141 ), MAVLINK_MSG_ID_SET_GLOBAL_POSITION_SETPOINT_INT : ( '<iiihB', MAVLink_set_global_position_setpoint_int_message, [4, 0, 1, 2, 3], 33 ), MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA : ( '<ffffffBBB', MAVLink_safety_set_allowed_area_message, [6, 7, 8, 0, 1, 2, 3, 4, 5], 15 ), MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA : ( '<ffffffB', MAVLink_safety_allowed_area_message, [6, 0, 1, 2, 3, 4, 5], 3 ), MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_THRUST : ( '<ffffBB', MAVLink_set_roll_pitch_yaw_thrust_message, [4, 5, 0, 1, 2, 3], 100 ), MAVLINK_MSG_ID_SET_ROLL_PITCH_YAW_SPEED_THRUST : ( '<ffffBB', MAVLink_set_roll_pitch_yaw_speed_thrust_message, [4, 5, 0, 1, 2, 3], 24 ), MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT : ( '<Iffff', MAVLink_roll_pitch_yaw_thrust_setpoint_message, [0, 1, 2, 3, 4], 239 ), MAVLINK_MSG_ID_ROLL_PITCH_YAW_SPEED_THRUST_SETPOINT : ( '<Iffff', MAVLink_roll_pitch_yaw_speed_thrust_setpoint_message, [0, 1, 2, 3, 4], 238 ), MAVLINK_MSG_ID_SET_QUAD_MOTORS_SETPOINT : ( '<HHHHB', MAVLink_set_quad_motors_setpoint_message, [4, 0, 1, 2, 3], 30 ), MAVLINK_MSG_ID_SET_QUAD_SWARM_ROLL_PITCH_YAW_THRUST : ( '<4h4h4h4HBB', MAVLink_set_quad_swarm_roll_pitch_yaw_thrust_message, [4, 5, 0, 1, 2, 3], 240 ), MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT : ( '<fffffhhH', MAVLink_nav_controller_output_message, [0, 1, 5, 6, 7, 2, 3, 4], 183 ), MAVLINK_MSG_ID_SET_QUAD_SWARM_LED_ROLL_PITCH_YAW_THRUST : ( '<4h4h4h4HBB4s4s4s', MAVLink_set_quad_swarm_led_roll_pitch_yaw_thrust_message, [4, 5, 6, 7, 8, 0, 1, 2, 3], 130 ), MAVLINK_MSG_ID_STATE_CORRECTION : ( '<fffffffff', MAVLink_state_correction_message, [0, 1, 2, 3, 4, 5, 6, 7, 8], 130 ), MAVLINK_MSG_ID_REQUEST_DATA_STREAM : ( '<HBBBB', MAVLink_request_data_stream_message, [1, 2, 3, 0, 4], 148 ), MAVLINK_MSG_ID_DATA_STREAM : ( '<HBB', MAVLink_data_stream_message, [1, 0, 2], 21 ), MAVLINK_MSG_ID_MANUAL_CONTROL : ( '<hhhhHB', MAVLink_manual_control_message, [5, 0, 1, 2, 3, 4], 243 ), MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE : ( '<HHHHHHHHBB', MAVLink_rc_channels_override_message, [8, 9, 0, 1, 2, 3, 4, 5, 6, 7], 124 ), MAVLINK_MSG_ID_VFR_HUD : ( '<ffffhH', MAVLink_vfr_hud_message, [0, 1, 4, 5, 2, 3], 20 ), MAVLINK_MSG_ID_COMMAND_LONG : ( '<fffffffHBBB', MAVLink_command_long_message, [8, 9, 7, 10, 0, 1, 2, 3, 4, 5, 6], 152 ), MAVLINK_MSG_ID_COMMAND_ACK : ( '<HB', MAVLink_command_ack_message, [0, 1], 143 ), MAVLINK_MSG_ID_ROLL_PITCH_YAW_RATES_THRUST_SETPOINT : ( '<Iffff', MAVLink_roll_pitch_yaw_rates_thrust_setpoint_message, [0, 1, 2, 3, 4], 127 ), MAVLINK_MSG_ID_MANUAL_SETPOINT : ( '<IffffBB', MAVLink_manual_setpoint_message, [0, 1, 2, 3, 4, 5, 6], 106 ), MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET : ( '<Iffffff', MAVLink_local_position_ned_system_global_offset_message, [0, 1, 2, 3, 4, 5, 6], 231 ), MAVLINK_MSG_ID_HIL_STATE : ( '<Qffffffiiihhhhhh', MAVLink_hil_state_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 183 ), MAVLINK_MSG_ID_HIL_CONTROLS : ( '<QffffffffBB', MAVLink_hil_controls_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 63 ), MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW : ( '<QHHHHHHHHHHHHB', MAVLink_hil_rc_inputs_raw_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 54 ), MAVLINK_MSG_ID_OPTICAL_FLOW : ( '<QfffhhBB', MAVLink_optical_flow_message, [0, 6, 4, 5, 1, 2, 7, 3], 175 ), MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE : ( '<Qffffff', MAVLink_global_vision_position_estimate_message, [0, 1, 2, 3, 4, 5, 6], 102 ), MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE : ( '<Qffffff', MAVLink_vision_position_estimate_message, [0, 1, 2, 3, 4, 5, 6], 158 ), MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE : ( '<Qfff', MAVLink_vision_speed_estimate_message, [0, 1, 2, 3], 208 ), MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE : ( '<Qffffff', MAVLink_vicon_position_estimate_message, [0, 1, 2, 3, 4, 5, 6], 56 ), MAVLINK_MSG_ID_HIGHRES_IMU : ( '<QfffffffffffffH', MAVLink_highres_imu_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 93 ), MAVLINK_MSG_ID_OMNIDIRECTIONAL_FLOW : ( '<Qf10h10hBB', MAVLink_omnidirectional_flow_message, [0, 4, 2, 3, 5, 1], 211 ), MAVLINK_MSG_ID_HIL_SENSOR : ( '<QfffffffffffffI', MAVLink_hil_sensor_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 108 ), MAVLINK_MSG_ID_SIM_STATE : ( '<fffffffffffffffffffff', MAVLink_sim_state_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 32 ), MAVLINK_MSG_ID_RADIO_STATUS : ( '<HHBBBBB', MAVLink_radio_status_message, [2, 3, 4, 5, 6, 0, 1], 185 ), MAVLINK_MSG_ID_FILE_TRANSFER_START : ( '<QI240sBB', MAVLink_file_transfer_start_message, [0, 2, 3, 1, 4], 235 ), MAVLINK_MSG_ID_FILE_TRANSFER_DIR_LIST : ( '<Q240sB', MAVLink_file_transfer_dir_list_message, [0, 1, 2], 93 ), MAVLINK_MSG_ID_FILE_TRANSFER_RES : ( '<QB', MAVLink_file_transfer_res_message, [0, 1], 124 ), MAVLINK_MSG_ID_HIL_GPS : ( '<QiiiHHHhhhHBB', MAVLink_hil_gps_message, [0, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], 124 ), MAVLINK_MSG_ID_HIL_OPTICAL_FLOW : ( '<QfffhhBB', MAVLink_hil_optical_flow_message, [0, 6, 4, 5, 1, 2, 7, 3], 119 ), MAVLINK_MSG_ID_HIL_STATE_QUATERNION : ( '<Q4ffffiiihhhHHhhh', MAVLink_hil_state_quaternion_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 4 ), MAVLINK_MSG_ID_SCALED_IMU2 : ( '<Ihhhhhhhhh', MAVLink_scaled_imu2_message, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 76 ), MAVLINK_MSG_ID_LOG_REQUEST_LIST : ( '<HHBB', MAVLink_log_request_list_message, [2, 3, 0, 1], 128 ), MAVLINK_MSG_ID_LOG_ENTRY : ( '<IIHHH', MAVLink_log_entry_message, [2, 3, 4, 0, 1], 56 ), MAVLINK_MSG_ID_LOG_REQUEST_DATA : ( '<IIHBB', MAVLink_log_request_data_message, [3, 4, 2, 0, 1], 116 ), MAVLINK_MSG_ID_LOG_DATA : ( '<IHB90s', MAVLink_log_data_message, [1, 0, 2, 3], 134 ), MAVLINK_MSG_ID_LOG_ERASE : ( '<BB', MAVLink_log_erase_message, [0, 1], 237 ), MAVLINK_MSG_ID_LOG_REQUEST_END : ( '<BB', MAVLink_log_request_end_message, [0, 1], 203 ), MAVLINK_MSG_ID_GPS_INJECT_DATA : ( '<BBB110s', MAVLink_gps_inject_data_message, [0, 1, 2, 3], 250 ), MAVLINK_MSG_ID_GPS2_RAW : ( '<QiiiIHHHHBBB', MAVLink_gps2_raw_message, [0, 9, 1, 2, 3, 5, 6, 7, 8, 10, 11, 4], 87 ), MAVLINK_MSG_ID_POWER_STATUS : ( '<HHH', MAVLink_power_status_message, [0, 1, 2], 203 ), MAVLINK_MSG_ID_BATTERY_STATUS : ( '<iiHHHHHHhBb', MAVLink_battery_status_message, [9, 2, 3, 4, 5, 6, 7, 8, 0, 1, 10], 177 ), MAVLINK_MSG_ID_SETPOINT_8DOF : ( '<ffffffffB', MAVLink_setpoint_8dof_message, [8, 0, 1, 2, 3, 4, 5, 6, 7], 241 ), MAVLINK_MSG_ID_SETPOINT_6DOF : ( '<ffffffB', MAVLink_setpoint_6dof_message, [6, 0, 1, 2, 3, 4, 5], 15 ), MAVLINK_MSG_ID_MEMORY_VECT : ( '<HBB32s', MAVLink_memory_vect_message, [0, 1, 2, 3], 204 ), MAVLINK_MSG_ID_DEBUG_VECT : ( '<Qfff10s', MAVLink_debug_vect_message, [4, 0, 1, 2, 3], 49 ), MAVLINK_MSG_ID_NAMED_VALUE_FLOAT : ( '<If10s', MAVLink_named_value_float_message, [0, 2, 1], 170 ), MAVLINK_MSG_ID_NAMED_VALUE_INT : ( '<Ii10s', MAVLink_named_value_int_message, [0, 2, 1], 44 ), MAVLINK_MSG_ID_STATUSTEXT : ( '<B50s', MAVLink_statustext_message, [0, 1], 83 ), MAVLINK_MSG_ID_DEBUG : ( '<IfB', MAVLink_debug_message, [0, 2, 1], 46 ), } class MAVError(Exception): '''MAVLink error class''' def __init__(self, msg): Exception.__init__(self, msg) self.message = msg class MAVString(str): '''NUL terminated string''' def __init__(self, s): str.__init__(self) def __str__(self): i = self.find(chr(0)) if i == -1: return self[:] return self[0:i] class MAVLink_bad_data(MAVLink_message): ''' a piece of bad data in a mavlink stream ''' def __init__(self, data, reason): MAVLink_message.__init__(self, MAVLINK_MSG_ID_BAD_DATA, 'BAD_DATA') self._fieldnames = ['data', 'reason'] self.data = data self.reason = reason self._msgbuf = data def __str__(self): '''Override the __str__ function from MAVLink_messages because non-printable characters are common in to be the reason for this message to exist.''' return '%s {%s, data:%s}' % (self._type, self.reason, [('%x' % ord(i) if isinstance(i, str) else '%x' % i) for i in self.data]) class MAVLink(object): '''MAVLink protocol handling class''' def __init__(self, file, srcSystem=0, srcComponent=0): self.seq = 0 self.file = file self.srcSystem = srcSystem self.srcComponent = srcComponent self.callback = None self.callback_args = None self.callback_kwargs = None self.send_callback = None self.send_callback_args = None self.send_callback_kwargs = None self.buf = array.array('B') self.expected_length = 6 self.have_prefix_error = False self.robust_parsing = False self.protocol_marker = 254 self.little_endian = True self.crc_extra = True self.sort_fields = True self.total_packets_sent = 0 self.total_bytes_sent = 0 self.total_packets_received = 0 self.total_bytes_received = 0 self.total_receive_errors = 0 self.startup_time = time.time() def set_callback(self, callback, *args, **kwargs): self.callback = callback self.callback_args = args self.callback_kwargs = kwargs def set_send_callback(self, callback, *args, **kwargs): self.send_callback = callback self.send_callback_args = args self.send_callback_kwargs = kwargs def send(self, mavmsg): '''send a MAVLink message''' buf = mavmsg.pack(self) self.file.write(buf) self.seq = (self.seq + 1) % 255 self.total_packets_sent += 1 self.total_bytes_sent += len(buf) if self.send_callback: self.send_callback(mavmsg, *self.send_callback_args, **self.send_callback_kwargs) def bytes_needed(self): '''return number of bytes needed for next parsing stage''' ret = self.expected_length - len(self.buf) if ret <= 0: return 1 return ret def parse_char(self, c): '''input some data bytes, possibly returning a new message''' if isinstance(c, str): self.buf.fromstring(c) else: self.buf.extend(c) self.total_bytes_received += len(c) if len(self.buf) >= 1 and self.buf[0] != 254: magic = self.buf[0] self.buf = self.buf[1:] if self.robust_parsing: m = MAVLink_bad_data(chr(magic), "Bad prefix") if self.callback: self.callback(m, *self.callback_args, **self.callback_kwargs) self.expected_length = 6 self.total_receive_errors += 1 return m if self.have_prefix_error: return None self.have_prefix_error = True self.total_receive_errors += 1 raise MAVError("invalid MAVLink prefix '%s'" % magic) self.have_prefix_error = False if len(self.buf) >= 2: (magic, self.expected_length) = struct.unpack('BB', self.buf[0:2]) self.expected_length += 8 if self.expected_length >= 8 and len(self.buf) >= self.expected_length: mbuf = self.buf[0:self.expected_length] self.buf = self.buf[self.expected_length:] self.expected_length = 6 if self.robust_parsing: try: m = self.decode(mbuf) self.total_packets_received += 1 except MAVError as reason: m = MAVLink_bad_data(mbuf, reason.message) self.total_receive_errors += 1 else: m = self.decode(mbuf) self.total_packets_received += 1 if self.callback: self.callback(m, *self.callback_args, **self.callback_kwargs) return m return None def parse_buffer(self, s): '''input some data bytes, possibly returning a list of new messages''' m = self.parse_char(s) if m is None: return None ret = [m] while True: m = self.parse_char("") if m is None: return ret ret.append(m) return ret def decode(self, msgbuf): '''decode a buffer as a MAVLink message''' # decode the header try: magic, mlen, seq, srcSystem, srcComponent, msgId = struct.unpack('cBBBBB', msgbuf[:6]) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink header: %s' % emsg) if ord(magic) != 254: raise MAVError("invalid MAVLink prefix '%s'" % magic) if mlen != len(msgbuf)-8: raise MAVError('invalid MAVLink message length. Got %u expected %u, msgId=%u' % (len(msgbuf)-8, mlen, msgId)) if not msgId in mavlink_map: raise MAVError('unknown MAVLink message ID %u' % msgId) # decode the payload (fmt, type, order_map, crc_extra) = mavlink_map[msgId] # decode the checksum try: crc, = struct.unpack('<H', msgbuf[-2:]) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink CRC: %s' % emsg) crc2 = x25crc(msgbuf[1:-2]) if True: # using CRC extra crc2.accumulate(chr(crc_extra)) if crc != crc2.crc: raise MAVError('invalid MAVLink CRC in msgID %u 0x%04x should be 0x%04x' % (msgId, crc, crc2.crc)) try: t = struct.unpack(fmt, msgbuf[6:-2]) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink payload type=%s fmt=%s payloadLength=%u: %s' % ( type, fmt, len(msgbuf[6:-2]), emsg)) tlist = list(t) # handle sorted fields if True: t = tlist[:] for i in range(0, len(tlist)): tlist[i] = t[order_map[i]] # terminate any strings for i in range(0, len(tlist)): if isinstance(tlist[i], str): tlist[i] = MAVString(tlist[i]) t = tuple(tlist) # construct the message object try: m = type(*t) except Exception as emsg: raise MAVError('Unable to instantiate MAVLink message of type %s : %s' % (type, emsg)) m._msgbuf = msgbuf m._payload = msgbuf[6:-2] m._crc = crc m._header = MAVLink_header(msgId, mlen, seq, srcSystem, srcComponent) return m def set_cam_shutter_encode(self, cam_no, cam_mode, trigger_pin, interval, exposure, gain): ''' cam_no : Camera id (uint8_t) cam_mode : Camera mode: 0 = auto, 1 = manual (uint8_t) trigger_pin : Trigger pin, 0-3 for PtGrey FireFly (uint8_t) interval : Shutter interval, in microseconds (uint16_t) exposure : Exposure time, in microseconds (uint16_t) gain : Camera gain (float) ''' msg = MAVLink_set_cam_shutter_message(cam_no, cam_mode, trigger_pin, interval, exposure, gain) msg.pack(self) return msg def set_cam_shutter_send(self, cam_no, cam_mode, trigger_pin, interval, exposure, gain): ''' cam_no : Camera id (uint8_t) cam_mode : Camera mode: 0 = auto, 1 = manual (uint8_t) trigger_pin : Trigger pin, 0-3 for PtGrey FireFly (uint8_t) interval : Shutter interval, in microseconds (uint16_t) exposure : Exposure time, in microseconds (uint16_t) gain : Camera gain (float) ''' return self.send(self.set_cam_shutter_encode(cam_no, cam_mode, trigger_pin, interval, exposure, gain)) def image_triggered_encode(self, timestamp, seq, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): ''' timestamp : Timestamp (uint64_t) seq : IMU seq (uint32_t) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) local_z : Local frame Z coordinate (height over ground) (float) lat : GPS X coordinate (float) lon : GPS Y coordinate (float) alt : Global frame altitude (float) ground_x : Ground truth X (float) ground_y : Ground truth Y (float) ground_z : Ground truth Z (float) ''' msg = MAVLink_image_triggered_message(timestamp, seq, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z) msg.pack(self) return msg def image_triggered_send(self, timestamp, seq, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): ''' timestamp : Timestamp (uint64_t) seq : IMU seq (uint32_t) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) local_z : Local frame Z coordinate (height over ground) (float) lat : GPS X coordinate (float) lon : GPS Y coordinate (float) alt : Global frame altitude (float) ground_x : Ground truth X (float) ground_y : Ground truth Y (float) ground_z : Ground truth Z (float) ''' return self.send(self.image_triggered_encode(timestamp, seq, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z)) def image_trigger_control_encode(self, enable): ''' enable : 0 to disable, 1 to enable (uint8_t) ''' msg = MAVLink_image_trigger_control_message(enable) msg.pack(self) return msg def image_trigger_control_send(self, enable): ''' enable : 0 to disable, 1 to enable (uint8_t) ''' return self.send(self.image_trigger_control_encode(enable)) def image_available_encode(self, cam_id, cam_no, timestamp, valid_until, img_seq, img_buf_index, width, height, depth, channels, key, exposure, gain, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): ''' cam_id : Camera id (uint64_t) cam_no : Camera # (starts with 0) (uint8_t) timestamp : Timestamp (uint64_t) valid_until : Until which timestamp this buffer will stay valid (uint64_t) img_seq : The image sequence number (uint32_t) img_buf_index : Position of the image in the buffer, starts with 0 (uint32_t) width : Image width (uint16_t) height : Image height (uint16_t) depth : Image depth (uint16_t) channels : Image channels (uint8_t) key : Shared memory area key (uint32_t) exposure : Exposure time, in microseconds (uint32_t) gain : Camera gain (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) local_z : Local frame Z coordinate (height over ground) (float) lat : GPS X coordinate (float) lon : GPS Y coordinate (float) alt : Global frame altitude (float) ground_x : Ground truth X (float) ground_y : Ground truth Y (float) ground_z : Ground truth Z (float) ''' msg = MAVLink_image_available_message(cam_id, cam_no, timestamp, valid_until, img_seq, img_buf_index, width, height, depth, channels, key, exposure, gain, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z) msg.pack(self) return msg def image_available_send(self, cam_id, cam_no, timestamp, valid_until, img_seq, img_buf_index, width, height, depth, channels, key, exposure, gain, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z): ''' cam_id : Camera id (uint64_t) cam_no : Camera # (starts with 0) (uint8_t) timestamp : Timestamp (uint64_t) valid_until : Until which timestamp this buffer will stay valid (uint64_t) img_seq : The image sequence number (uint32_t) img_buf_index : Position of the image in the buffer, starts with 0 (uint32_t) width : Image width (uint16_t) height : Image height (uint16_t) depth : Image depth (uint16_t) channels : Image channels (uint8_t) key : Shared memory area key (uint32_t) exposure : Exposure time, in microseconds (uint32_t) gain : Camera gain (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) local_z : Local frame Z coordinate (height over ground) (float) lat : GPS X coordinate (float) lon : GPS Y coordinate (float) alt : Global frame altitude (float) ground_x : Ground truth X (float) ground_y : Ground truth Y (float) ground_z : Ground truth Z (float) ''' return self.send(self.image_available_encode(cam_id, cam_no, timestamp, valid_until, img_seq, img_buf_index, width, height, depth, channels, key, exposure, gain, roll, pitch, yaw, local_z, lat, lon, alt, ground_x, ground_y, ground_z)) def set_position_control_offset_encode(self, target_system, target_component, x, y, z, yaw): ''' Message sent to the MAV to set a new offset from the currently controlled position target_system : System ID (uint8_t) target_component : Component ID (uint8_t) x : x position offset (float) y : y position offset (float) z : z position offset (float) yaw : yaw orientation offset in radians, 0 = NORTH (float) ''' msg = MAVLink_set_position_control_offset_message(target_system, target_component, x, y, z, yaw) msg.pack(self) return msg def set_position_control_offset_send(self, target_system, target_component, x, y, z, yaw): ''' Message sent to the MAV to set a new offset from the currently controlled position target_system : System ID (uint8_t) target_component : Component ID (uint8_t) x : x position offset (float) y : y position offset (float) z : z position offset (float) yaw : yaw orientation offset in radians, 0 = NORTH (float) ''' return self.send(self.set_position_control_offset_encode(target_system, target_component, x, y, z, yaw)) def position_control_setpoint_encode(self, id, x, y, z, yaw): ''' id : ID of waypoint, 0 for plain position (uint16_t) x : x position (float) y : y position (float) z : z position (float) yaw : yaw orientation in radians, 0 = NORTH (float) ''' msg = MAVLink_position_control_setpoint_message(id, x, y, z, yaw) msg.pack(self) return msg def position_control_setpoint_send(self, id, x, y, z, yaw): ''' id : ID of waypoint, 0 for plain position (uint16_t) x : x position (float) y : y position (float) z : z position (float) yaw : yaw orientation in radians, 0 = NORTH (float) ''' return self.send(self.position_control_setpoint_encode(id, x, y, z, yaw)) def marker_encode(self, id, x, y, z, roll, pitch, yaw): ''' id : ID (uint16_t) x : x position (float) y : y position (float) z : z position (float) roll : roll orientation (float) pitch : pitch orientation (float) yaw : yaw orientation (float) ''' msg = MAVLink_marker_message(id, x, y, z, roll, pitch, yaw) msg.pack(self) return msg def marker_send(self, id, x, y, z, roll, pitch, yaw): ''' id : ID (uint16_t) x : x position (float) y : y position (float) z : z position (float) roll : roll orientation (float) pitch : pitch orientation (float) yaw : yaw orientation (float) ''' return self.send(self.marker_encode(id, x, y, z, roll, pitch, yaw)) def raw_aux_encode(self, adc1, adc2, adc3, adc4, vbat, temp, baro): ''' adc1 : ADC1 (J405 ADC3, LPC2148 AD0.6) (uint16_t) adc2 : ADC2 (J405 ADC5, LPC2148 AD0.2) (uint16_t) adc3 : ADC3 (J405 ADC6, LPC2148 AD0.1) (uint16_t) adc4 : ADC4 (J405 ADC7, LPC2148 AD1.3) (uint16_t) vbat : Battery voltage (uint16_t) temp : Temperature (degrees celcius) (int16_t) baro : Barometric pressure (hecto Pascal) (int32_t) ''' msg = MAVLink_raw_aux_message(adc1, adc2, adc3, adc4, vbat, temp, baro) msg.pack(self) return msg def raw_aux_send(self, adc1, adc2, adc3, adc4, vbat, temp, baro): ''' adc1 : ADC1 (J405 ADC3, LPC2148 AD0.6) (uint16_t) adc2 : ADC2 (J405 ADC5, LPC2148 AD0.2) (uint16_t) adc3 : ADC3 (J405 ADC6, LPC2148 AD0.1) (uint16_t) adc4 : ADC4 (J405 ADC7, LPC2148 AD1.3) (uint16_t) vbat : Battery voltage (uint16_t) temp : Temperature (degrees celcius) (int16_t) baro : Barometric pressure (hecto Pascal) (int32_t) ''' return self.send(self.raw_aux_encode(adc1, adc2, adc3, adc4, vbat, temp, baro)) def watchdog_heartbeat_encode(self, watchdog_id, process_count): ''' watchdog_id : Watchdog ID (uint16_t) process_count : Number of processes (uint16_t) ''' msg = MAVLink_watchdog_heartbeat_message(watchdog_id, process_count) msg.pack(self) return msg def watchdog_heartbeat_send(self, watchdog_id, process_count): ''' watchdog_id : Watchdog ID (uint16_t) process_count : Number of processes (uint16_t) ''' return self.send(self.watchdog_heartbeat_encode(watchdog_id, process_count)) def watchdog_process_info_encode(self, watchdog_id, process_id, name, arguments, timeout): ''' watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) name : Process name (char) arguments : Process arguments (char) timeout : Timeout (seconds) (int32_t) ''' msg = MAVLink_watchdog_process_info_message(watchdog_id, process_id, name, arguments, timeout) msg.pack(self) return msg def watchdog_process_info_send(self, watchdog_id, process_id, name, arguments, timeout): ''' watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) name : Process name (char) arguments : Process arguments (char) timeout : Timeout (seconds) (int32_t) ''' return self.send(self.watchdog_process_info_encode(watchdog_id, process_id, name, arguments, timeout)) def watchdog_process_status_encode(self, watchdog_id, process_id, state, muted, pid, crashes): ''' watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) state : Is running / finished / suspended / crashed (uint8_t) muted : Is muted (uint8_t) pid : PID (int32_t) crashes : Number of crashes (uint16_t) ''' msg = MAVLink_watchdog_process_status_message(watchdog_id, process_id, state, muted, pid, crashes) msg.pack(self) return msg def watchdog_process_status_send(self, watchdog_id, process_id, state, muted, pid, crashes): ''' watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) state : Is running / finished / suspended / crashed (uint8_t) muted : Is muted (uint8_t) pid : PID (int32_t) crashes : Number of crashes (uint16_t) ''' return self.send(self.watchdog_process_status_encode(watchdog_id, process_id, state, muted, pid, crashes)) def watchdog_command_encode(self, target_system_id, watchdog_id, process_id, command_id): ''' target_system_id : Target system ID (uint8_t) watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) command_id : Command ID (uint8_t) ''' msg = MAVLink_watchdog_command_message(target_system_id, watchdog_id, process_id, command_id) msg.pack(self) return msg def watchdog_command_send(self, target_system_id, watchdog_id, process_id, command_id): ''' target_system_id : Target system ID (uint8_t) watchdog_id : Watchdog ID (uint16_t) process_id : Process ID (uint16_t) command_id : Command ID (uint8_t) ''' return self.send(self.watchdog_command_encode(target_system_id, watchdog_id, process_id, command_id)) def pattern_detected_encode(self, type, confidence, file, detected): ''' type : 0: Pattern, 1: Letter (uint8_t) confidence : Confidence of detection (float) file : Pattern file name (char) detected : Accepted as true detection, 0 no, 1 yes (uint8_t) ''' msg = MAVLink_pattern_detected_message(type, confidence, file, detected) msg.pack(self) return msg def pattern_detected_send(self, type, confidence, file, detected): ''' type : 0: Pattern, 1: Letter (uint8_t) confidence : Confidence of detection (float) file : Pattern file name (char) detected : Accepted as true detection, 0 no, 1 yes (uint8_t) ''' return self.send(self.pattern_detected_encode(type, confidence, file, detected)) def point_of_interest_encode(self, type, color, coordinate_system, timeout, x, y, z, name): ''' Notifies the operator about a point of interest (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. type : 0: Notice, 1: Warning, 2: Critical, 3: Emergency, 4: Debug (uint8_t) color : 0: blue, 1: yellow, 2: red, 3: orange, 4: green, 5: magenta (uint8_t) coordinate_system : 0: global, 1:local (uint8_t) timeout : 0: no timeout, >1: timeout in seconds (uint16_t) x : X Position (float) y : Y Position (float) z : Z Position (float) name : POI name (char) ''' msg = MAVLink_point_of_interest_message(type, color, coordinate_system, timeout, x, y, z, name) msg.pack(self) return msg def point_of_interest_send(self, type, color, coordinate_system, timeout, x, y, z, name): ''' Notifies the operator about a point of interest (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. type : 0: Notice, 1: Warning, 2: Critical, 3: Emergency, 4: Debug (uint8_t) color : 0: blue, 1: yellow, 2: red, 3: orange, 4: green, 5: magenta (uint8_t) coordinate_system : 0: global, 1:local (uint8_t) timeout : 0: no timeout, >1: timeout in seconds (uint16_t) x : X Position (float) y : Y Position (float) z : Z Position (float) name : POI name (char) ''' return self.send(self.point_of_interest_encode(type, color, coordinate_system, timeout, x, y, z, name)) def point_of_interest_connection_encode(self, type, color, coordinate_system, timeout, xp1, yp1, zp1, xp2, yp2, zp2, name): ''' Notifies the operator about the connection of two point of interests (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. type : 0: Notice, 1: Warning, 2: Critical, 3: Emergency, 4: Debug (uint8_t) color : 0: blue, 1: yellow, 2: red, 3: orange, 4: green, 5: magenta (uint8_t) coordinate_system : 0: global, 1:local (uint8_t) timeout : 0: no timeout, >1: timeout in seconds (uint16_t) xp1 : X1 Position (float) yp1 : Y1 Position (float) zp1 : Z1 Position (float) xp2 : X2 Position (float) yp2 : Y2 Position (float) zp2 : Z2 Position (float) name : POI connection name (char) ''' msg = MAVLink_point_of_interest_connection_message(type, color, coordinate_system, timeout, xp1, yp1, zp1, xp2, yp2, zp2, name) msg.pack(self) return msg def point_of_interest_connection_send(self, type, color, coordinate_system, timeout, xp1, yp1, zp1, xp2, yp2, zp2, name): ''' Notifies the operator about the connection of two point of interests (POI). This can be anything detected by the system. This generic message is intented to help interfacing to generic visualizations and to display the POI on a map. type : 0: Notice, 1: Warning, 2: Critical, 3: Emergency, 4: Debug (uint8_t) color : 0: blue, 1: yellow, 2: red, 3: orange, 4: green, 5: magenta (uint8_t) coordinate_system : 0: global, 1:local (uint8_t) timeout : 0: no timeout, >1: timeout in seconds (uint16_t) xp1 : X1 Position (float) yp1 : Y1 Position (float) zp1 : Z1 Position (float) xp2 : X2 Position (float) yp2 : Y2 Position (float) zp2 : Z2 Position (float) name : POI connection name (char) ''' return self.send(self.point_of_interest_connection_encode(type, color, coordinate_system, timeout, xp1, yp1, zp1, xp2, yp2, zp2, name)) def data_transmission_handshake_encode(self, type, size, width, height, packets, payload, jpg_quality): ''' type : type of requested/acknowledged data (as defined in ENUM DATA_TYPES in mavlink/include/mavlink_types.h) (uint8_t) size : total data size in bytes (set on ACK only) (uint32_t) width : Width of a matrix or image (uint16_t) height : Height of a matrix or image (uint16_t) packets : number of packets beeing sent (set on ACK only) (uint8_t) payload : payload size per packet (normally 253 byte, see DATA field size in message ENCAPSULATED_DATA) (set on ACK only) (uint8_t) jpg_quality : JPEG quality out of [1,100] (uint8_t) ''' msg = MAVLink_data_transmission_handshake_message(type, size, width, height, packets, payload, jpg_quality) msg.pack(self) return msg def data_transmission_handshake_send(self, type, size, width, height, packets, payload, jpg_quality): ''' type : type of requested/acknowledged data (as defined in ENUM DATA_TYPES in mavlink/include/mavlink_types.h) (uint8_t) size : total data size in bytes (set on ACK only) (uint32_t) width : Width of a matrix or image (uint16_t) height : Height of a matrix or image (uint16_t) packets : number of packets beeing sent (set on ACK only) (uint8_t) payload : payload size per packet (normally 253 byte, see DATA field size in message ENCAPSULATED_DATA) (set on ACK only) (uint8_t) jpg_quality : JPEG quality out of [1,100] (uint8_t) ''' return self.send(self.data_transmission_handshake_encode(type, size, width, height, packets, payload, jpg_quality)) def encapsulated_data_encode(self, seqnr, data): ''' seqnr : sequence number (starting with 0 on every transmission) (uint16_t) data : image data bytes (uint8_t) ''' msg = MAVLink_encapsulated_data_message(seqnr, data) msg.pack(self) return msg def encapsulated_data_send(self, seqnr, data): ''' seqnr : sequence number (starting with 0 on every transmission) (uint16_t) data : image data bytes (uint8_t) ''' return self.send(self.encapsulated_data_encode(seqnr, data)) def brief_feature_encode(self, x, y, z, orientation_assignment, size, orientation, descriptor, response): ''' x : x position in m (float) y : y position in m (float) z : z position in m (float) orientation_assignment : Orientation assignment 0: false, 1:true (uint8_t) size : Size in pixels (uint16_t) orientation : Orientation (uint16_t) descriptor : Descriptor (uint8_t) response : Harris operator response at this location (float) ''' msg = MAVLink_brief_feature_message(x, y, z, orientation_assignment, size, orientation, descriptor, response) msg.pack(self) return msg def brief_feature_send(self, x, y, z, orientation_assignment, size, orientation, descriptor, response): ''' x : x position in m (float) y : y position in m (float) z : z position in m (float) orientation_assignment : Orientation assignment 0: false, 1:true (uint8_t) size : Size in pixels (uint16_t) orientation : Orientation (uint16_t) descriptor : Descriptor (uint8_t) response : Harris operator response at this location (float) ''' return self.send(self.brief_feature_encode(x, y, z, orientation_assignment, size, orientation, descriptor, response)) def attitude_control_encode(self, target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual): ''' target : The system to be controlled (uint8_t) roll : roll (float) pitch : pitch (float) yaw : yaw (float) thrust : thrust (float) roll_manual : roll control enabled auto:0, manual:1 (uint8_t) pitch_manual : pitch auto:0, manual:1 (uint8_t) yaw_manual : yaw auto:0, manual:1 (uint8_t) thrust_manual : thrust auto:0, manual:1 (uint8_t) ''' msg = MAVLink_attitude_control_message(target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual) msg.pack(self) return msg def attitude_control_send(self, target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual): ''' target : The system to be controlled (uint8_t) roll : roll (float) pitch : pitch (float) yaw : yaw (float) thrust : thrust (float) roll_manual : roll control enabled auto:0, manual:1 (uint8_t) pitch_manual : pitch auto:0, manual:1 (uint8_t) yaw_manual : yaw auto:0, manual:1 (uint8_t) thrust_manual : thrust auto:0, manual:1 (uint8_t) ''' return self.send(self.attitude_control_encode(target, roll, pitch, yaw, thrust, roll_manual, pitch_manual, yaw_manual, thrust_manual)) def heartbeat_encode(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=3): ''' The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by laying out the user interface based on the autopilot). type : Type of the MAV (quadrotor, helicopter, etc., up to 15 types, defined in MAV_TYPE ENUM) (uint8_t) autopilot : Autopilot type / class. defined in MAV_AUTOPILOT ENUM (uint8_t) base_mode : System mode bitfield, see MAV_MODE_FLAGS ENUM in mavlink/include/mavlink_types.h (uint8_t) custom_mode : A bitfield for use for autopilot-specific flags. (uint32_t) system_status : System status flag, see MAV_STATE ENUM (uint8_t) mavlink_version : MAVLink version, not writable by user, gets added by protocol because of magic data type: uint8_t_mavlink_version (uint8_t) ''' msg = MAVLink_heartbeat_message(type, autopilot, base_mode, custom_mode, system_status, mavlink_version) msg.pack(self) return msg def heartbeat_send(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=3): ''' The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by laying out the user interface based on the autopilot). type : Type of the MAV (quadrotor, helicopter, etc., up to 15 types, defined in MAV_TYPE ENUM) (uint8_t) autopilot : Autopilot type / class. defined in MAV_AUTOPILOT ENUM (uint8_t) base_mode : System mode bitfield, see MAV_MODE_FLAGS ENUM in mavlink/include/mavlink_types.h (uint8_t) custom_mode : A bitfield for use for autopilot-specific flags. (uint32_t) system_status : System status flag, see MAV_STATE ENUM (uint8_t) mavlink_version : MAVLink version, not writable by user, gets added by protocol because of magic data type: uint8_t_mavlink_version (uint8_t) ''' return self.send(self.heartbeat_encode(type, autopilot, base_mode, custom_mode, system_status, mavlink_version)) def sys_status_encode(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows wether the system is currently active or not and if an emergency occured. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occured it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. onboard_control_sensors_present : Bitmask showing which onboard controllers and sensors are present. Value of 0: not present. Value of 1: present. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) onboard_control_sensors_enabled : Bitmask showing which onboard controllers and sensors are enabled: Value of 0: not enabled. Value of 1: enabled. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) onboard_control_sensors_health : Bitmask showing which onboard controllers and sensors are operational or have an error: Value of 0: not enabled. Value of 1: enabled. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) load : Maximum usage in percent of the mainloop time, (0%: 0, 100%: 1000) should be always below 1000 (uint16_t) voltage_battery : Battery voltage, in millivolts (1 = 1 millivolt) (uint16_t) current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilot does not measure the current (int16_t) battery_remaining : Remaining battery energy: (0%: 0, 100%: 100), -1: autopilot estimate the remaining battery (int8_t) drop_rate_comm : Communication drops in percent, (0%: 0, 100%: 10'000), (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (uint16_t) errors_comm : Communication errors (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (uint16_t) errors_count1 : Autopilot-specific errors (uint16_t) errors_count2 : Autopilot-specific errors (uint16_t) errors_count3 : Autopilot-specific errors (uint16_t) errors_count4 : Autopilot-specific errors (uint16_t) ''' msg = MAVLink_sys_status_message(onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4) msg.pack(self) return msg def sys_status_send(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows wether the system is currently active or not and if an emergency occured. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occured it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. onboard_control_sensors_present : Bitmask showing which onboard controllers and sensors are present. Value of 0: not present. Value of 1: present. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) onboard_control_sensors_enabled : Bitmask showing which onboard controllers and sensors are enabled: Value of 0: not enabled. Value of 1: enabled. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) onboard_control_sensors_health : Bitmask showing which onboard controllers and sensors are operational or have an error: Value of 0: not enabled. Value of 1: enabled. Indices defined by ENUM MAV_SYS_STATUS_SENSOR (uint32_t) load : Maximum usage in percent of the mainloop time, (0%: 0, 100%: 1000) should be always below 1000 (uint16_t) voltage_battery : Battery voltage, in millivolts (1 = 1 millivolt) (uint16_t) current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilot does not measure the current (int16_t) battery_remaining : Remaining battery energy: (0%: 0, 100%: 100), -1: autopilot estimate the remaining battery (int8_t) drop_rate_comm : Communication drops in percent, (0%: 0, 100%: 10'000), (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (uint16_t) errors_comm : Communication errors (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (uint16_t) errors_count1 : Autopilot-specific errors (uint16_t) errors_count2 : Autopilot-specific errors (uint16_t) errors_count3 : Autopilot-specific errors (uint16_t) errors_count4 : Autopilot-specific errors (uint16_t) ''' return self.send(self.sys_status_encode(onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4)) def system_time_encode(self, time_unix_usec, time_boot_ms): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. time_unix_usec : Timestamp of the master clock in microseconds since UNIX epoch. (uint64_t) time_boot_ms : Timestamp of the component clock since boot time in milliseconds. (uint32_t) ''' msg = MAVLink_system_time_message(time_unix_usec, time_boot_ms) msg.pack(self) return msg def system_time_send(self, time_unix_usec, time_boot_ms): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. time_unix_usec : Timestamp of the master clock in microseconds since UNIX epoch. (uint64_t) time_boot_ms : Timestamp of the component clock since boot time in milliseconds. (uint32_t) ''' return self.send(self.system_time_encode(time_unix_usec, time_boot_ms)) def ping_encode(self, time_usec, seq, target_system, target_component): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. time_usec : Unix timestamp in microseconds (uint64_t) seq : PING sequence (uint32_t) target_system : 0: request ping from all receiving systems, if greater than 0: message is a ping response and number is the system id of the requesting system (uint8_t) target_component : 0: request ping from all receiving components, if greater than 0: message is a ping response and number is the system id of the requesting system (uint8_t) ''' msg = MAVLink_ping_message(time_usec, seq, target_system, target_component) msg.pack(self) return msg def ping_send(self, time_usec, seq, target_system, target_component): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. time_usec : Unix timestamp in microseconds (uint64_t) seq : PING sequence (uint32_t) target_system : 0: request ping from all receiving systems, if greater than 0: message is a ping response and number is the system id of the requesting system (uint8_t) target_component : 0: request ping from all receiving components, if greater than 0: message is a ping response and number is the system id of the requesting system (uint8_t) ''' return self.send(self.ping_encode(time_usec, seq, target_system, target_component)) def change_operator_control_encode(self, target_system, control_request, version, passkey): ''' Request to control this MAV target_system : System the GCS requests control for (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. (uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (char) ''' msg = MAVLink_change_operator_control_message(target_system, control_request, version, passkey) msg.pack(self) return msg def change_operator_control_send(self, target_system, control_request, version, passkey): ''' Request to control this MAV target_system : System the GCS requests control for (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. (uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (char) ''' return self.send(self.change_operator_control_encode(target_system, control_request, version, passkey)) def change_operator_control_ack_encode(self, gcs_system_id, control_request, ack): ''' Accept / deny control of this MAV gcs_system_id : ID of the GCS this message (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) ack : 0: ACK, 1: NACK: Wrong passkey, 2: NACK: Unsupported passkey encryption method, 3: NACK: Already under control (uint8_t) ''' msg = MAVLink_change_operator_control_ack_message(gcs_system_id, control_request, ack) msg.pack(self) return msg def change_operator_control_ack_send(self, gcs_system_id, control_request, ack): ''' Accept / deny control of this MAV gcs_system_id : ID of the GCS this message (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) ack : 0: ACK, 1: NACK: Wrong passkey, 2: NACK: Unsupported passkey encryption method, 3: NACK: Already under control (uint8_t) ''' return self.send(self.change_operator_control_ack_encode(gcs_system_id, control_request, ack)) def auth_key_encode(self, key): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. key : key (char) ''' msg = MAVLink_auth_key_message(key) msg.pack(self) return msg def auth_key_send(self, key): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. key : key (char) ''' return self.send(self.auth_key_encode(key)) def set_mode_encode(self, target_system, base_mode, custom_mode): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. target_system : The system setting the mode (uint8_t) base_mode : The new base mode (uint8_t) custom_mode : The new autopilot-specific mode. This field can be ignored by an autopilot. (uint32_t) ''' msg = MAVLink_set_mode_message(target_system, base_mode, custom_mode) msg.pack(self) return msg def set_mode_send(self, target_system, base_mode, custom_mode): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. target_system : The system setting the mode (uint8_t) base_mode : The new base mode (uint8_t) custom_mode : The new autopilot-specific mode. This field can be ignored by an autopilot. (uint32_t) ''' return self.send(self.set_mode_encode(target_system, base_mode, custom_mode)) def param_request_read_encode(self, target_system, target_component, param_id, param_index): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also http://qgroundcontrol.org/parameter_interface for a full documentation of QGroundControl and IMU code. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored) (int16_t) ''' msg = MAVLink_param_request_read_message(target_system, target_component, param_id, param_index) msg.pack(self) return msg def param_request_read_send(self, target_system, target_component, param_id, param_index): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also http://qgroundcontrol.org/parameter_interface for a full documentation of QGroundControl and IMU code. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored) (int16_t) ''' return self.send(self.param_request_read_encode(target_system, target_component, param_id, param_index)) def param_request_list_encode(self, target_system, target_component): ''' Request all parameters of this component. After his request, all parameters are emitted. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' msg = MAVLink_param_request_list_message(target_system, target_component) msg.pack(self) return msg def param_request_list_send(self, target_system, target_component): ''' Request all parameters of this component. After his request, all parameters are emitted. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.param_request_list_encode(target_system, target_component)) def param_value_encode(self, param_id, param_value, param_type, param_count, param_index): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) param_count : Total number of onboard parameters (uint16_t) param_index : Index of this onboard parameter (uint16_t) ''' msg = MAVLink_param_value_message(param_id, param_value, param_type, param_count, param_index) msg.pack(self) return msg def param_value_send(self, param_id, param_value, param_type, param_count, param_index): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) param_count : Total number of onboard parameters (uint16_t) param_index : Index of this onboard parameter (uint16_t) ''' return self.send(self.param_value_encode(param_id, param_value, param_type, param_count, param_index)) def param_set_encode(self, target_system, target_component, param_id, param_value, param_type): ''' Set a parameter value TEMPORARILY to RAM. It will be reset to default on system reboot. Send the ACTION MAV_ACTION_STORAGE_WRITE to PERMANENTLY write the RAM contents to EEPROM. IMPORTANT: The receiving component should acknowledge the new parameter value by sending a param_value message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) ''' msg = MAVLink_param_set_message(target_system, target_component, param_id, param_value, param_type) msg.pack(self) return msg def param_set_send(self, target_system, target_component, param_id, param_value, param_type): ''' Set a parameter value TEMPORARILY to RAM. It will be reset to default on system reboot. Send the ACTION MAV_ACTION_STORAGE_WRITE to PERMANENTLY write the RAM contents to EEPROM. IMPORTANT: The receiving component should acknowledge the new parameter value by sending a param_value message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) ''' return self.send(self.param_set_encode(target_system, target_component, param_id, param_value, param_type)) def gps_raw_int_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: UINT16_MAX (uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) ''' msg = MAVLink_gps_raw_int_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible) msg.pack(self) return msg def gps_raw_int_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: UINT16_MAX (uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) ''' return self.send(self.gps_raw_int_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible)) def gps_status_encode(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. satellites_visible : Number of satellites visible (uint8_t) satellite_prn : Global satellite ID (uint8_t) satellite_used : 0: Satellite not used, 1: used for localization (uint8_t) satellite_elevation : Elevation (0: right on top of receiver, 90: on the horizon) of satellite (uint8_t) satellite_azimuth : Direction of satellite, 0: 0 deg, 255: 360 deg. (uint8_t) satellite_snr : Signal to noise ratio of satellite (uint8_t) ''' msg = MAVLink_gps_status_message(satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr) msg.pack(self) return msg def gps_status_send(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. satellites_visible : Number of satellites visible (uint8_t) satellite_prn : Global satellite ID (uint8_t) satellite_used : 0: Satellite not used, 1: used for localization (uint8_t) satellite_elevation : Elevation (0: right on top of receiver, 90: on the horizon) of satellite (uint8_t) satellite_azimuth : Direction of satellite, 0: 0 deg, 255: 360 deg. (uint8_t) satellite_snr : Signal to noise ratio of satellite (uint8_t) ''' return self.send(self.gps_status_encode(satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr)) def scaled_imu_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) xgyro : Angular speed around X axis (millirad /sec) (int16_t) ygyro : Angular speed around Y axis (millirad /sec) (int16_t) zgyro : Angular speed around Z axis (millirad /sec) (int16_t) xmag : X Magnetic field (milli tesla) (int16_t) ymag : Y Magnetic field (milli tesla) (int16_t) zmag : Z Magnetic field (milli tesla) (int16_t) ''' msg = MAVLink_scaled_imu_message(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag) msg.pack(self) return msg def scaled_imu_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) xgyro : Angular speed around X axis (millirad /sec) (int16_t) ygyro : Angular speed around Y axis (millirad /sec) (int16_t) zgyro : Angular speed around Z axis (millirad /sec) (int16_t) xmag : X Magnetic field (milli tesla) (int16_t) ymag : Y Magnetic field (milli tesla) (int16_t) zmag : Z Magnetic field (milli tesla) (int16_t) ''' return self.send(self.scaled_imu_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag)) def raw_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) xacc : X acceleration (raw) (int16_t) yacc : Y acceleration (raw) (int16_t) zacc : Z acceleration (raw) (int16_t) xgyro : Angular speed around X axis (raw) (int16_t) ygyro : Angular speed around Y axis (raw) (int16_t) zgyro : Angular speed around Z axis (raw) (int16_t) xmag : X Magnetic field (raw) (int16_t) ymag : Y Magnetic field (raw) (int16_t) zmag : Z Magnetic field (raw) (int16_t) ''' msg = MAVLink_raw_imu_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag) msg.pack(self) return msg def raw_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) xacc : X acceleration (raw) (int16_t) yacc : Y acceleration (raw) (int16_t) zacc : Z acceleration (raw) (int16_t) xgyro : Angular speed around X axis (raw) (int16_t) ygyro : Angular speed around Y axis (raw) (int16_t) zgyro : Angular speed around Z axis (raw) (int16_t) xmag : X Magnetic field (raw) (int16_t) ymag : Y Magnetic field (raw) (int16_t) zmag : Z Magnetic field (raw) (int16_t) ''' return self.send(self.raw_imu_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag)) def raw_pressure_encode(self, time_usec, press_abs, press_diff1, press_diff2, temperature): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) press_abs : Absolute pressure (raw) (int16_t) press_diff1 : Differential pressure 1 (raw) (int16_t) press_diff2 : Differential pressure 2 (raw) (int16_t) temperature : Raw Temperature measurement (raw) (int16_t) ''' msg = MAVLink_raw_pressure_message(time_usec, press_abs, press_diff1, press_diff2, temperature) msg.pack(self) return msg def raw_pressure_send(self, time_usec, press_abs, press_diff1, press_diff2, temperature): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) press_abs : Absolute pressure (raw) (int16_t) press_diff1 : Differential pressure 1 (raw) (int16_t) press_diff2 : Differential pressure 2 (raw) (int16_t) temperature : Raw Temperature measurement (raw) (int16_t) ''' return self.send(self.raw_pressure_encode(time_usec, press_abs, press_diff1, press_diff2, temperature)) def scaled_pressure_encode(self, time_boot_ms, press_abs, press_diff, temperature): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute pressure (hectopascal) (float) press_diff : Differential pressure 1 (hectopascal) (float) temperature : Temperature measurement (0.01 degrees celsius) (int16_t) ''' msg = MAVLink_scaled_pressure_message(time_boot_ms, press_abs, press_diff, temperature) msg.pack(self) return msg def scaled_pressure_send(self, time_boot_ms, press_abs, press_diff, temperature): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute pressure (hectopascal) (float) press_diff : Differential pressure 1 (hectopascal) (float) temperature : Temperature measurement (0.01 degrees celsius) (int16_t) ''' return self.send(self.scaled_pressure_encode(time_boot_ms, press_abs, press_diff, temperature)) def attitude_encode(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) roll : Roll angle (rad, -pi..+pi) (float) pitch : Pitch angle (rad, -pi..+pi) (float) yaw : Yaw angle (rad, -pi..+pi) (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float) ''' msg = MAVLink_attitude_message(time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed) msg.pack(self) return msg def attitude_send(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) roll : Roll angle (rad, -pi..+pi) (float) pitch : Pitch angle (rad, -pi..+pi) (float) yaw : Yaw angle (rad, -pi..+pi) (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float) ''' return self.send(self.attitude_encode(time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed)) def attitude_quaternion_encode(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) q1 : Quaternion component 1 (float) q2 : Quaternion component 2 (float) q3 : Quaternion component 3 (float) q4 : Quaternion component 4 (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float) ''' msg = MAVLink_attitude_quaternion_message(time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed) msg.pack(self) return msg def attitude_quaternion_send(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) q1 : Quaternion component 1 (float) q2 : Quaternion component 2 (float) q3 : Quaternion component 3 (float) q4 : Quaternion component 4 (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float) ''' return self.send(self.attitude_quaternion_encode(time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed)) def local_position_ned_encode(self, time_boot_ms, x, y, z, vx, vy, vz): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) vx : X Speed (float) vy : Y Speed (float) vz : Z Speed (float) ''' msg = MAVLink_local_position_ned_message(time_boot_ms, x, y, z, vx, vy, vz) msg.pack(self) return msg def local_position_ned_send(self, time_boot_ms, x, y, z, vx, vy, vz): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) vx : X Speed (float) vy : Y Speed (float) vz : Z Speed (float) ''' return self.send(self.local_position_ned_encode(time_boot_ms, x, y, z, vx, vy, vz)) def global_position_int_encode(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t) relative_alt : Altitude above ground in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) hdg : Compass heading in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) ''' msg = MAVLink_global_position_int_message(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg) msg.pack(self) return msg def global_position_int_send(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t) relative_alt : Altitude above ground in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) hdg : Compass heading in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) ''' return self.send(self.global_position_int_encode(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg)) def rc_channels_scaled_encode(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi): ''' The scaled values of the RC channels received. (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t) chan1_scaled : RC channel 1 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan2_scaled : RC channel 2 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan3_scaled : RC channel 3 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan4_scaled : RC channel 4 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan5_scaled : RC channel 5 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan6_scaled : RC channel 6 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan7_scaled : RC channel 7 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan8_scaled : RC channel 8 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t) ''' msg = MAVLink_rc_channels_scaled_message(time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi) msg.pack(self) return msg def rc_channels_scaled_send(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi): ''' The scaled values of the RC channels received. (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t) chan1_scaled : RC channel 1 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan2_scaled : RC channel 2 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan3_scaled : RC channel 3 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan4_scaled : RC channel 4 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan5_scaled : RC channel 5 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan6_scaled : RC channel 6 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan7_scaled : RC channel 7 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) chan8_scaled : RC channel 8 value scaled, (-100%) -10000, (0%) 0, (100%) 10000, (invalid) INT16_MAX. (int16_t) rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t) ''' return self.send(self.rc_channels_scaled_encode(time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi)) def rc_channels_raw_encode(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t) chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t) ''' msg = MAVLink_rc_channels_raw_message(time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi) msg.pack(self) return msg def rc_channels_raw_send(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t) chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t) ''' return self.send(self.rc_channels_raw_encode(time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi)) def servo_output_raw_encode(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. time_usec : Timestamp (microseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows to encode more than 8 servos. (uint8_t) servo1_raw : Servo output 1 value, in microseconds (uint16_t) servo2_raw : Servo output 2 value, in microseconds (uint16_t) servo3_raw : Servo output 3 value, in microseconds (uint16_t) servo4_raw : Servo output 4 value, in microseconds (uint16_t) servo5_raw : Servo output 5 value, in microseconds (uint16_t) servo6_raw : Servo output 6 value, in microseconds (uint16_t) servo7_raw : Servo output 7 value, in microseconds (uint16_t) servo8_raw : Servo output 8 value, in microseconds (uint16_t) ''' msg = MAVLink_servo_output_raw_message(time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw) msg.pack(self) return msg def servo_output_raw_send(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. time_usec : Timestamp (microseconds since system boot) (uint32_t) port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows to encode more than 8 servos. (uint8_t) servo1_raw : Servo output 1 value, in microseconds (uint16_t) servo2_raw : Servo output 2 value, in microseconds (uint16_t) servo3_raw : Servo output 3 value, in microseconds (uint16_t) servo4_raw : Servo output 4 value, in microseconds (uint16_t) servo5_raw : Servo output 5 value, in microseconds (uint16_t) servo6_raw : Servo output 6 value, in microseconds (uint16_t) servo7_raw : Servo output 7 value, in microseconds (uint16_t) servo8_raw : Servo output 8 value, in microseconds (uint16_t) ''' return self.send(self.servo_output_raw_encode(time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw)) def mission_request_partial_list_encode(self, target_system, target_component, start_index, end_index): ''' Request a partial list of mission items from the system/component. http://qgroundcontrol.org/mavlink/waypoint_protocol. If start and end index are the same, just send one waypoint. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start_index : Start index, 0 by default (int16_t) end_index : End index, -1 by default (-1: send list to end). Else a valid index of the list (int16_t) ''' msg = MAVLink_mission_request_partial_list_message(target_system, target_component, start_index, end_index) msg.pack(self) return msg def mission_request_partial_list_send(self, target_system, target_component, start_index, end_index): ''' Request a partial list of mission items from the system/component. http://qgroundcontrol.org/mavlink/waypoint_protocol. If start and end index are the same, just send one waypoint. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start_index : Start index, 0 by default (int16_t) end_index : End index, -1 by default (-1: send list to end). Else a valid index of the list (int16_t) ''' return self.send(self.mission_request_partial_list_encode(target_system, target_component, start_index, end_index)) def mission_write_partial_list_encode(self, target_system, target_component, start_index, end_index): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start_index : Start index, 0 by default and smaller / equal to the largest index of the current onboard list. (int16_t) end_index : End index, equal or greater than start index. (int16_t) ''' msg = MAVLink_mission_write_partial_list_message(target_system, target_component, start_index, end_index) msg.pack(self) return msg def mission_write_partial_list_send(self, target_system, target_component, start_index, end_index): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start_index : Start index, 0 by default and smaller / equal to the largest index of the current onboard list. (int16_t) end_index : End index, equal or greater than start index. (int16_t) ''' return self.send(self.mission_write_partial_list_encode(target_system, target_component, start_index, end_index)) def mission_item_encode(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also http://qgroundcontrol.org/mavlink/waypoint_protocol. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) frame : The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h (uint8_t) command : The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs (uint16_t) current : false:0, true:1 (uint8_t) autocontinue : autocontinue to next wp (uint8_t) param1 : PARAM1, see MAV_CMD enum (float) param2 : PARAM2, see MAV_CMD enum (float) param3 : PARAM3, see MAV_CMD enum (float) param4 : PARAM4, see MAV_CMD enum (float) x : PARAM5 / local: x position, global: latitude (float) y : PARAM6 / y position: global: longitude (float) z : PARAM7 / z position: global: altitude (relative or absolute, depending on frame. (float) ''' msg = MAVLink_mission_item_message(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z) msg.pack(self) return msg def mission_item_send(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also http://qgroundcontrol.org/mavlink/waypoint_protocol. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) frame : The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h (uint8_t) command : The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs (uint16_t) current : false:0, true:1 (uint8_t) autocontinue : autocontinue to next wp (uint8_t) param1 : PARAM1, see MAV_CMD enum (float) param2 : PARAM2, see MAV_CMD enum (float) param3 : PARAM3, see MAV_CMD enum (float) param4 : PARAM4, see MAV_CMD enum (float) x : PARAM5 / local: x position, global: latitude (float) y : PARAM6 / y position: global: longitude (float) z : PARAM7 / z position: global: altitude (relative or absolute, depending on frame. (float) ''' return self.send(self.mission_item_encode(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z)) def mission_request_encode(self, target_system, target_component, seq): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. http://qgroundcontrol.org/mavlink/waypoint_protocol target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) ''' msg = MAVLink_mission_request_message(target_system, target_component, seq) msg.pack(self) return msg def mission_request_send(self, target_system, target_component, seq): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. http://qgroundcontrol.org/mavlink/waypoint_protocol target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) ''' return self.send(self.mission_request_encode(target_system, target_component, seq)) def mission_set_current_encode(self, target_system, target_component, seq): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in-between). target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) ''' msg = MAVLink_mission_set_current_message(target_system, target_component, seq) msg.pack(self) return msg def mission_set_current_send(self, target_system, target_component, seq): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in-between). target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) ''' return self.send(self.mission_set_current_encode(target_system, target_component, seq)) def mission_current_encode(self, seq): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. seq : Sequence (uint16_t) ''' msg = MAVLink_mission_current_message(seq) msg.pack(self) return msg def mission_current_send(self, seq): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. seq : Sequence (uint16_t) ''' return self.send(self.mission_current_encode(seq)) def mission_request_list_encode(self, target_system, target_component): ''' Request the overall list of mission items from the system/component. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' msg = MAVLink_mission_request_list_message(target_system, target_component) msg.pack(self) return msg def mission_request_list_send(self, target_system, target_component): ''' Request the overall list of mission items from the system/component. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.mission_request_list_encode(target_system, target_component)) def mission_count_encode(self, target_system, target_component, count): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of MISSIONs. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) count : Number of mission items in the sequence (uint16_t) ''' msg = MAVLink_mission_count_message(target_system, target_component, count) msg.pack(self) return msg def mission_count_send(self, target_system, target_component, count): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of MISSIONs. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) count : Number of mission items in the sequence (uint16_t) ''' return self.send(self.mission_count_encode(target_system, target_component, count)) def mission_clear_all_encode(self, target_system, target_component): ''' Delete all mission items at once. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' msg = MAVLink_mission_clear_all_message(target_system, target_component) msg.pack(self) return msg def mission_clear_all_send(self, target_system, target_component): ''' Delete all mission items at once. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.mission_clear_all_encode(target_system, target_component)) def mission_item_reached_encode(self, seq): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next MISSION. seq : Sequence (uint16_t) ''' msg = MAVLink_mission_item_reached_message(seq) msg.pack(self) return msg def mission_item_reached_send(self, seq): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next MISSION. seq : Sequence (uint16_t) ''' return self.send(self.mission_item_reached_encode(seq)) def mission_ack_encode(self, target_system, target_component, type): ''' Ack message during MISSION handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). target_system : System ID (uint8_t) target_component : Component ID (uint8_t) type : See MAV_MISSION_RESULT enum (uint8_t) ''' msg = MAVLink_mission_ack_message(target_system, target_component, type) msg.pack(self) return msg def mission_ack_send(self, target_system, target_component, type): ''' Ack message during MISSION handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). target_system : System ID (uint8_t) target_component : Component ID (uint8_t) type : See MAV_MISSION_RESULT enum (uint8_t) ''' return self.send(self.mission_ack_encode(target_system, target_component, type)) def set_gps_global_origin_encode(self, target_system, latitude, longitude, altitude): ''' As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84, in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) ''' msg = MAVLink_set_gps_global_origin_message(target_system, latitude, longitude, altitude) msg.pack(self) return msg def set_gps_global_origin_send(self, target_system, latitude, longitude, altitude): ''' As local waypoints exist, the global MISSION reference allows to transform between the local coordinate frame and the global (GPS) coordinate frame. This can be necessary when e.g. in- and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84, in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) ''' return self.send(self.set_gps_global_origin_encode(target_system, latitude, longitude, altitude)) def gps_global_origin_encode(self, latitude, longitude, altitude): ''' Once the MAV sets a new GPS-Local correspondence, this message announces the origin (0,0,0) position latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) ''' msg = MAVLink_gps_global_origin_message(latitude, longitude, altitude) msg.pack(self) return msg def gps_global_origin_send(self, latitude, longitude, altitude): ''' Once the MAV sets a new GPS-Local correspondence, this message announces the origin (0,0,0) position latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) ''' return self.send(self.gps_global_origin_encode(latitude, longitude, altitude)) def set_local_position_setpoint_encode(self, target_system, target_component, coordinate_frame, x, y, z, yaw): ''' Set the setpoint for a local position controller. This is the position in local coordinates the MAV should fly to. This message is sent by the path/MISSION planner to the onboard position controller. As some MAVs have a degree of freedom in yaw (e.g. all helicopters/quadrotors), the desired yaw angle is part of the message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_LOCAL_NED or MAV_FRAME_LOCAL_ENU (uint8_t) x : x position (float) y : y position (float) z : z position (float) yaw : Desired yaw angle (float) ''' msg = MAVLink_set_local_position_setpoint_message(target_system, target_component, coordinate_frame, x, y, z, yaw) msg.pack(self) return msg def set_local_position_setpoint_send(self, target_system, target_component, coordinate_frame, x, y, z, yaw): ''' Set the setpoint for a local position controller. This is the position in local coordinates the MAV should fly to. This message is sent by the path/MISSION planner to the onboard position controller. As some MAVs have a degree of freedom in yaw (e.g. all helicopters/quadrotors), the desired yaw angle is part of the message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_LOCAL_NED or MAV_FRAME_LOCAL_ENU (uint8_t) x : x position (float) y : y position (float) z : z position (float) yaw : Desired yaw angle (float) ''' return self.send(self.set_local_position_setpoint_encode(target_system, target_component, coordinate_frame, x, y, z, yaw)) def local_position_setpoint_encode(self, coordinate_frame, x, y, z, yaw): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_LOCAL_NED or MAV_FRAME_LOCAL_ENU (uint8_t) x : x position (float) y : y position (float) z : z position (float) yaw : Desired yaw angle (float) ''' msg = MAVLink_local_position_setpoint_message(coordinate_frame, x, y, z, yaw) msg.pack(self) return msg def local_position_setpoint_send(self, coordinate_frame, x, y, z, yaw): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_LOCAL_NED or MAV_FRAME_LOCAL_ENU (uint8_t) x : x position (float) y : y position (float) z : z position (float) yaw : Desired yaw angle (float) ''' return self.send(self.local_position_setpoint_encode(coordinate_frame, x, y, z, yaw)) def global_position_setpoint_int_encode(self, coordinate_frame, latitude, longitude, altitude, yaw): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_GLOBAL or MAV_FRAME_GLOBAL_RELATIVE_ALT (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) yaw : Desired yaw angle in degrees * 100 (int16_t) ''' msg = MAVLink_global_position_setpoint_int_message(coordinate_frame, latitude, longitude, altitude, yaw) msg.pack(self) return msg def global_position_setpoint_int_send(self, coordinate_frame, latitude, longitude, altitude, yaw): ''' Transmit the current local setpoint of the controller to other MAVs (collision avoidance) and to the GCS. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_GLOBAL or MAV_FRAME_GLOBAL_RELATIVE_ALT (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) yaw : Desired yaw angle in degrees * 100 (int16_t) ''' return self.send(self.global_position_setpoint_int_encode(coordinate_frame, latitude, longitude, altitude, yaw)) def set_global_position_setpoint_int_encode(self, coordinate_frame, latitude, longitude, altitude, yaw): ''' Set the current global position setpoint. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_GLOBAL or MAV_FRAME_GLOBAL_RELATIVE_ALT (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) yaw : Desired yaw angle in degrees * 100 (int16_t) ''' msg = MAVLink_set_global_position_setpoint_int_message(coordinate_frame, latitude, longitude, altitude, yaw) msg.pack(self) return msg def set_global_position_setpoint_int_send(self, coordinate_frame, latitude, longitude, altitude, yaw): ''' Set the current global position setpoint. coordinate_frame : Coordinate frame - valid values are only MAV_FRAME_GLOBAL or MAV_FRAME_GLOBAL_RELATIVE_ALT (uint8_t) latitude : Latitude (WGS84), in degrees * 1E7 (int32_t) longitude : Longitude (WGS84), in degrees * 1E7 (int32_t) altitude : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) yaw : Desired yaw angle in degrees * 100 (int16_t) ''' return self.send(self.set_global_position_setpoint_int_encode(coordinate_frame, latitude, longitude, altitude, yaw)) def safety_set_allowed_area_encode(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/MISSIONs to accept and which to reject. Safety areas are often enforced by national or competition regulations. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t) p1x : x position 1 / Latitude 1 (float) p1y : y position 1 / Longitude 1 (float) p1z : z position 1 / Altitude 1 (float) p2x : x position 2 / Latitude 2 (float) p2y : y position 2 / Longitude 2 (float) p2z : z position 2 / Altitude 2 (float) ''' msg = MAVLink_safety_set_allowed_area_message(target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z) msg.pack(self) return msg def safety_set_allowed_area_send(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/MISSIONs to accept and which to reject. Safety areas are often enforced by national or competition regulations. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t) p1x : x position 1 / Latitude 1 (float) p1y : y position 1 / Longitude 1 (float) p1z : z position 1 / Altitude 1 (float) p2x : x position 2 / Latitude 2 (float) p2y : y position 2 / Longitude 2 (float) p2z : z position 2 / Altitude 2 (float) ''' return self.send(self.safety_set_allowed_area_encode(target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z)) def safety_allowed_area_encode(self, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Read out the safety zone the MAV currently assumes. frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t) p1x : x position 1 / Latitude 1 (float) p1y : y position 1 / Longitude 1 (float) p1z : z position 1 / Altitude 1 (float) p2x : x position 2 / Latitude 2 (float) p2y : y position 2 / Longitude 2 (float) p2z : z position 2 / Altitude 2 (float) ''' msg = MAVLink_safety_allowed_area_message(frame, p1x, p1y, p1z, p2x, p2y, p2z) msg.pack(self) return msg def safety_allowed_area_send(self, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Read out the safety zone the MAV currently assumes. frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t) p1x : x position 1 / Latitude 1 (float) p1y : y position 1 / Longitude 1 (float) p1z : z position 1 / Altitude 1 (float) p2x : x position 2 / Latitude 2 (float) p2y : y position 2 / Longitude 2 (float) p2z : z position 2 / Altitude 2 (float) ''' return self.send(self.safety_allowed_area_encode(frame, p1x, p1y, p1z, p2x, p2y, p2z)) def set_roll_pitch_yaw_thrust_encode(self, target_system, target_component, roll, pitch, yaw, thrust): ''' Set roll, pitch and yaw. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) roll : Desired roll angle in radians (float) pitch : Desired pitch angle in radians (float) yaw : Desired yaw angle in radians (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' msg = MAVLink_set_roll_pitch_yaw_thrust_message(target_system, target_component, roll, pitch, yaw, thrust) msg.pack(self) return msg def set_roll_pitch_yaw_thrust_send(self, target_system, target_component, roll, pitch, yaw, thrust): ''' Set roll, pitch and yaw. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) roll : Desired roll angle in radians (float) pitch : Desired pitch angle in radians (float) yaw : Desired yaw angle in radians (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' return self.send(self.set_roll_pitch_yaw_thrust_encode(target_system, target_component, roll, pitch, yaw, thrust)) def set_roll_pitch_yaw_speed_thrust_encode(self, target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust): ''' Set roll, pitch and yaw. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) roll_speed : Desired roll angular speed in rad/s (float) pitch_speed : Desired pitch angular speed in rad/s (float) yaw_speed : Desired yaw angular speed in rad/s (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' msg = MAVLink_set_roll_pitch_yaw_speed_thrust_message(target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust) msg.pack(self) return msg def set_roll_pitch_yaw_speed_thrust_send(self, target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust): ''' Set roll, pitch and yaw. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) roll_speed : Desired roll angular speed in rad/s (float) pitch_speed : Desired pitch angular speed in rad/s (float) yaw_speed : Desired yaw angular speed in rad/s (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' return self.send(self.set_roll_pitch_yaw_speed_thrust_encode(target_system, target_component, roll_speed, pitch_speed, yaw_speed, thrust)) def roll_pitch_yaw_thrust_setpoint_encode(self, time_boot_ms, roll, pitch, yaw, thrust): ''' Setpoint in roll, pitch, yaw currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll angle in radians (float) pitch : Desired pitch angle in radians (float) yaw : Desired yaw angle in radians (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' msg = MAVLink_roll_pitch_yaw_thrust_setpoint_message(time_boot_ms, roll, pitch, yaw, thrust) msg.pack(self) return msg def roll_pitch_yaw_thrust_setpoint_send(self, time_boot_ms, roll, pitch, yaw, thrust): ''' Setpoint in roll, pitch, yaw currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll angle in radians (float) pitch : Desired pitch angle in radians (float) yaw : Desired yaw angle in radians (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' return self.send(self.roll_pitch_yaw_thrust_setpoint_encode(time_boot_ms, roll, pitch, yaw, thrust)) def roll_pitch_yaw_speed_thrust_setpoint_encode(self, time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust): ''' Setpoint in rollspeed, pitchspeed, yawspeed currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll_speed : Desired roll angular speed in rad/s (float) pitch_speed : Desired pitch angular speed in rad/s (float) yaw_speed : Desired yaw angular speed in rad/s (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' msg = MAVLink_roll_pitch_yaw_speed_thrust_setpoint_message(time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust) msg.pack(self) return msg def roll_pitch_yaw_speed_thrust_setpoint_send(self, time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust): ''' Setpoint in rollspeed, pitchspeed, yawspeed currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll_speed : Desired roll angular speed in rad/s (float) pitch_speed : Desired pitch angular speed in rad/s (float) yaw_speed : Desired yaw angular speed in rad/s (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' return self.send(self.roll_pitch_yaw_speed_thrust_setpoint_encode(time_boot_ms, roll_speed, pitch_speed, yaw_speed, thrust)) def set_quad_motors_setpoint_encode(self, target_system, motor_front_nw, motor_right_ne, motor_back_se, motor_left_sw): ''' Setpoint in the four motor speeds target_system : System ID of the system that should set these motor commands (uint8_t) motor_front_nw : Front motor in + configuration, front left motor in x configuration (uint16_t) motor_right_ne : Right motor in + configuration, front right motor in x configuration (uint16_t) motor_back_se : Back motor in + configuration, back right motor in x configuration (uint16_t) motor_left_sw : Left motor in + configuration, back left motor in x configuration (uint16_t) ''' msg = MAVLink_set_quad_motors_setpoint_message(target_system, motor_front_nw, motor_right_ne, motor_back_se, motor_left_sw) msg.pack(self) return msg def set_quad_motors_setpoint_send(self, target_system, motor_front_nw, motor_right_ne, motor_back_se, motor_left_sw): ''' Setpoint in the four motor speeds target_system : System ID of the system that should set these motor commands (uint8_t) motor_front_nw : Front motor in + configuration, front left motor in x configuration (uint16_t) motor_right_ne : Right motor in + configuration, front right motor in x configuration (uint16_t) motor_back_se : Back motor in + configuration, back right motor in x configuration (uint16_t) motor_left_sw : Left motor in + configuration, back left motor in x configuration (uint16_t) ''' return self.send(self.set_quad_motors_setpoint_encode(target_system, motor_front_nw, motor_right_ne, motor_back_se, motor_left_sw)) def set_quad_swarm_roll_pitch_yaw_thrust_encode(self, group, mode, roll, pitch, yaw, thrust): ''' Setpoint for up to four quadrotors in a group / wing group : ID of the quadrotor group (0 - 255, up to 256 groups supported) (uint8_t) mode : ID of the flight mode (0 - 255, up to 256 modes supported) (uint8_t) roll : Desired roll angle in radians +-PI (+-INT16_MAX) (int16_t) pitch : Desired pitch angle in radians +-PI (+-INT16_MAX) (int16_t) yaw : Desired yaw angle in radians, scaled to int16 +-PI (+-INT16_MAX) (int16_t) thrust : Collective thrust, scaled to uint16 (0..UINT16_MAX) (uint16_t) ''' msg = MAVLink_set_quad_swarm_roll_pitch_yaw_thrust_message(group, mode, roll, pitch, yaw, thrust) msg.pack(self) return msg def set_quad_swarm_roll_pitch_yaw_thrust_send(self, group, mode, roll, pitch, yaw, thrust): ''' Setpoint for up to four quadrotors in a group / wing group : ID of the quadrotor group (0 - 255, up to 256 groups supported) (uint8_t) mode : ID of the flight mode (0 - 255, up to 256 modes supported) (uint8_t) roll : Desired roll angle in radians +-PI (+-INT16_MAX) (int16_t) pitch : Desired pitch angle in radians +-PI (+-INT16_MAX) (int16_t) yaw : Desired yaw angle in radians, scaled to int16 +-PI (+-INT16_MAX) (int16_t) thrust : Collective thrust, scaled to uint16 (0..UINT16_MAX) (uint16_t) ''' return self.send(self.set_quad_swarm_roll_pitch_yaw_thrust_encode(group, mode, roll, pitch, yaw, thrust)) def nav_controller_output_encode(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error): ''' Outputs of the APM navigation controller. The primary use of this message is to check the response and signs of the controller before actual flight and to assist with tuning controller parameters. nav_roll : Current desired roll in degrees (float) nav_pitch : Current desired pitch in degrees (float) nav_bearing : Current desired heading in degrees (int16_t) target_bearing : Bearing to current MISSION/target in degrees (int16_t) wp_dist : Distance to active MISSION in meters (uint16_t) alt_error : Current altitude error in meters (float) aspd_error : Current airspeed error in meters/second (float) xtrack_error : Current crosstrack error on x-y plane in meters (float) ''' msg = MAVLink_nav_controller_output_message(nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error) msg.pack(self) return msg def nav_controller_output_send(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error): ''' Outputs of the APM navigation controller. The primary use of this message is to check the response and signs of the controller before actual flight and to assist with tuning controller parameters. nav_roll : Current desired roll in degrees (float) nav_pitch : Current desired pitch in degrees (float) nav_bearing : Current desired heading in degrees (int16_t) target_bearing : Bearing to current MISSION/target in degrees (int16_t) wp_dist : Distance to active MISSION in meters (uint16_t) alt_error : Current altitude error in meters (float) aspd_error : Current airspeed error in meters/second (float) xtrack_error : Current crosstrack error on x-y plane in meters (float) ''' return self.send(self.nav_controller_output_encode(nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error)) def set_quad_swarm_led_roll_pitch_yaw_thrust_encode(self, group, mode, led_red, led_blue, led_green, roll, pitch, yaw, thrust): ''' Setpoint for up to four quadrotors in a group / wing group : ID of the quadrotor group (0 - 255, up to 256 groups supported) (uint8_t) mode : ID of the flight mode (0 - 255, up to 256 modes supported) (uint8_t) led_red : RGB red channel (0-255) (uint8_t) led_blue : RGB green channel (0-255) (uint8_t) led_green : RGB blue channel (0-255) (uint8_t) roll : Desired roll angle in radians +-PI (+-INT16_MAX) (int16_t) pitch : Desired pitch angle in radians +-PI (+-INT16_MAX) (int16_t) yaw : Desired yaw angle in radians, scaled to int16 +-PI (+-INT16_MAX) (int16_t) thrust : Collective thrust, scaled to uint16 (0..UINT16_MAX) (uint16_t) ''' msg = MAVLink_set_quad_swarm_led_roll_pitch_yaw_thrust_message(group, mode, led_red, led_blue, led_green, roll, pitch, yaw, thrust) msg.pack(self) return msg def set_quad_swarm_led_roll_pitch_yaw_thrust_send(self, group, mode, led_red, led_blue, led_green, roll, pitch, yaw, thrust): ''' Setpoint for up to four quadrotors in a group / wing group : ID of the quadrotor group (0 - 255, up to 256 groups supported) (uint8_t) mode : ID of the flight mode (0 - 255, up to 256 modes supported) (uint8_t) led_red : RGB red channel (0-255) (uint8_t) led_blue : RGB green channel (0-255) (uint8_t) led_green : RGB blue channel (0-255) (uint8_t) roll : Desired roll angle in radians +-PI (+-INT16_MAX) (int16_t) pitch : Desired pitch angle in radians +-PI (+-INT16_MAX) (int16_t) yaw : Desired yaw angle in radians, scaled to int16 +-PI (+-INT16_MAX) (int16_t) thrust : Collective thrust, scaled to uint16 (0..UINT16_MAX) (uint16_t) ''' return self.send(self.set_quad_swarm_led_roll_pitch_yaw_thrust_encode(group, mode, led_red, led_blue, led_green, roll, pitch, yaw, thrust)) def state_correction_encode(self, xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr): ''' Corrects the systems state by adding an error correction term to the position and velocity, and by rotating the attitude by a correction angle. xErr : x position error (float) yErr : y position error (float) zErr : z position error (float) rollErr : roll error (radians) (float) pitchErr : pitch error (radians) (float) yawErr : yaw error (radians) (float) vxErr : x velocity (float) vyErr : y velocity (float) vzErr : z velocity (float) ''' msg = MAVLink_state_correction_message(xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr) msg.pack(self) return msg def state_correction_send(self, xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr): ''' Corrects the systems state by adding an error correction term to the position and velocity, and by rotating the attitude by a correction angle. xErr : x position error (float) yErr : y position error (float) zErr : z position error (float) rollErr : roll error (radians) (float) pitchErr : pitch error (radians) (float) yawErr : yaw error (radians) (float) vxErr : x velocity (float) vyErr : y velocity (float) vzErr : z velocity (float) ''' return self.send(self.state_correction_encode(xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr)) def request_data_stream_encode(self, target_system, target_component, req_stream_id, req_message_rate, start_stop): ''' target_system : The target requested to send the message stream. (uint8_t) target_component : The target requested to send the message stream. (uint8_t) req_stream_id : The ID of the requested data stream (uint8_t) req_message_rate : The requested interval between two messages of this type (uint16_t) start_stop : 1 to start sending, 0 to stop sending. (uint8_t) ''' msg = MAVLink_request_data_stream_message(target_system, target_component, req_stream_id, req_message_rate, start_stop) msg.pack(self) return msg def request_data_stream_send(self, target_system, target_component, req_stream_id, req_message_rate, start_stop): ''' target_system : The target requested to send the message stream. (uint8_t) target_component : The target requested to send the message stream. (uint8_t) req_stream_id : The ID of the requested data stream (uint8_t) req_message_rate : The requested interval between two messages of this type (uint16_t) start_stop : 1 to start sending, 0 to stop sending. (uint8_t) ''' return self.send(self.request_data_stream_encode(target_system, target_component, req_stream_id, req_message_rate, start_stop)) def data_stream_encode(self, stream_id, message_rate, on_off): ''' stream_id : The ID of the requested data stream (uint8_t) message_rate : The requested interval between two messages of this type (uint16_t) on_off : 1 stream is enabled, 0 stream is stopped. (uint8_t) ''' msg = MAVLink_data_stream_message(stream_id, message_rate, on_off) msg.pack(self) return msg def data_stream_send(self, stream_id, message_rate, on_off): ''' stream_id : The ID of the requested data stream (uint8_t) message_rate : The requested interval between two messages of this type (uint16_t) on_off : 1 stream is enabled, 0 stream is stopped. (uint8_t) ''' return self.send(self.data_stream_encode(stream_id, message_rate, on_off)) def manual_control_encode(self, target, x, y, z, r, buttons): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their target : The system to be controlled. (uint8_t) x : X-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to forward(1000)-backward(-1000) movement on a joystick and the pitch of a vehicle. (int16_t) y : Y-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to left(-1000)-right(1000) movement on a joystick and the roll of a vehicle. (int16_t) z : Z-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a separate slider movement with maximum being 1000 and minimum being -1000 on a joystick and the thrust of a vehicle. (int16_t) r : R-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a twisting of the joystick, with counter-clockwise being 1000 and clockwise being -1000, and the yaw of a vehicle. (int16_t) buttons : A bitfield corresponding to the joystick buttons' current state, 1 for pressed, 0 for released. The lowest bit corresponds to Button 1. (uint16_t) ''' msg = MAVLink_manual_control_message(target, x, y, z, r, buttons) msg.pack(self) return msg def manual_control_send(self, target, x, y, z, r, buttons): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their target : The system to be controlled. (uint8_t) x : X-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to forward(1000)-backward(-1000) movement on a joystick and the pitch of a vehicle. (int16_t) y : Y-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to left(-1000)-right(1000) movement on a joystick and the roll of a vehicle. (int16_t) z : Z-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a separate slider movement with maximum being 1000 and minimum being -1000 on a joystick and the thrust of a vehicle. (int16_t) r : R-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a twisting of the joystick, with counter-clockwise being 1000 and clockwise being -1000, and the yaw of a vehicle. (int16_t) buttons : A bitfield corresponding to the joystick buttons' current state, 1 for pressed, 0 for released. The lowest bit corresponds to Button 1. (uint16_t) ''' return self.send(self.manual_control_encode(target, x, y, z, r, buttons)) def rc_channels_override_encode(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) ''' msg = MAVLink_rc_channels_override_message(target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw) msg.pack(self) return msg def rc_channels_override_send(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX means to ignore this field. (uint16_t) ''' return self.send(self.rc_channels_override_encode(target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw)) def vfr_hud_encode(self, airspeed, groundspeed, heading, throttle, alt, climb): ''' Metrics typically displayed on a HUD for fixed wing aircraft airspeed : Current airspeed in m/s (float) groundspeed : Current ground speed in m/s (float) heading : Current heading in degrees, in compass units (0..360, 0=north) (int16_t) throttle : Current throttle setting in integer percent, 0 to 100 (uint16_t) alt : Current altitude (MSL), in meters (float) climb : Current climb rate in meters/second (float) ''' msg = MAVLink_vfr_hud_message(airspeed, groundspeed, heading, throttle, alt, climb) msg.pack(self) return msg def vfr_hud_send(self, airspeed, groundspeed, heading, throttle, alt, climb): ''' Metrics typically displayed on a HUD for fixed wing aircraft airspeed : Current airspeed in m/s (float) groundspeed : Current ground speed in m/s (float) heading : Current heading in degrees, in compass units (0..360, 0=north) (int16_t) throttle : Current throttle setting in integer percent, 0 to 100 (uint16_t) alt : Current altitude (MSL), in meters (float) climb : Current climb rate in meters/second (float) ''' return self.send(self.vfr_hud_encode(airspeed, groundspeed, heading, throttle, alt, climb)) def command_long_encode(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7): ''' Send a command with up to seven parameters to the MAV target_system : System which should execute the command (uint8_t) target_component : Component which should execute the command, 0 for all components (uint8_t) command : Command ID, as defined by MAV_CMD enum. (uint16_t) confirmation : 0: First transmission of this command. 1-255: Confirmation transmissions (e.g. for kill command) (uint8_t) param1 : Parameter 1, as defined by MAV_CMD enum. (float) param2 : Parameter 2, as defined by MAV_CMD enum. (float) param3 : Parameter 3, as defined by MAV_CMD enum. (float) param4 : Parameter 4, as defined by MAV_CMD enum. (float) param5 : Parameter 5, as defined by MAV_CMD enum. (float) param6 : Parameter 6, as defined by MAV_CMD enum. (float) param7 : Parameter 7, as defined by MAV_CMD enum. (float) ''' msg = MAVLink_command_long_message(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7) msg.pack(self) return msg def command_long_send(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7): ''' Send a command with up to seven parameters to the MAV target_system : System which should execute the command (uint8_t) target_component : Component which should execute the command, 0 for all components (uint8_t) command : Command ID, as defined by MAV_CMD enum. (uint16_t) confirmation : 0: First transmission of this command. 1-255: Confirmation transmissions (e.g. for kill command) (uint8_t) param1 : Parameter 1, as defined by MAV_CMD enum. (float) param2 : Parameter 2, as defined by MAV_CMD enum. (float) param3 : Parameter 3, as defined by MAV_CMD enum. (float) param4 : Parameter 4, as defined by MAV_CMD enum. (float) param5 : Parameter 5, as defined by MAV_CMD enum. (float) param6 : Parameter 6, as defined by MAV_CMD enum. (float) param7 : Parameter 7, as defined by MAV_CMD enum. (float) ''' return self.send(self.command_long_encode(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7)) def command_ack_encode(self, command, result): ''' Report status of a command. Includes feedback wether the command was executed. command : Command ID, as defined by MAV_CMD enum. (uint16_t) result : See MAV_RESULT enum (uint8_t) ''' msg = MAVLink_command_ack_message(command, result) msg.pack(self) return msg def command_ack_send(self, command, result): ''' Report status of a command. Includes feedback wether the command was executed. command : Command ID, as defined by MAV_CMD enum. (uint16_t) result : See MAV_RESULT enum (uint8_t) ''' return self.send(self.command_ack_encode(command, result)) def roll_pitch_yaw_rates_thrust_setpoint_encode(self, time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust): ''' Setpoint in roll, pitch, yaw rates and thrust currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll_rate : Desired roll rate in radians per second (float) pitch_rate : Desired pitch rate in radians per second (float) yaw_rate : Desired yaw rate in radians per second (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' msg = MAVLink_roll_pitch_yaw_rates_thrust_setpoint_message(time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust) msg.pack(self) return msg def roll_pitch_yaw_rates_thrust_setpoint_send(self, time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust): ''' Setpoint in roll, pitch, yaw rates and thrust currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll_rate : Desired roll rate in radians per second (float) pitch_rate : Desired pitch rate in radians per second (float) yaw_rate : Desired yaw rate in radians per second (float) thrust : Collective thrust, normalized to 0 .. 1 (float) ''' return self.send(self.roll_pitch_yaw_rates_thrust_setpoint_encode(time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust)) def manual_setpoint_encode(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): ''' Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll rate in radians per second (float) pitch : Desired pitch rate in radians per second (float) yaw : Desired yaw rate in radians per second (float) thrust : Collective thrust, normalized to 0 .. 1 (float) mode_switch : Flight mode switch position, 0.. 255 (uint8_t) manual_override_switch : Override mode switch position, 0.. 255 (uint8_t) ''' msg = MAVLink_manual_setpoint_message(time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch) msg.pack(self) return msg def manual_setpoint_send(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): ''' Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll : Desired roll rate in radians per second (float) pitch : Desired pitch rate in radians per second (float) yaw : Desired yaw rate in radians per second (float) thrust : Collective thrust, normalized to 0 .. 1 (float) mode_switch : Flight mode switch position, 0.. 255 (uint8_t) manual_override_switch : Override mode switch position, 0.. 255 (uint8_t) ''' return self.send(self.manual_setpoint_encode(time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch)) def local_position_ned_system_global_offset_encode(self, time_boot_ms, x, y, z, roll, pitch, yaw): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) roll : Roll (float) pitch : Pitch (float) yaw : Yaw (float) ''' msg = MAVLink_local_position_ned_system_global_offset_message(time_boot_ms, x, y, z, roll, pitch, yaw) msg.pack(self) return msg def local_position_ned_system_global_offset_send(self, time_boot_ms, x, y, z, roll, pitch, yaw): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) roll : Roll (float) pitch : Pitch (float) yaw : Yaw (float) ''' return self.send(self.local_position_ned_system_global_offset_encode(time_boot_ms, x, y, z, roll, pitch, yaw)) def hil_state_encode(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): ''' DEPRECATED PACKET! Suffers from missing airspeed fields and singularities due to Euler angles. Please use HIL_STATE_QUATERNION instead. Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) roll : Roll angle (rad) (float) pitch : Pitch angle (rad) (float) yaw : Yaw angle (rad) (float) rollspeed : Body frame roll / phi angular speed (rad/s) (float) pitchspeed : Body frame pitch / theta angular speed (rad/s) (float) yawspeed : Body frame yaw / psi angular speed (rad/s) (float) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) ''' msg = MAVLink_hil_state_message(time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc) msg.pack(self) return msg def hil_state_send(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): ''' DEPRECATED PACKET! Suffers from missing airspeed fields and singularities due to Euler angles. Please use HIL_STATE_QUATERNION instead. Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) roll : Roll angle (rad) (float) pitch : Pitch angle (rad) (float) yaw : Yaw angle (rad) (float) rollspeed : Body frame roll / phi angular speed (rad/s) (float) pitchspeed : Body frame pitch / theta angular speed (rad/s) (float) yawspeed : Body frame yaw / psi angular speed (rad/s) (float) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) ''' return self.send(self.hil_state_encode(time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc)) def hil_controls_encode(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode): ''' Sent from autopilot to simulation. Hardware in the loop control outputs time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) roll_ailerons : Control output -1 .. 1 (float) pitch_elevator : Control output -1 .. 1 (float) yaw_rudder : Control output -1 .. 1 (float) throttle : Throttle 0 .. 1 (float) aux1 : Aux 1, -1 .. 1 (float) aux2 : Aux 2, -1 .. 1 (float) aux3 : Aux 3, -1 .. 1 (float) aux4 : Aux 4, -1 .. 1 (float) mode : System mode (MAV_MODE) (uint8_t) nav_mode : Navigation mode (MAV_NAV_MODE) (uint8_t) ''' msg = MAVLink_hil_controls_message(time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode) msg.pack(self) return msg def hil_controls_send(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode): ''' Sent from autopilot to simulation. Hardware in the loop control outputs time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) roll_ailerons : Control output -1 .. 1 (float) pitch_elevator : Control output -1 .. 1 (float) yaw_rudder : Control output -1 .. 1 (float) throttle : Throttle 0 .. 1 (float) aux1 : Aux 1, -1 .. 1 (float) aux2 : Aux 2, -1 .. 1 (float) aux3 : Aux 3, -1 .. 1 (float) aux4 : Aux 4, -1 .. 1 (float) mode : System mode (MAV_MODE) (uint8_t) nav_mode : Navigation mode (MAV_NAV_MODE) (uint8_t) ''' return self.send(self.hil_controls_encode(time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode)) def hil_rc_inputs_raw_encode(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) chan1_raw : RC channel 1 value, in microseconds (uint16_t) chan2_raw : RC channel 2 value, in microseconds (uint16_t) chan3_raw : RC channel 3 value, in microseconds (uint16_t) chan4_raw : RC channel 4 value, in microseconds (uint16_t) chan5_raw : RC channel 5 value, in microseconds (uint16_t) chan6_raw : RC channel 6 value, in microseconds (uint16_t) chan7_raw : RC channel 7 value, in microseconds (uint16_t) chan8_raw : RC channel 8 value, in microseconds (uint16_t) chan9_raw : RC channel 9 value, in microseconds (uint16_t) chan10_raw : RC channel 10 value, in microseconds (uint16_t) chan11_raw : RC channel 11 value, in microseconds (uint16_t) chan12_raw : RC channel 12 value, in microseconds (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 255: 100% (uint8_t) ''' msg = MAVLink_hil_rc_inputs_raw_message(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi) msg.pack(self) return msg def hil_rc_inputs_raw_send(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) chan1_raw : RC channel 1 value, in microseconds (uint16_t) chan2_raw : RC channel 2 value, in microseconds (uint16_t) chan3_raw : RC channel 3 value, in microseconds (uint16_t) chan4_raw : RC channel 4 value, in microseconds (uint16_t) chan5_raw : RC channel 5 value, in microseconds (uint16_t) chan6_raw : RC channel 6 value, in microseconds (uint16_t) chan7_raw : RC channel 7 value, in microseconds (uint16_t) chan8_raw : RC channel 8 value, in microseconds (uint16_t) chan9_raw : RC channel 9 value, in microseconds (uint16_t) chan10_raw : RC channel 10 value, in microseconds (uint16_t) chan11_raw : RC channel 11 value, in microseconds (uint16_t) chan12_raw : RC channel 12 value, in microseconds (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 255: 100% (uint8_t) ''' return self.send(self.hil_rc_inputs_raw_encode(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi)) def optical_flow_encode(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels * 10 in x-sensor direction (dezi-pixels) (int16_t) flow_y : Flow in pixels * 10 in y-sensor direction (dezi-pixels) (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float) ''' msg = MAVLink_optical_flow_message(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance) msg.pack(self) return msg def optical_flow_send(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels * 10 in x-sensor direction (dezi-pixels) (int16_t) flow_y : Flow in pixels * 10 in y-sensor direction (dezi-pixels) (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float) ''' return self.send(self.optical_flow_encode(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance)) def global_vision_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' msg = MAVLink_global_vision_position_estimate_message(usec, x, y, z, roll, pitch, yaw) msg.pack(self) return msg def global_vision_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' return self.send(self.global_vision_position_estimate_encode(usec, x, y, z, roll, pitch, yaw)) def vision_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' msg = MAVLink_vision_position_estimate_message(usec, x, y, z, roll, pitch, yaw) msg.pack(self) return msg def vision_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' return self.send(self.vision_position_estimate_encode(usec, x, y, z, roll, pitch, yaw)) def vision_speed_estimate_encode(self, usec, x, y, z): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X speed (float) y : Global Y speed (float) z : Global Z speed (float) ''' msg = MAVLink_vision_speed_estimate_message(usec, x, y, z) msg.pack(self) return msg def vision_speed_estimate_send(self, usec, x, y, z): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X speed (float) y : Global Y speed (float) z : Global Z speed (float) ''' return self.send(self.vision_speed_estimate_encode(usec, x, y, z)) def vicon_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' msg = MAVLink_vicon_position_estimate_message(usec, x, y, z, roll, pitch, yaw) msg.pack(self) return msg def vicon_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw): ''' usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) x : Global X position (float) y : Global Y position (float) z : Global Z position (float) roll : Roll angle in rad (float) pitch : Pitch angle in rad (float) yaw : Yaw angle in rad (float) ''' return self.send(self.vicon_position_estimate_encode(usec, x, y, z, roll, pitch, yaw)) def highres_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) zacc : Z acceleration (m/s^2) (float) xgyro : Angular speed around X axis (rad / sec) (float) ygyro : Angular speed around Y axis (rad / sec) (float) zgyro : Angular speed around Z axis (rad / sec) (float) xmag : X Magnetic field (Gauss) (float) ymag : Y Magnetic field (Gauss) (float) zmag : Z Magnetic field (Gauss) (float) abs_pressure : Absolute pressure in millibar (float) diff_pressure : Differential pressure in millibar (float) pressure_alt : Altitude calculated from pressure (float) temperature : Temperature in degrees celsius (float) fields_updated : Bitmask for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (uint16_t) ''' msg = MAVLink_highres_imu_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated) msg.pack(self) return msg def highres_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) zacc : Z acceleration (m/s^2) (float) xgyro : Angular speed around X axis (rad / sec) (float) ygyro : Angular speed around Y axis (rad / sec) (float) zgyro : Angular speed around Z axis (rad / sec) (float) xmag : X Magnetic field (Gauss) (float) ymag : Y Magnetic field (Gauss) (float) zmag : Z Magnetic field (Gauss) (float) abs_pressure : Absolute pressure in millibar (float) diff_pressure : Differential pressure in millibar (float) pressure_alt : Altitude calculated from pressure (float) temperature : Temperature in degrees celsius (float) fields_updated : Bitmask for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (uint16_t) ''' return self.send(self.highres_imu_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated)) def omnidirectional_flow_encode(self, time_usec, sensor_id, left, right, quality, front_distance_m): ''' Optical flow from an omnidirectional flow sensor (e.g. PX4FLOW with wide angle lens) time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) sensor_id : Sensor ID (uint8_t) left : Flow in deci pixels (1 = 0.1 pixel) on left hemisphere (int16_t) right : Flow in deci pixels (1 = 0.1 pixel) on right hemisphere (int16_t) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) front_distance_m : Front distance in meters. Positive value (including zero): distance known. Negative value: Unknown distance (float) ''' msg = MAVLink_omnidirectional_flow_message(time_usec, sensor_id, left, right, quality, front_distance_m) msg.pack(self) return msg def omnidirectional_flow_send(self, time_usec, sensor_id, left, right, quality, front_distance_m): ''' Optical flow from an omnidirectional flow sensor (e.g. PX4FLOW with wide angle lens) time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) sensor_id : Sensor ID (uint8_t) left : Flow in deci pixels (1 = 0.1 pixel) on left hemisphere (int16_t) right : Flow in deci pixels (1 = 0.1 pixel) on right hemisphere (int16_t) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) front_distance_m : Front distance in meters. Positive value (including zero): distance known. Negative value: Unknown distance (float) ''' return self.send(self.omnidirectional_flow_encode(time_usec, sensor_id, left, right, quality, front_distance_m)) def hil_sensor_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) zacc : Z acceleration (m/s^2) (float) xgyro : Angular speed around X axis in body frame (rad / sec) (float) ygyro : Angular speed around Y axis in body frame (rad / sec) (float) zgyro : Angular speed around Z axis in body frame (rad / sec) (float) xmag : X Magnetic field (Gauss) (float) ymag : Y Magnetic field (Gauss) (float) zmag : Z Magnetic field (Gauss) (float) abs_pressure : Absolute pressure in millibar (float) diff_pressure : Differential pressure (airspeed) in millibar (float) pressure_alt : Altitude calculated from pressure (float) temperature : Temperature in degrees celsius (float) fields_updated : Bitmask for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (uint32_t) ''' msg = MAVLink_hil_sensor_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated) msg.pack(self) return msg def hil_sensor_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) zacc : Z acceleration (m/s^2) (float) xgyro : Angular speed around X axis in body frame (rad / sec) (float) ygyro : Angular speed around Y axis in body frame (rad / sec) (float) zgyro : Angular speed around Z axis in body frame (rad / sec) (float) xmag : X Magnetic field (Gauss) (float) ymag : Y Magnetic field (Gauss) (float) zmag : Z Magnetic field (Gauss) (float) abs_pressure : Absolute pressure in millibar (float) diff_pressure : Differential pressure (airspeed) in millibar (float) pressure_alt : Altitude calculated from pressure (float) temperature : Temperature in degrees celsius (float) fields_updated : Bitmask for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (uint32_t) ''' return self.send(self.hil_sensor_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated)) def sim_state_encode(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd): ''' Status of simulation environment, if used q1 : True attitude quaternion component 1 (float) q2 : True attitude quaternion component 2 (float) q3 : True attitude quaternion component 3 (float) q4 : True attitude quaternion component 4 (float) roll : Attitude roll expressed as Euler angles, not recommended except for human-readable outputs (float) pitch : Attitude pitch expressed as Euler angles, not recommended except for human-readable outputs (float) yaw : Attitude yaw expressed as Euler angles, not recommended except for human-readable outputs (float) xacc : X acceleration m/s/s (float) yacc : Y acceleration m/s/s (float) zacc : Z acceleration m/s/s (float) xgyro : Angular speed around X axis rad/s (float) ygyro : Angular speed around Y axis rad/s (float) zgyro : Angular speed around Z axis rad/s (float) lat : Latitude in degrees (float) lon : Longitude in degrees (float) alt : Altitude in meters (float) std_dev_horz : Horizontal position standard deviation (float) std_dev_vert : Vertical position standard deviation (float) vn : True velocity in m/s in NORTH direction in earth-fixed NED frame (float) ve : True velocity in m/s in EAST direction in earth-fixed NED frame (float) vd : True velocity in m/s in DOWN direction in earth-fixed NED frame (float) ''' msg = MAVLink_sim_state_message(q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd) msg.pack(self) return msg def sim_state_send(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd): ''' Status of simulation environment, if used q1 : True attitude quaternion component 1 (float) q2 : True attitude quaternion component 2 (float) q3 : True attitude quaternion component 3 (float) q4 : True attitude quaternion component 4 (float) roll : Attitude roll expressed as Euler angles, not recommended except for human-readable outputs (float) pitch : Attitude pitch expressed as Euler angles, not recommended except for human-readable outputs (float) yaw : Attitude yaw expressed as Euler angles, not recommended except for human-readable outputs (float) xacc : X acceleration m/s/s (float) yacc : Y acceleration m/s/s (float) zacc : Z acceleration m/s/s (float) xgyro : Angular speed around X axis rad/s (float) ygyro : Angular speed around Y axis rad/s (float) zgyro : Angular speed around Z axis rad/s (float) lat : Latitude in degrees (float) lon : Longitude in degrees (float) alt : Altitude in meters (float) std_dev_horz : Horizontal position standard deviation (float) std_dev_vert : Vertical position standard deviation (float) vn : True velocity in m/s in NORTH direction in earth-fixed NED frame (float) ve : True velocity in m/s in EAST direction in earth-fixed NED frame (float) vd : True velocity in m/s in DOWN direction in earth-fixed NED frame (float) ''' return self.send(self.sim_state_encode(q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd)) def radio_status_encode(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): ''' Status generated by radio rssi : local signal strength (uint8_t) remrssi : remote signal strength (uint8_t) txbuf : how full the tx buffer is as a percentage (uint8_t) noise : background noise level (uint8_t) remnoise : remote background noise level (uint8_t) rxerrors : receive errors (uint16_t) fixed : count of error corrected packets (uint16_t) ''' msg = MAVLink_radio_status_message(rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed) msg.pack(self) return msg def radio_status_send(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): ''' Status generated by radio rssi : local signal strength (uint8_t) remrssi : remote signal strength (uint8_t) txbuf : how full the tx buffer is as a percentage (uint8_t) noise : background noise level (uint8_t) remnoise : remote background noise level (uint8_t) rxerrors : receive errors (uint16_t) fixed : count of error corrected packets (uint16_t) ''' return self.send(self.radio_status_encode(rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed)) def file_transfer_start_encode(self, transfer_uid, dest_path, direction, file_size, flags): ''' Begin file transfer transfer_uid : Unique transfer ID (uint64_t) dest_path : Destination path (char) direction : Transfer direction: 0: from requester, 1: to requester (uint8_t) file_size : File size in bytes (uint32_t) flags : RESERVED (uint8_t) ''' msg = MAVLink_file_transfer_start_message(transfer_uid, dest_path, direction, file_size, flags) msg.pack(self) return msg def file_transfer_start_send(self, transfer_uid, dest_path, direction, file_size, flags): ''' Begin file transfer transfer_uid : Unique transfer ID (uint64_t) dest_path : Destination path (char) direction : Transfer direction: 0: from requester, 1: to requester (uint8_t) file_size : File size in bytes (uint32_t) flags : RESERVED (uint8_t) ''' return self.send(self.file_transfer_start_encode(transfer_uid, dest_path, direction, file_size, flags)) def file_transfer_dir_list_encode(self, transfer_uid, dir_path, flags): ''' Get directory listing transfer_uid : Unique transfer ID (uint64_t) dir_path : Directory path to list (char) flags : RESERVED (uint8_t) ''' msg = MAVLink_file_transfer_dir_list_message(transfer_uid, dir_path, flags) msg.pack(self) return msg def file_transfer_dir_list_send(self, transfer_uid, dir_path, flags): ''' Get directory listing transfer_uid : Unique transfer ID (uint64_t) dir_path : Directory path to list (char) flags : RESERVED (uint8_t) ''' return self.send(self.file_transfer_dir_list_encode(transfer_uid, dir_path, flags)) def file_transfer_res_encode(self, transfer_uid, result): ''' File transfer result transfer_uid : Unique transfer ID (uint64_t) result : 0: OK, 1: not permitted, 2: bad path / file name, 3: no space left on device (uint8_t) ''' msg = MAVLink_file_transfer_res_message(transfer_uid, result) msg.pack(self) return msg def file_transfer_res_send(self, transfer_uid, result): ''' File transfer result transfer_uid : Unique transfer ID (uint64_t) result : 0: OK, 1: not permitted, 2: bad path / file name, 3: no space left on device (uint8_t) ''' return self.send(self.file_transfer_res_encode(transfer_uid, result)) def hil_gps_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right- handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: 65535 (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: 65535 (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: 65535 (uint16_t) vn : GPS velocity in cm/s in NORTH direction in earth-fixed NED frame (int16_t) ve : GPS velocity in cm/s in EAST direction in earth-fixed NED frame (int16_t) vd : GPS velocity in cm/s in DOWN direction in earth-fixed NED frame (int16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: 65535 (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) ''' msg = MAVLink_hil_gps_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible) msg.pack(self) return msg def hil_gps_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. Coordinate frame is right- handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: 65535 (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: 65535 (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: 65535 (uint16_t) vn : GPS velocity in cm/s in NORTH direction in earth-fixed NED frame (int16_t) ve : GPS velocity in cm/s in EAST direction in earth-fixed NED frame (int16_t) vd : GPS velocity in cm/s in DOWN direction in earth-fixed NED frame (int16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: 65535 (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) ''' return self.send(self.hil_gps_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible)) def hil_optical_flow_encode(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): ''' Simulated optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels in x-sensor direction (int16_t) flow_y : Flow in pixels in y-sensor direction (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float) ''' msg = MAVLink_hil_optical_flow_message(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance) msg.pack(self) return msg def hil_optical_flow_send(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance): ''' Simulated optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX) (uint64_t) sensor_id : Sensor ID (uint8_t) flow_x : Flow in pixels in x-sensor direction (int16_t) flow_y : Flow in pixels in y-sensor direction (int16_t) flow_comp_m_x : Flow in meters in x-sensor direction, angular-speed compensated (float) flow_comp_m_y : Flow in meters in y-sensor direction, angular-speed compensated (float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (uint8_t) ground_distance : Ground distance in meters. Positive value: distance known. Negative value: Unknown distance (float) ''' return self.send(self.hil_optical_flow_encode(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance)) def hil_state_quaternion_encode(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) attitude_quaternion : Vehicle attitude expressed as normalized quaternion (float) rollspeed : Body frame roll / phi angular speed (rad/s) (float) pitchspeed : Body frame pitch / theta angular speed (rad/s) (float) yawspeed : Body frame yaw / psi angular speed (rad/s) (float) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) ind_airspeed : Indicated airspeed, expressed as m/s * 100 (uint16_t) true_airspeed : True airspeed, expressed as m/s * 100 (uint16_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) ''' msg = MAVLink_hil_state_quaternion_message(time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc) msg.pack(self) return msg def hil_state_quaternion_send(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) attitude_quaternion : Vehicle attitude expressed as normalized quaternion (float) rollspeed : Body frame roll / phi angular speed (rad/s) (float) pitchspeed : Body frame pitch / theta angular speed (rad/s) (float) yawspeed : Body frame yaw / psi angular speed (rad/s) (float) lat : Latitude, expressed as * 1E7 (int32_t) lon : Longitude, expressed as * 1E7 (int32_t) alt : Altitude in meters, expressed as * 1000 (millimeters) (int32_t) vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t) vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t) vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t) ind_airspeed : Indicated airspeed, expressed as m/s * 100 (uint16_t) true_airspeed : True airspeed, expressed as m/s * 100 (uint16_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) ''' return self.send(self.hil_state_quaternion_encode(time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc)) def scaled_imu2_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) xgyro : Angular speed around X axis (millirad /sec) (int16_t) ygyro : Angular speed around Y axis (millirad /sec) (int16_t) zgyro : Angular speed around Z axis (millirad /sec) (int16_t) xmag : X Magnetic field (milli tesla) (int16_t) ymag : Y Magnetic field (milli tesla) (int16_t) zmag : Z Magnetic field (milli tesla) (int16_t) ''' msg = MAVLink_scaled_imu2_message(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag) msg.pack(self) return msg def scaled_imu2_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) xacc : X acceleration (mg) (int16_t) yacc : Y acceleration (mg) (int16_t) zacc : Z acceleration (mg) (int16_t) xgyro : Angular speed around X axis (millirad /sec) (int16_t) ygyro : Angular speed around Y axis (millirad /sec) (int16_t) zgyro : Angular speed around Z axis (millirad /sec) (int16_t) xmag : X Magnetic field (milli tesla) (int16_t) ymag : Y Magnetic field (milli tesla) (int16_t) zmag : Z Magnetic field (milli tesla) (int16_t) ''' return self.send(self.scaled_imu2_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag)) def log_request_list_encode(self, target_system, target_component, start, end): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start : First log id (0 for first available) (uint16_t) end : Last log id (0xffff for last available) (uint16_t) ''' msg = MAVLink_log_request_list_message(target_system, target_component, start, end) msg.pack(self) return msg def log_request_list_send(self, target_system, target_component, start, end): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) start : First log id (0 for first available) (uint16_t) end : Last log id (0xffff for last available) (uint16_t) ''' return self.send(self.log_request_list_encode(target_system, target_component, start, end)) def log_entry_encode(self, id, num_logs, last_log_num, time_utc, size): ''' Reply to LOG_REQUEST_LIST id : Log id (uint16_t) num_logs : Total number of logs (uint16_t) last_log_num : High log number (uint16_t) time_utc : UTC timestamp of log in seconds since 1970, or 0 if not available (uint32_t) size : Size of the log (may be approximate) in bytes (uint32_t) ''' msg = MAVLink_log_entry_message(id, num_logs, last_log_num, time_utc, size) msg.pack(self) return msg def log_entry_send(self, id, num_logs, last_log_num, time_utc, size): ''' Reply to LOG_REQUEST_LIST id : Log id (uint16_t) num_logs : Total number of logs (uint16_t) last_log_num : High log number (uint16_t) time_utc : UTC timestamp of log in seconds since 1970, or 0 if not available (uint32_t) size : Size of the log (may be approximate) in bytes (uint32_t) ''' return self.send(self.log_entry_encode(id, num_logs, last_log_num, time_utc, size)) def log_request_data_encode(self, target_system, target_component, id, ofs, count): ''' Request a chunk of a log target_system : System ID (uint8_t) target_component : Component ID (uint8_t) id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (uint32_t) ''' msg = MAVLink_log_request_data_message(target_system, target_component, id, ofs, count) msg.pack(self) return msg def log_request_data_send(self, target_system, target_component, id, ofs, count): ''' Request a chunk of a log target_system : System ID (uint8_t) target_component : Component ID (uint8_t) id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (uint32_t) ''' return self.send(self.log_request_data_encode(target_system, target_component, id, ofs, count)) def log_data_encode(self, id, ofs, count, data): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (zero for end of log) (uint8_t) data : log data (uint8_t) ''' msg = MAVLink_log_data_message(id, ofs, count, data) msg.pack(self) return msg def log_data_send(self, id, ofs, count, data): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (zero for end of log) (uint8_t) data : log data (uint8_t) ''' return self.send(self.log_data_encode(id, ofs, count, data)) def log_erase_encode(self, target_system, target_component): ''' Erase all logs target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' msg = MAVLink_log_erase_message(target_system, target_component) msg.pack(self) return msg def log_erase_send(self, target_system, target_component): ''' Erase all logs target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.log_erase_encode(target_system, target_component)) def log_request_end_encode(self, target_system, target_component): ''' Stop log transfer and resume normal logging target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' msg = MAVLink_log_request_end_message(target_system, target_component) msg.pack(self) return msg def log_request_end_send(self, target_system, target_component): ''' Stop log transfer and resume normal logging target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.log_request_end_encode(target_system, target_component)) def gps_inject_data_encode(self, target_system, target_component, len, data): ''' data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) len : data length (uint8_t) data : raw data (110 is enough for 12 satellites of RTCMv2) (uint8_t) ''' msg = MAVLink_gps_inject_data_message(target_system, target_component, len, data) msg.pack(self) return msg def gps_inject_data_send(self, target_system, target_component, len, data): ''' data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) len : data length (uint8_t) data : raw data (110 is enough for 12 satellites of RTCMv2) (uint8_t) ''' return self.send(self.gps_inject_data_encode(target_system, target_component, len, data)) def gps2_raw_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): ''' Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: UINT16_MAX (uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) dgps_numch : Number of DGPS satellites (uint8_t) dgps_age : Age of DGPS info (uint32_t) ''' msg = MAVLink_gps2_raw_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age) msg.pack(self) return msg def gps2_raw_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): ''' Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (uint8_t) lat : Latitude (WGS84), in degrees * 1E7 (int32_t) lon : Longitude (WGS84), in degrees * 1E7 (int32_t) alt : Altitude (WGS84), in meters * 1000 (positive for up) (int32_t) eph : GPS HDOP horizontal dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) epv : GPS VDOP vertical dilution of position in cm (m*100). If unknown, set to: UINT16_MAX (uint16_t) vel : GPS ground speed (m/s * 100). If unknown, set to: UINT16_MAX (uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX (uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (uint8_t) dgps_numch : Number of DGPS satellites (uint8_t) dgps_age : Age of DGPS info (uint32_t) ''' return self.send(self.gps2_raw_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age)) def power_status_encode(self, Vcc, Vservo, flags): ''' Power supply status Vcc : 5V rail voltage in millivolts (uint16_t) Vservo : servo rail voltage in millivolts (uint16_t) flags : power supply status flags (see MAV_POWER_STATUS enum) (uint16_t) ''' msg = MAVLink_power_status_message(Vcc, Vservo, flags) msg.pack(self) return msg def power_status_send(self, Vcc, Vservo, flags): ''' Power supply status Vcc : 5V rail voltage in millivolts (uint16_t) Vservo : servo rail voltage in millivolts (uint16_t) flags : power supply status flags (see MAV_POWER_STATUS enum) (uint16_t) ''' return self.send(self.power_status_encode(Vcc, Vservo, flags)) def battery_status_encode(self, accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining): ''' Transmitte battery informations for a accu pack. accu_id : Accupack ID (uint8_t) voltage_cell_1 : Battery voltage of cell 1, in millivolts (1 = 1 millivolt) (uint16_t) voltage_cell_2 : Battery voltage of cell 2, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_3 : Battery voltage of cell 3, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_4 : Battery voltage of cell 4, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_5 : Battery voltage of cell 5, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_6 : Battery voltage of cell 6, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilot does not measure the current (int16_t) current_consumed : Consumed charge, in milliampere hours (1 = 1 mAh), -1: autopilot does not provide mAh consumption estimate (int32_t) energy_consumed : Consumed energy, in 100*Joules (intergrated U*I*dt) (1 = 100 Joule), -1: autopilot does not provide energy consumption estimate (int32_t) battery_remaining : Remaining battery energy: (0%: 0, 100%: 100), -1: autopilot does not estimate the remaining battery (int8_t) ''' msg = MAVLink_battery_status_message(accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining) msg.pack(self) return msg def battery_status_send(self, accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining): ''' Transmitte battery informations for a accu pack. accu_id : Accupack ID (uint8_t) voltage_cell_1 : Battery voltage of cell 1, in millivolts (1 = 1 millivolt) (uint16_t) voltage_cell_2 : Battery voltage of cell 2, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_3 : Battery voltage of cell 3, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_4 : Battery voltage of cell 4, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_5 : Battery voltage of cell 5, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) voltage_cell_6 : Battery voltage of cell 6, in millivolts (1 = 1 millivolt), -1: no cell (uint16_t) current_battery : Battery current, in 10*milliamperes (1 = 10 milliampere), -1: autopilot does not measure the current (int16_t) current_consumed : Consumed charge, in milliampere hours (1 = 1 mAh), -1: autopilot does not provide mAh consumption estimate (int32_t) energy_consumed : Consumed energy, in 100*Joules (intergrated U*I*dt) (1 = 100 Joule), -1: autopilot does not provide energy consumption estimate (int32_t) battery_remaining : Remaining battery energy: (0%: 0, 100%: 100), -1: autopilot does not estimate the remaining battery (int8_t) ''' return self.send(self.battery_status_encode(accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining)) def setpoint_8dof_encode(self, target_system, val1, val2, val3, val4, val5, val6, val7, val8): ''' Set the 8 DOF setpoint for a controller. target_system : System ID (uint8_t) val1 : Value 1 (float) val2 : Value 2 (float) val3 : Value 3 (float) val4 : Value 4 (float) val5 : Value 5 (float) val6 : Value 6 (float) val7 : Value 7 (float) val8 : Value 8 (float) ''' msg = MAVLink_setpoint_8dof_message(target_system, val1, val2, val3, val4, val5, val6, val7, val8) msg.pack(self) return msg def setpoint_8dof_send(self, target_system, val1, val2, val3, val4, val5, val6, val7, val8): ''' Set the 8 DOF setpoint for a controller. target_system : System ID (uint8_t) val1 : Value 1 (float) val2 : Value 2 (float) val3 : Value 3 (float) val4 : Value 4 (float) val5 : Value 5 (float) val6 : Value 6 (float) val7 : Value 7 (float) val8 : Value 8 (float) ''' return self.send(self.setpoint_8dof_encode(target_system, val1, val2, val3, val4, val5, val6, val7, val8)) def setpoint_6dof_encode(self, target_system, trans_x, trans_y, trans_z, rot_x, rot_y, rot_z): ''' Set the 6 DOF setpoint for a attitude and position controller. target_system : System ID (uint8_t) trans_x : Translational Component in x (float) trans_y : Translational Component in y (float) trans_z : Translational Component in z (float) rot_x : Rotational Component in x (float) rot_y : Rotational Component in y (float) rot_z : Rotational Component in z (float) ''' msg = MAVLink_setpoint_6dof_message(target_system, trans_x, trans_y, trans_z, rot_x, rot_y, rot_z) msg.pack(self) return msg def setpoint_6dof_send(self, target_system, trans_x, trans_y, trans_z, rot_x, rot_y, rot_z): ''' Set the 6 DOF setpoint for a attitude and position controller. target_system : System ID (uint8_t) trans_x : Translational Component in x (float) trans_y : Translational Component in y (float) trans_z : Translational Component in z (float) rot_x : Rotational Component in x (float) rot_y : Rotational Component in y (float) rot_z : Rotational Component in z (float) ''' return self.send(self.setpoint_6dof_encode(target_system, trans_x, trans_y, trans_z, rot_x, rot_y, rot_z)) def memory_vect_encode(self, address, ver, type, value): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. address : Starting address of the debug variables (uint16_t) ver : Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below (uint8_t) type : Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14 (uint8_t) value : Memory contents at specified address (int8_t) ''' msg = MAVLink_memory_vect_message(address, ver, type, value) msg.pack(self) return msg def memory_vect_send(self, address, ver, type, value): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. address : Starting address of the debug variables (uint16_t) ver : Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below (uint8_t) type : Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14 (uint8_t) value : Memory contents at specified address (int8_t) ''' return self.send(self.memory_vect_encode(address, ver, type, value)) def debug_vect_encode(self, name, time_usec, x, y, z): ''' name : Name (char) time_usec : Timestamp (uint64_t) x : x (float) y : y (float) z : z (float) ''' msg = MAVLink_debug_vect_message(name, time_usec, x, y, z) msg.pack(self) return msg def debug_vect_send(self, name, time_usec, x, y, z): ''' name : Name (char) time_usec : Timestamp (uint64_t) x : x (float) y : y (float) z : z (float) ''' return self.send(self.debug_vect_encode(name, time_usec, x, y, z)) def named_value_float_encode(self, time_boot_ms, name, value): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) name : Name of the debug variable (char) value : Floating point value (float) ''' msg = MAVLink_named_value_float_message(time_boot_ms, name, value) msg.pack(self) return msg def named_value_float_send(self, time_boot_ms, name, value): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) name : Name of the debug variable (char) value : Floating point value (float) ''' return self.send(self.named_value_float_encode(time_boot_ms, name, value)) def named_value_int_encode(self, time_boot_ms, name, value): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) name : Name of the debug variable (char) value : Signed integer value (int32_t) ''' msg = MAVLink_named_value_int_message(time_boot_ms, name, value) msg.pack(self) return msg def named_value_int_send(self, time_boot_ms, name, value): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) name : Name of the debug variable (char) value : Signed integer value (int32_t) ''' return self.send(self.named_value_int_encode(time_boot_ms, name, value)) def statustext_encode(self, severity, text): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). severity : Severity of status. Relies on the definitions within RFC-5424. See enum MAV_SEVERITY. (uint8_t) text : Status text message, without null termination character (char) ''' msg = MAVLink_statustext_message(severity, text) msg.pack(self) return msg def statustext_send(self, severity, text): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). severity : Severity of status. Relies on the definitions within RFC-5424. See enum MAV_SEVERITY. (uint8_t) text : Status text message, without null termination character (char) ''' return self.send(self.statustext_encode(severity, text)) def debug_encode(self, time_boot_ms, ind, value): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) ind : index of debug variable (uint8_t) value : DEBUG value (float) ''' msg = MAVLink_debug_message(time_boot_ms, ind, value) msg.pack(self) return msg def debug_send(self, time_boot_ms, ind, value): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) ind : index of debug variable (uint8_t) value : DEBUG value (float) ''' return self.send(self.debug_encode(time_boot_ms, ind, value))
bsd-3-clause
exclie/Imagenologia
vendor/zendframework/zendframework/library/Zend/View/Helper/Navigation/Links.php
23185
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\View\Helper\Navigation; use RecursiveIteratorIterator; use Traversable; use Zend\Navigation\AbstractContainer; use Zend\Navigation\Page\AbstractPage; use Zend\Stdlib\ArrayUtils; use Zend\Stdlib\ErrorHandler; use Zend\View\Exception; /** * Helper for printing <link> elements */ class Links extends AbstractHelper { /** * Constants used for specifying which link types to find and render * * @var int */ const RENDER_ALTERNATE = 0x0001; const RENDER_STYLESHEET = 0x0002; const RENDER_START = 0x0004; const RENDER_NEXT = 0x0008; const RENDER_PREV = 0x0010; const RENDER_CONTENTS = 0x0020; const RENDER_INDEX = 0x0040; const RENDER_GLOSSARY = 0x0080; const RENDER_COPYRIGHT = 0x0100; const RENDER_CHAPTER = 0x0200; const RENDER_SECTION = 0x0400; const RENDER_SUBSECTION = 0x0800; const RENDER_APPENDIX = 0x1000; const RENDER_HELP = 0x2000; const RENDER_BOOKMARK = 0x4000; const RENDER_CUSTOM = 0x8000; const RENDER_ALL = 0xffff; /** * Maps render constants to W3C link types * * @var array */ protected static $RELATIONS = array( self::RENDER_ALTERNATE => 'alternate', self::RENDER_STYLESHEET => 'stylesheet', self::RENDER_START => 'start', self::RENDER_NEXT => 'next', self::RENDER_PREV => 'prev', self::RENDER_CONTENTS => 'contents', self::RENDER_INDEX => 'index', self::RENDER_GLOSSARY => 'glossary', self::RENDER_COPYRIGHT => 'copyright', self::RENDER_CHAPTER => 'chapter', self::RENDER_SECTION => 'section', self::RENDER_SUBSECTION => 'subsection', self::RENDER_APPENDIX => 'appendix', self::RENDER_HELP => 'help', self::RENDER_BOOKMARK => 'bookmark', ); /** * The helper's render flag * * @see render() * @see setRenderFlag() * @var int */ protected $renderFlag = self::RENDER_ALL; /** * Root container * * Used for preventing methods to traverse above the container given to * the {@link render()} method. * * @see _findRoot() * @var AbstractContainer */ protected $root; /** * Helper entry point * * @param string|AbstractContainer $container container to operate on * @return Links */ public function __invoke($container = null) { if (null !== $container) { $this->setContainer($container); } return $this; } /** * Magic overload: Proxy calls to {@link findRelation()} or container * * Examples of finder calls: * <code> * // METHOD // SAME AS * $h->findRelNext($page); // $h->findRelation($page, 'rel', 'next') * $h->findRevSection($page); // $h->findRelation($page, 'rev', 'section'); * $h->findRelFoo($page); // $h->findRelation($page, 'rel', 'foo'); * </code> * * @param string $method * @param array $arguments * @return mixed * @throws Exception\ExceptionInterface */ public function __call($method, array $arguments = array()) { ErrorHandler::start(E_WARNING); $result = preg_match('/find(Rel|Rev)(.+)/', $method, $match); ErrorHandler::stop(); if ($result) { return $this->findRelation($arguments[0], strtolower($match[1]), strtolower($match[2])); } return parent::__call($method, $arguments); } /** * Renders helper * * Implements {@link HelperInterface::render()}. * * @param AbstractContainer|string|null $container [optional] container to render. * Default is to render the * container registered in the * helper. * @return string */ public function render($container = null) { $this->parseContainer($container); if (null === $container) { $container = $this->getContainer(); } $active = $this->findActive($container); if ($active) { $active = $active['page']; } else { // no active page return ''; } $output = ''; $indent = $this->getIndent(); $this->root = $container; $result = $this->findAllRelations($active, $this->getRenderFlag()); foreach ($result as $attrib => $types) { foreach ($types as $relation => $pages) { foreach ($pages as $page) { $r = $this->renderLink($page, $attrib, $relation); if ($r) { $output .= $indent . $r . self::EOL; } } } } $this->root = null; // return output (trim last newline by spec) return strlen($output) ? rtrim($output, self::EOL) : ''; } /** * Renders the given $page as a link element, with $attrib = $relation * * @param AbstractPage $page the page to render the link for * @param string $attrib the attribute to use for $type, * either 'rel' or 'rev' * @param string $relation relation type, muse be one of; * alternate, appendix, bookmark, * chapter, contents, copyright, * glossary, help, home, index, next, * prev, section, start, stylesheet, * subsection * @return string * @throws Exception\DomainException */ public function renderLink(AbstractPage $page, $attrib, $relation) { if (!in_array($attrib, array('rel', 'rev'))) { throw new Exception\DomainException(sprintf( 'Invalid relation attribute "%s", must be "rel" or "rev"', $attrib )); } if (!$href = $page->getHref()) { return ''; } // TODO: add more attribs // http://www.w3.org/TR/html401/struct/links.html#h-12.2 $attribs = array( $attrib => $relation, 'href' => $href, 'title' => $page->getLabel() ); return '<link' . $this->htmlAttribs($attribs) . $this->getClosingBracket(); } // Finder methods: /** * Finds all relations (forward and reverse) for the given $page * * The form of the returned array: * <code> * // $page denotes an instance of Zend\Navigation\Page\AbstractPage * $returned = array( * 'rel' => array( * 'alternate' => array($page, $page, $page), * 'start' => array($page), * 'next' => array($page), * 'prev' => array($page), * 'canonical' => array($page) * ), * 'rev' => array( * 'section' => array($page) * ) * ); * </code> * * @param AbstractPage $page page to find links for * @param null|int * @return array */ public function findAllRelations(AbstractPage $page, $flag = null) { if (!is_int($flag)) { $flag = self::RENDER_ALL; } $result = array('rel' => array(), 'rev' => array()); $native = array_values(static::$RELATIONS); foreach (array_keys($result) as $rel) { $meth = 'getDefined' . ucfirst($rel); $types = array_merge($native, array_diff($page->$meth(), $native)); foreach ($types as $type) { if (!$relFlag = array_search($type, static::$RELATIONS)) { $relFlag = self::RENDER_CUSTOM; } if (!($flag & $relFlag)) { continue; } $found = $this->findRelation($page, $rel, $type); if ($found) { if (!is_array($found)) { $found = array($found); } $result[$rel][$type] = $found; } } } return $result; } /** * Finds relations of the given $rel=$type from $page * * This method will first look for relations in the page instance, then * by searching the root container if nothing was found in the page. * * @param AbstractPage $page page to find relations for * @param string $rel relation, "rel" or "rev" * @param string $type link type, e.g. 'start', 'next' * @return AbstractPage|array|null * @throws Exception\DomainException if $rel is not "rel" or "rev" */ public function findRelation(AbstractPage $page, $rel, $type) { if (!in_array($rel, array('rel', 'rev'))) { throw new Exception\DomainException(sprintf( 'Invalid argument: $rel must be "rel" or "rev"; "%s" given', $rel )); } if (!$result = $this->findFromProperty($page, $rel, $type)) { $result = $this->findFromSearch($page, $rel, $type); } return $result; } /** * Finds relations of given $type for $page by checking if the * relation is specified as a property of $page * * @param AbstractPage $page page to find relations for * @param string $rel relation, 'rel' or 'rev' * @param string $type link type, e.g. 'start', 'next' * @return AbstractPage|array|null */ protected function findFromProperty(AbstractPage $page, $rel, $type) { $method = 'get' . ucfirst($rel); $result = $page->$method($type); if ($result) { $result = $this->convertToPages($result); if ($result) { if (!is_array($result)) { $result = array($result); } foreach ($result as $key => $page) { if (!$this->accept($page)) { unset($result[$key]); } } return count($result) == 1 ? $result[0] : $result; } } return null; } /** * Finds relations of given $rel=$type for $page by using the helper to * search for the relation in the root container * * @param AbstractPage $page page to find relations for * @param string $rel relation, 'rel' or 'rev' * @param string $type link type, e.g. 'start', 'next', etc * @return array|null */ protected function findFromSearch(AbstractPage $page, $rel, $type) { $found = null; $method = 'search' . ucfirst($rel) . ucfirst($type); if (method_exists($this, $method)) { $found = $this->$method($page); } return $found; } // Search methods: /** * Searches the root container for the forward 'start' relation of the given * $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to the first document in a collection of documents. This link type * tells search engines which document is considered by the author to be the * starting point of the collection. * * @param AbstractPage $page * @return AbstractPage|null */ public function searchRelStart(AbstractPage $page) { $found = $this->findRoot($page); if (!$found instanceof AbstractPage) { $found->rewind(); $found = $found->current(); } if ($found === $page || !$this->accept($found)) { $found = null; } return $found; } /** * Searches the root container for the forward 'next' relation of the given * $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to the next document in a linear sequence of documents. User * agents may choose to preload the "next" document, to reduce the perceived * load time. * * @param AbstractPage $page * @return AbstractPage|null */ public function searchRelNext(AbstractPage $page) { $found = null; $break = false; $iterator = new RecursiveIteratorIterator($this->findRoot($page), RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $intermediate) { if ($intermediate === $page) { // current page; break at next accepted page $break = true; continue; } if ($break && $this->accept($intermediate)) { $found = $intermediate; break; } } return $found; } /** * Searches the root container for the forward 'prev' relation of the given * $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to the previous document in an ordered series of documents. Some * user agents also support the synonym "Previous". * * @param AbstractPage $page * @return AbstractPage|null */ public function searchRelPrev(AbstractPage $page) { $found = null; $prev = null; $iterator = new RecursiveIteratorIterator( $this->findRoot($page), RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $intermediate) { if (!$this->accept($intermediate)) { continue; } if ($intermediate === $page) { $found = $prev; break; } $prev = $intermediate; } return $found; } /** * Searches the root container for forward 'chapter' relations of the given * $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to a document serving as a chapter in a collection of documents. * * @param AbstractPage $page * @return AbstractPage|array|null */ public function searchRelChapter(AbstractPage $page) { $found = array(); // find first level of pages $root = $this->findRoot($page); // find start page(s) $start = $this->findRelation($page, 'rel', 'start'); if (!is_array($start)) { $start = array($start); } foreach ($root as $chapter) { // exclude self and start page from chapters if ($chapter !== $page && !in_array($chapter, $start) && $this->accept($chapter)) { $found[] = $chapter; } } switch (count($found)) { case 0: return null; case 1: return $found[0]; default: return $found; } } /** * Searches the root container for forward 'section' relations of the given * $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to a document serving as a section in a collection of documents. * * @param AbstractPage $page * @return AbstractPage|array|null */ public function searchRelSection(AbstractPage $page) { $found = array(); // check if given page has pages and is a chapter page if ($page->hasPages() && $this->findRoot($page)->hasPage($page)) { foreach ($page as $section) { if ($this->accept($section)) { $found[] = $section; } } } switch (count($found)) { case 0: return null; case 1: return $found[0]; default: return $found; } } /** * Searches the root container for forward 'subsection' relations of the * given $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to a document serving as a subsection in a collection of * documents. * * @param AbstractPage $page * @return AbstractPage|array|null */ public function searchRelSubsection(AbstractPage $page) { $found = array(); if ($page->hasPages()) { // given page has child pages, loop chapters foreach ($this->findRoot($page) as $chapter) { // is page a section? if ($chapter->hasPage($page)) { foreach ($page as $subsection) { if ($this->accept($subsection)) { $found[] = $subsection; } } } } } switch (count($found)) { case 0: return null; case 1: return $found[0]; default: return $found; } } /** * Searches the root container for the reverse 'section' relation of the * given $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to a document serving as a section in a collection of documents. * * @param AbstractPage $page * @return AbstractPage|null */ public function searchRevSection(AbstractPage $page) { $found = null; $parent = $page->getParent(); if ($parent) { if ($parent instanceof AbstractPage && $this->findRoot($page)->hasPage($parent)) { $found = $parent; } } return $found; } /** * Searches the root container for the reverse 'section' relation of the * given $page * * From {@link http://www.w3.org/TR/html4/types.html#type-links}: * Refers to a document serving as a subsection in a collection of * documents. * * @param AbstractPage $page * @return AbstractPage|null */ public function searchRevSubsection(AbstractPage $page) { $found = null; $parent = $page->getParent(); if ($parent) { if ($parent instanceof AbstractPage) { $root = $this->findRoot($page); foreach ($root as $chapter) { if ($chapter->hasPage($parent)) { $found = $parent; break; } } } } return $found; } // Util methods: /** * Returns the root container of the given page * * When rendering a container, the render method still store the given * container as the root container, and unset it when done rendering. This * makes sure finder methods will not traverse above the container given * to the render method. * * @param AbstractPage $page * @return AbstractContainer */ protected function findRoot(AbstractPage $page) { if ($this->root) { return $this->root; } $root = $page; while ($parent = $page->getParent()) { $root = $parent; if ($parent instanceof AbstractPage) { $page = $parent; } else { break; } } return $root; } /** * Converts a $mixed value to an array of pages * * @param mixed $mixed mixed value to get page(s) from * @param bool $recursive whether $value should be looped * if it is an array or a config * @return AbstractPage|array|null */ protected function convertToPages($mixed, $recursive = true) { if ($mixed instanceof AbstractPage) { // value is a page instance; return directly return $mixed; } elseif ($mixed instanceof AbstractContainer) { // value is a container; return pages in it $pages = array(); foreach ($mixed as $page) { $pages[] = $page; } return $pages; } elseif ($mixed instanceof Traversable) { $mixed = ArrayUtils::iteratorToArray($mixed); } elseif (is_string($mixed)) { // value is a string; make a URI page return AbstractPage::factory(array( 'type' => 'uri', 'uri' => $mixed )); } if (is_array($mixed) && !empty($mixed)) { if ($recursive && is_numeric(key($mixed))) { // first key is numeric; assume several pages $pages = array(); foreach ($mixed as $value) { $value = $this->convertToPages($value, false); if ($value) { $pages[] = $value; } } return $pages; } else { // pass array to factory directly try { $page = AbstractPage::factory($mixed); return $page; } catch (\Exception $e) { } } } // nothing found return null; } /** * Sets the helper's render flag * * The helper uses the bitwise '&' operator against the hex values of the * render constants. This means that the flag can is "bitwised" value of * the render constants. Examples: * <code> * // render all links except glossary * $flag = Links:RENDER_ALL ^ Links:RENDER_GLOSSARY; * $helper->setRenderFlag($flag); * * // render only chapters and sections * $flag = Links:RENDER_CHAPTER | Links:RENDER_SECTION; * $helper->setRenderFlag($flag); * * // render only relations that are not native W3C relations * $helper->setRenderFlag(Links:RENDER_CUSTOM); * * // render all relations (default) * $helper->setRenderFlag(Links:RENDER_ALL); * </code> * * Note that custom relations can also be rendered directly using the * {@link renderLink()} method. * * @param int $renderFlag * @return Links */ public function setRenderFlag($renderFlag) { $this->renderFlag = (int) $renderFlag; return $this; } /** * Returns the helper's render flag * * @return int */ public function getRenderFlag() { return $this->renderFlag; } }
bsd-3-clause
darkrsw/safe
tests/typing_tests/TAJS_micro/test102.js
516
var i = 0; var j = 799; //dumpValue(i); var __result1 = i; // for SAFE var __expect1 = 0.0; // for SAFE //dumpValue(j); var __result2 = j; // for SAFE var __expect2 = 799.0; // for SAFE while (i <= j) { // dumpValue("foo"); var __result3 = "foo"; // for SAFE i++; } var __expect3 = "foo"; // for SAFE //dumpValue(i); var __result4 = i; // for SAFE var __expect4 = 800.0; // for SAFE //dumpValue("bar"); var __result5 = "bar"; // for SAFE var __expect5 = "bar"; // for SAFE
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_82_bad.cpp
1418
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_82_bad.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml Template File: sources-sink-82_bad.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sinks: memcpy * BadSink : Copy string to data using memcpy * Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_82.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_82 { void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_memcpy_82_bad::action(wchar_t * data) { { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ memcpy(data, source, 100*sizeof(wchar_t)); data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); delete [] data; } } } #endif /* OMITBAD */
bsd-3-clause
cyhalothrin/yii2-rbac
src/views/users/_assign-role-form.php
543
<?php use arogachev\rbac\components\Rbac; use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model arogachev\rbac\models\AssignRoleToUserForm */ /* @var $form yii\widgets\ActiveForm */ ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'role')->dropDownList(Rbac::getRolesMap(), [ 'prompt' => Yii::t('rbac', 'Without role'), ]) ?> <div class="form-group"> <?= Html::submitButton(Yii::t('rbac', 'Assign'), ['class' => 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?>
bsd-3-clause
NCIP/cadsr-semantic-tools
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/PreferenceDialog.java
7779
/* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.util.*; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; /** * Dialog displaying all configurable User Preferences. * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class PreferenceDialog extends JDialog implements ActionListener { private JCheckBox associationBox = new JCheckBox(PropertyAccessor.getProperty("preference.view.association")), umlDescriptionBox = new JCheckBox(PropertyAccessor.getProperty("preference.uml.description")), evsAutoSearchBox = new JCheckBox(PropertyAccessor.getProperty("preference.auto.evs")), privateApiSearchBox = new JCheckBox(PropertyAccessor.getProperty("preference.private.api")), orderOfConceptsBox = new JCheckBox(PropertyAccessor.getProperty("preference.concept.order")), showInheritedAttributesBox = new JCheckBox(PropertyAccessor.getProperty("preference.inherited.attributes")), sortElementsBox = new JCheckBox(PropertyAccessor.getProperty("preference.sort.elements")), preTBox = new JCheckBox(PropertyAccessor.getProperty("preference.concept.validator.preT")), inheritedCDEMappingBox = new JCheckBox(PropertyAccessor.getProperty("preference.inherited.cde.warning")), showGMETagsBox = new JCheckBox(PropertyAccessor.getProperty("show.gme.tags")), showConceptCodeAndNameSummaryBox = new JCheckBox(PropertyAccessor.getProperty("show.concept.code.name.summary")); private JButton apply = new JButton("Apply"); private JButton cancel = new JButton("Cancel"); private JButton ok = new JButton("OK"); private static final String APPLY = "Apply"; private static final String CANCEL = "Cancel"; private static final String OK = "OK"; public PreferenceDialog(JFrame owner) { super(owner, "Preferences"); JPanel southPanel = new JPanel(); southPanel.add(ok); southPanel.add(cancel); southPanel.add(apply); JPanel centerPanel = new JPanel(); centerPanel.add(associationBox); centerPanel.add(umlDescriptionBox); centerPanel.add(evsAutoSearchBox); // centerPanel.add(privateApiSearchBox); centerPanel.add(orderOfConceptsBox); centerPanel.add(showInheritedAttributesBox); centerPanel.add(sortElementsBox); centerPanel.add(preTBox); centerPanel.add(inheritedCDEMappingBox); centerPanel.add(showGMETagsBox); centerPanel.add(showConceptCodeAndNameSummaryBox); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(centerPanel); this.getContentPane().add(southPanel,BorderLayout.SOUTH); this.setSize(300,400); apply.setActionCommand(APPLY); cancel.setActionCommand(CANCEL); ok.setActionCommand(OK); apply.addActionListener(this); cancel.addActionListener(this); ok.addActionListener(this); UserSelections selections = UserSelections.getInstance(); RunMode runMode = (RunMode)(selections.getProperty("MODE")); if(runMode.equals(RunMode.Curator)) { associationBox.setVisible(false); } } public void updatePreferences() { UserPreferences prefs = UserPreferences.getInstance(); associationBox.setSelected(prefs.getViewAssociationType().equalsIgnoreCase("true")); umlDescriptionBox.setSelected(!prefs.getUmlDescriptionOrder().equals("first")); orderOfConceptsBox.setSelected(prefs.getOrderOfConcepts().equalsIgnoreCase("first")); evsAutoSearchBox.setSelected(prefs.getEvsAutoSearch()); privateApiSearchBox.setSelected(prefs.isUsePrivateApi()); showInheritedAttributesBox.setSelected(prefs.getShowInheritedAttributes()); sortElementsBox.setSelected(prefs.getSortElements()); preTBox.setSelected(prefs.getPreTBox()); inheritedCDEMappingBox.setSelected(prefs.getBoolean("de.over.vd.mapping.warning")); showGMETagsBox.setSelected(prefs.getShowGMETags()); showConceptCodeAndNameSummaryBox.setSelected(prefs.getShowConceptCodeNameSummary()); } public void actionPerformed(ActionEvent event) { JButton button = (JButton)event.getSource(); if(button.getActionCommand().equals(OK) || button.getActionCommand().equals(APPLY)) { UserPreferences prefs = UserPreferences.getInstance(); if(associationBox.isSelected()) prefs.setViewAssociationType("true"); else prefs.setViewAssociationType("false"); if(umlDescriptionBox.isSelected()) prefs.setUmlDescriptionOrder("last"); else prefs.setUmlDescriptionOrder("first"); if(orderOfConceptsBox.isSelected()) prefs.setOrderOfConcepts("first"); else prefs.setOrderOfConcepts("last"); prefs.setEvsAutoSeatch(evsAutoSearchBox.isSelected()); prefs.setUsePrivateApi(privateApiSearchBox.isSelected()); prefs.setShowInheritedAttributes(showInheritedAttributesBox.isSelected()); prefs.setSortElements(sortElementsBox.isSelected()); prefs.setPreTBox(preTBox.isSelected()); prefs.setBoolean("de.over.vd.mapping.warning", inheritedCDEMappingBox.isSelected()); prefs.setShowGMETags(showGMETagsBox.isSelected()); prefs.setShowConceptCodeNameSummary(showConceptCodeAndNameSummaryBox.isSelected()); if(button.getActionCommand().equals(OK)) this.dispose(); } if(button.getActionCommand().equals(CANCEL)) this.dispose(); } }
bsd-3-clause
codeactual/mockery
mockery/fixtures/same_name_imports.go
209
package test import ( "net/http" my_http "github.com/vektra/mockery/mockery/fixtures/http" ) // Example is an example type Example interface { A() http.Flusher B(fixtureshttp string) my_http.MyStruct }
bsd-3-clause
ArxdSilva/tsuru-client
vendor/github.com/tsuru/tsuru/app/platform.go
4471
// Copyright 2013 tsuru authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package app import ( "strconv" "github.com/pkg/errors" "github.com/tsuru/tsuru/db" tsuruErrors "github.com/tsuru/tsuru/errors" "github.com/tsuru/tsuru/log" "github.com/tsuru/tsuru/provision" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Platform struct { Name string `bson:"_id"` Disabled bool `bson:",omitempty"` } var ( ErrPlatformNameMissing = errors.New("Platform name is required.") ErrPlatformNotFound = errors.New("Platform doesn't exist.") DuplicatePlatformError = errors.New("Duplicate platform") InvalidPlatformError = errors.New("Invalid platform") ErrDeletePlatformWithApps = errors.New("Platform has apps. You should remove them before remove the platform.") ) // Platforms returns the list of available platforms. func Platforms(enabledOnly bool) ([]Platform, error) { var platforms []Platform conn, err := db.Conn() if err != nil { return nil, err } defer conn.Close() var query bson.M if enabledOnly { query = bson.M{"$or": []bson.M{{"disabled": false}, {"disabled": bson.M{"$exists": false}}}} } err = conn.Platforms().Find(query).All(&platforms) return platforms, err } // PlatformAdd add a new platform to tsuru func PlatformAdd(opts provision.PlatformOptions) error { if opts.Name == "" { return ErrPlatformNameMissing } provisioners, err := provision.Registry() if err != nil { return err } p := Platform{Name: opts.Name} conn, err := db.Conn() if err != nil { return err } defer conn.Close() err = conn.Platforms().Insert(p) if err != nil { if mgo.IsDup(err) { return DuplicatePlatformError } return err } for _, p := range provisioners { if extensibleProv, ok := p.(provision.ExtensibleProvisioner); ok { err = extensibleProv.PlatformAdd(opts) if err != nil { break } } } if err != nil { dbErr := conn.Platforms().RemoveId(p.Name) if dbErr != nil { return tsuruErrors.NewMultiError( errors.Wrapf(dbErr, "unable to rollback platform add"), errors.Wrapf(err, "original platform add error"), ) } return err } return nil } func PlatformUpdate(opts provision.PlatformOptions) error { provisioners, err := provision.Registry() if err != nil { return err } var platform Platform if opts.Name == "" { return ErrPlatformNameMissing } conn, err := db.Conn() if err != nil { return err } defer conn.Close() err = conn.Platforms().Find(bson.M{"_id": opts.Name}).One(&platform) if err != nil { if err == mgo.ErrNotFound { return ErrPlatformNotFound } return err } if opts.Args["dockerfile"] != "" || opts.Input != nil { for _, p := range provisioners { if extensibleProv, ok := p.(provision.ExtensibleProvisioner); ok { err = extensibleProv.PlatformUpdate(opts) if err != nil { return err } } } var apps []App err = conn.Apps().Find(bson.M{"framework": opts.Name}).All(&apps) if err != nil { return err } for _, app := range apps { app.SetUpdatePlatform(true) } } if opts.Args["disabled"] != "" { disableBool, err := strconv.ParseBool(opts.Args["disabled"]) if err != nil { return err } err = conn.Platforms().Update(bson.M{"_id": opts.Name}, bson.M{"$set": bson.M{"disabled": disableBool}}) if err != nil { return err } } return nil } func PlatformRemove(name string) error { provisioners, err := provision.Registry() if err != nil { return err } if name == "" { return ErrPlatformNameMissing } conn, err := db.Conn() if err != nil { return err } defer conn.Close() apps, _ := conn.Apps().Find(bson.M{"framework": name}).Count() if apps > 0 { return ErrDeletePlatformWithApps } for _, p := range provisioners { if extensibleProv, ok := p.(provision.ExtensibleProvisioner); ok { err = extensibleProv.PlatformRemove(name) if err != nil { log.Errorf("Failed to remove platform from provisioner %q: %s", p.GetName(), err) } } } err = conn.Platforms().Remove(bson.M{"_id": name}) if err == mgo.ErrNotFound { return ErrPlatformNotFound } return err } func GetPlatform(name string) (*Platform, error) { var p Platform conn, err := db.Conn() if err != nil { return nil, err } defer conn.Close() err = conn.Platforms().Find(bson.M{"_id": name}).One(&p) if err != nil { return nil, InvalidPlatformError } return &p, nil }
bsd-3-clause
DaanBiesterbos/zend-code
test/Generator/ClassGeneratorTest.php
35540
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Code\Generator; use ReflectionMethod; use Zend\Code\Generator\ClassGenerator; use Zend\Code\Generator\DocBlockGenerator; use Zend\Code\Generator\PropertyGenerator; use Zend\Code\Generator\MethodGenerator; use Zend\Code\Reflection\ClassReflection; /** * @group Zend_Code_Generator * @group Zend_Code_Generator_Php */ class ClassGeneratorTest extends \PHPUnit_Framework_TestCase { public function testConstruction() { $class = new ClassGenerator(); $this->isInstanceOf($class, 'Zend\Code\Generator\ClassGenerator'); } public function testNameAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->setName('TestClass'); $this->assertEquals($classGenerator->getName(), 'TestClass'); } public function testClassDocBlockAccessors() { $docBlockGenerator = new DocBlockGenerator(); $classGenerator = new ClassGenerator(); $classGenerator->setDocBlock($docBlockGenerator); $this->assertSame($docBlockGenerator, $classGenerator->getDocBlock()); } public function testAbstractAccessors() { $classGenerator = new ClassGenerator(); $this->assertFalse($classGenerator->isAbstract()); $classGenerator->setAbstract(true); $this->assertTrue($classGenerator->isAbstract()); } public function testExtendedClassAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->setExtendedClass('ExtendedClass'); $this->assertEquals($classGenerator->getExtendedClass(), 'ExtendedClass'); } public function testImplementedInterfacesAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->setImplementedInterfaces(array('Class1', 'Class2')); $this->assertEquals($classGenerator->getImplementedInterfaces(), array('Class1', 'Class2')); } public function testPropertyAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->addProperties(array( 'propOne', new PropertyGenerator('propTwo') )); $properties = $classGenerator->getProperties(); $this->assertEquals(count($properties), 2); $this->assertInstanceOf('Zend\Code\Generator\PropertyGenerator', current($properties)); $property = $classGenerator->getProperty('propTwo'); $this->assertInstanceOf('Zend\Code\Generator\PropertyGenerator', $property); $this->assertEquals($property->getName(), 'propTwo'); // add a new property $classGenerator->addProperty('prop3'); $this->assertEquals(count($classGenerator->getProperties()), 3); } public function testSetPropertyAlreadyExistsThrowsException() { $classGenerator = new ClassGenerator(); $classGenerator->addProperty('prop3'); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'A property by name prop3 already exists in this class' ); $classGenerator->addProperty('prop3'); } public function testSetPropertyNoArrayOrPropertyThrowsException() { $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Zend\Code\Generator\ClassGenerator::addProperty expects string for name' ); $classGenerator->addProperty(true); } public function testMethodAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->addMethods(array( 'methodOne', new MethodGenerator('methodTwo') )); $methods = $classGenerator->getMethods(); $this->assertEquals(count($methods), 2); $this->isInstanceOf(current($methods), '\Zend\Code\Generator\PhpMethod'); $method = $classGenerator->getMethod('methodOne'); $this->isInstanceOf($method, '\Zend\Code\Generator\PhpMethod'); $this->assertEquals($method->getName(), 'methodOne'); // add a new property $classGenerator->addMethod('methodThree'); $this->assertEquals(count($classGenerator->getMethods()), 3); } public function testSetMethodNoMethodOrArrayThrowsException() { $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\ExceptionInterface', 'Zend\Code\Generator\ClassGenerator::addMethod expects string for name' ); $classGenerator->addMethod(true); } public function testSetMethodNameAlreadyExistsThrowsException() { $methodA = new MethodGenerator(); $methodA->setName("foo"); $methodB = new MethodGenerator(); $methodB->setName("foo"); $classGenerator = new ClassGenerator(); $classGenerator->addMethodFromGenerator($methodA); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'A method by name foo already exists in this class.' ); $classGenerator->addMethodFromGenerator($methodB); } /** * @group ZF-7361 */ public function testHasMethod() { $classGenerator = new ClassGenerator(); $classGenerator->addMethod('methodOne'); $this->assertTrue($classGenerator->hasMethod('methodOne')); } public function testRemoveMethod() { $classGenerator = new ClassGenerator(); $classGenerator->addMethod('methodOne'); $this->assertTrue($classGenerator->hasMethod('methodOne')); $classGenerator->removeMethod('methodOne'); $this->assertFalse($classGenerator->hasMethod('methodOne')); } /** * @group ZF-7361 */ public function testHasProperty() { $classGenerator = new ClassGenerator(); $classGenerator->addProperty('propertyOne'); $this->assertTrue($classGenerator->hasProperty('propertyOne')); } public function testToString() { $classGenerator = ClassGenerator::fromArray(array( 'name' => 'SampleClass', 'flags' => ClassGenerator::FLAG_ABSTRACT, 'extendedClass' => 'ExtendedClassName', 'implementedInterfaces' => array('Iterator', 'Traversable'), 'properties' => array('foo', array('name' => 'bar') ), 'methods' => array( array('name' => 'baz') ), )); $expectedOutput = <<<EOS abstract class SampleClass extends ExtendedClassName implements Iterator, Traversable { public \$foo = null; public \$bar = null; public function baz() { } } EOS; $output = $classGenerator->generate(); $this->assertEquals($expectedOutput, $output, $output); } /** * @group ZF-7909 */ public function testClassFromReflectionThatImplementsInterfaces() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\ClassWithInterface'); $classGenerator = ClassGenerator::fromReflection($reflClass); $classGenerator->setSourceDirty(true); $code = $classGenerator->generate(); $expectedClassDef = 'class ClassWithInterface' . ' implements ZendTest\Code\Generator\TestAsset\OneInterface' . ', ZendTest\Code\Generator\TestAsset\TwoInterface'; $this->assertContains($expectedClassDef, $code); } /** * @group ZF-7909 */ public function testClassFromReflectionDiscardParentImplementedInterfaces() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\NewClassWithInterface'); $classGenerator = ClassGenerator::fromReflection($reflClass); $classGenerator->setSourceDirty(true); $code = $classGenerator->generate(); $expectedClassDef = 'class NewClassWithInterface' . ' extends ZendTest\Code\Generator\TestAsset\ClassWithInterface' . ' implements ZendTest\Code\Generator\TestAsset\ThreeInterface'; $this->assertContains($expectedClassDef, $code); } /** * @group 4988 */ public function testNonNamespaceClassReturnsAllMethods() { require_once __DIR__ . '/../TestAsset/NonNamespaceClass.php'; $reflClass = new ClassReflection('ZendTest_Code_NsTest_BarClass'); $classGenerator = ClassGenerator::fromReflection($reflClass); $this->assertCount(1, $classGenerator->getMethods()); } /** * @group ZF-9602 */ public function testSetextendedclassShouldIgnoreEmptyClassnameOnGenerate() { $classGeneratorClass = new ClassGenerator(); $classGeneratorClass ->setName('MyClass') ->setExtendedClass(''); $expected = <<<CODE class MyClass { } CODE; $this->assertEquals($expected, $classGeneratorClass->generate()); } /** * @group ZF-9602 */ public function testSetextendedclassShouldNotIgnoreNonEmptyClassnameOnGenerate() { $classGeneratorClass = new ClassGenerator(); $classGeneratorClass ->setName('MyClass') ->setExtendedClass('ParentClass'); $expected = <<<CODE class MyClass extends ParentClass { } CODE; $this->assertEquals($expected, $classGeneratorClass->generate()); } /** * @group namespace */ public function testCodeGenerationShouldTakeIntoAccountNamespacesFromReflection() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\ClassWithNamespace'); $classGenerator = ClassGenerator::fromReflection($reflClass); $this->assertEquals('ZendTest\Code\Generator\TestAsset', $classGenerator->getNamespaceName()); $this->assertEquals('ClassWithNamespace', $classGenerator->getName()); $expected = <<<CODE namespace ZendTest\Code\Generator\\TestAsset; class ClassWithNamespace { } CODE; $received = $classGenerator->generate(); $this->assertEquals($expected, $received, $received); } /** * @group namespace */ public function testSetNameShouldDetermineIfNamespaceSegmentIsPresent() { $classGeneratorClass = new ClassGenerator(); $classGeneratorClass->setName('My\Namespaced\FunClass'); $this->assertEquals('My\Namespaced', $classGeneratorClass->getNamespaceName()); } /** * @group namespace */ public function testPassingANamespacedClassnameShouldGenerateANamespaceDeclaration() { $classGeneratorClass = new ClassGenerator(); $classGeneratorClass->setName('My\Namespaced\FunClass'); $received = $classGeneratorClass->generate(); $this->assertContains('namespace My\Namespaced;', $received, $received); } /** * @group namespace */ public function testPassingANamespacedClassnameShouldGenerateAClassnameWithoutItsNamespace() { $classGeneratorClass = new ClassGenerator(); $classGeneratorClass->setName('My\Namespaced\FunClass'); $received = $classGeneratorClass->generate(); $this->assertContains('class FunClass', $received, $received); } /** * @group ZF2-151 */ public function testAddUses() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\Class'); $classGenerator->addUse('My\First\Use\Class'); $classGenerator->addUse('My\Second\Use\Class', 'MyAlias'); $generated = $classGenerator->generate(); $this->assertContains('use My\First\Use\Class;', $generated); $this->assertContains('use My\Second\Use\Class as MyAlias;', $generated); } /** * @group 4990 */ public function testAddOneUseTwiceOnlyAddsOne() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\Class'); $classGenerator->addUse('My\First\Use\Class'); $classGenerator->addUse('My\First\Use\Class'); $generated = $classGenerator->generate(); $this->assertCount(1, $classGenerator->getUses()); $this->assertContains('use My\First\Use\Class;', $generated); } /** * @group 4990 */ public function testAddOneUseWithAliasTwiceOnlyAddsOne() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\Class'); $classGenerator->addUse('My\First\Use\Class', 'MyAlias'); $classGenerator->addUse('My\First\Use\Class', 'MyAlias'); $generated = $classGenerator->generate(); $this->assertCount(1, $classGenerator->getUses()); $this->assertContains('use My\First\Use\Class as MyAlias;', $generated); } public function testCreateFromArrayWithDocBlockFromArray() { $classGenerator = ClassGenerator::fromArray(array( 'name' => 'SampleClass', 'docblock' => array( 'shortdescription' => 'foo', ), )); $docBlock = $classGenerator->getDocBlock(); $this->assertInstanceOf('Zend\Code\Generator\DocBlockGenerator', $docBlock); } public function testCreateFromArrayWithDocBlockInstance() { $classGenerator = ClassGenerator::fromArray(array( 'name' => 'SampleClass', 'docblock' => new DocBlockGenerator('foo'), )); $docBlock = $classGenerator->getDocBlock(); $this->assertInstanceOf('Zend\Code\Generator\DocBlockGenerator', $docBlock); } public function testExtendedClassProperies() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\ExtendedClassWithProperties'); $classGenerator = ClassGenerator::fromReflection($reflClass); $code = $classGenerator->generate(); $this->assertContains('publicExtendedClassProperty', $code); $this->assertContains('protectedExtendedClassProperty', $code); $this->assertContains('privateExtendedClassProperty', $code); $this->assertNotContains('publicClassProperty', $code); $this->assertNotContains('protectedClassProperty', $code); $this->assertNotContains('privateClassProperty', $code); } public function testHasMethodInsensitive() { $classGenerator = new ClassGenerator(); $classGenerator->addMethod('methodOne'); $this->assertTrue($classGenerator->hasMethod('methodOne')); $this->assertTrue($classGenerator->hasMethod('MethoDonE')); } public function testRemoveMethodInsensitive() { $classGenerator = new ClassGenerator(); $classGenerator->addMethod('methodOne'); $classGenerator->removeMethod('METHODONe'); $this->assertFalse($classGenerator->hasMethod('methodOne')); } public function testGenerateClassAndAddMethod() { $classGenerator = new ClassGenerator(); $classGenerator->setName('MyClass'); $classGenerator->addMethod('methodOne'); $expected = <<<CODE class MyClass { public function methodOne() { } } CODE; $output = $classGenerator->generate(); $this->assertEquals($expected, $output); } /** * @group 6274 */ public function testCanAddConstant() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\Class'); $classGenerator->addConstant('x', 'value'); $this->assertTrue($classGenerator->hasConstant('x')); $constant = $classGenerator->getConstant('x'); $this->assertInstanceOf('Zend\Code\Generator\PropertyGenerator', $constant); $this->assertTrue($constant->isConst()); $this->assertEquals($constant->getDefaultValue()->getValue(), 'value'); } /** * @group 6274 */ public function testCanAddConstantsWithArrayOfGenerators() { $classGenerator = new ClassGenerator(); $classGenerator->addConstants(array( new PropertyGenerator('x', 'value1', PropertyGenerator::FLAG_CONSTANT), new PropertyGenerator('y', 'value2', PropertyGenerator::FLAG_CONSTANT) )); $this->assertCount(2, $classGenerator->getConstants()); $this->assertEquals($classGenerator->getConstant('x')->getDefaultValue()->getValue(), 'value1'); $this->assertEquals($classGenerator->getConstant('y')->getDefaultValue()->getValue(), 'value2'); } /** * @group 6274 */ public function testCanAddConstantsWithArrayOfKeyValues() { $classGenerator = new ClassGenerator(); $classGenerator->addConstants(array( array( 'name'=> 'x', 'value' => 'value1'), array('name' => 'y', 'value' => 'value2') )); $this->assertCount(2, $classGenerator->getConstants()); $this->assertEquals($classGenerator->getConstant('x')->getDefaultValue()->getValue(), 'value1'); $this->assertEquals($classGenerator->getConstant('y')->getDefaultValue()->getValue(), 'value2'); } /** * @group 6274 */ public function testAddConstantThrowsExceptionWithInvalidName() { $this->setExpectedException('InvalidArgumentException'); $classGenerator = new ClassGenerator(); $classGenerator->addConstant(array(), 'value1'); } /** * @group 6274 */ public function testAddConstantThrowsExceptionWithInvalidValue() { $this->setExpectedException('InvalidArgumentException'); $classGenerator = new ClassGenerator(); $classGenerator->addConstant('x', null); } /** * @group 6274 */ public function testAddConstantThrowsExceptionOnDuplicate() { $this->setExpectedException('InvalidArgumentException'); $classGenerator = new ClassGenerator(); $classGenerator->addConstant('x', 'value1'); $classGenerator->addConstant('x', 'value1'); } /** * @group 6274 */ public function testAddPropertyIsBackwardsCompatibleWithConstants() { $classGenerator = new ClassGenerator(); $classGenerator->addProperty('x', 'value1', PropertyGenerator::FLAG_CONSTANT); $this->assertEquals($classGenerator->getConstant('x')->getDefaultValue()->getValue(), 'value1'); } /** * @group 6274 */ public function testAddPropertiesIsBackwardsCompatibleWithConstants() { $constants = array( new PropertyGenerator('x', 'value1', PropertyGenerator::FLAG_CONSTANT), new PropertyGenerator('y', 'value2', PropertyGenerator::FLAG_CONSTANT) ); $classGenerator = new ClassGenerator(); $classGenerator->addProperties($constants); $this->assertCount(2, $classGenerator->getConstants()); $this->assertEquals($classGenerator->getConstant('x')->getDefaultValue()->getValue(), 'value1'); $this->assertEquals($classGenerator->getConstant('y')->getDefaultValue()->getValue(), 'value2'); } /** * @group 6274 */ public function testConstantsAddedFromReflection() { $reflector = new ClassReflection('ZendTest\Code\Generator\TestAsset\TestClassWithManyProperties'); $classGenerator = ClassGenerator::fromReflection($reflector); $constant = $classGenerator->getConstant('FOO'); $this->assertEquals($constant->getDefaultValue()->getValue(), 'foo'); } /** * @group 6274 */ public function testClassCanBeGeneratedWithConstantAndPropertyWithSameName() { $reflector = new ClassReflection('ZendTest\Code\Generator\TestAsset\TestSampleSingleClass'); $classGenerator = ClassGenerator::fromReflection($reflector); $classGenerator->addProperty('fooProperty', true, PropertyGenerator::FLAG_PUBLIC); $classGenerator->addConstant('fooProperty', 'duplicate'); $contents = <<<'CODE' namespace ZendTest\Code\Generator\TestAsset; /** * class docblock */ class TestSampleSingleClass { const fooProperty = 'duplicate'; public $fooProperty = true; /** * Enter description here... * * @return bool */ public function someMethod() { /* test test */ } } CODE; $this->assertEquals($classGenerator->generate(), $contents); } /** * @group 6253 */ public function testHereDoc() { $reflector = new ClassReflection('ZendTest\Code\Generator\TestAsset\TestClassWithHeredoc'); $classGenerator = new ClassGenerator(); $methods = $reflector->getMethods(); $classGenerator->setName("OutputClass"); foreach ($methods as $method) { $methodGenerator = MethodGenerator::fromReflection($method); $classGenerator->addMethodFromGenerator($methodGenerator); } $contents = <<< 'CODE' class OutputClass { public function someFunction() { $output = <<< END Fix it, fix it! Fix it, fix it! Fix it, fix it! END; } } CODE; $this->assertEquals($contents, $classGenerator->generate()); } public function testCanAddTraitWithString() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTrait('myTrait'); $this->assertTrue($classGenerator->hasTrait('myTrait')); } public function testCanAddTraitWithArray() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTrait(array('traitName' => 'myTrait')); $this->assertTrue($classGenerator->hasTrait('myTrait')); } public function testCanRemoveTrait() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTrait(array('traitName' => 'myTrait')); $this->assertTrue($classGenerator->hasTrait('myTrait')); $classGenerator->removeTrait('myTrait'); $this->assertFalse($classGenerator->hasTrait('myTrait')); } public function testCanGetTraitsMethod() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTraits(array('myTrait', 'hisTrait')); $traits = $classGenerator->getTraits(); $this->assertContains('myTrait', $traits); $this->assertContains('hisTrait', $traits); } public function testCanAddTraitAliasWithString() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('myTrait::method', 'useMe', ReflectionMethod::IS_PRIVATE); $aliases = $classGenerator->getTraitAliases(); $this->assertArrayHasKey('myTrait::method', $aliases); $this->assertEquals($aliases['myTrait::method']['alias'], 'useMe'); $this->assertEquals($aliases['myTrait::method']['visibility'], ReflectionMethod::IS_PRIVATE); } public function testCanAddTraitAliasWithArray() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias(array( 'traitName' => 'myTrait', 'method' => 'method', ), 'useMe', ReflectionMethod::IS_PRIVATE); $aliases = $classGenerator->getTraitAliases(); $this->assertArrayHasKey('myTrait::method', $aliases); $this->assertEquals($aliases['myTrait::method']['alias'], 'useMe'); $this->assertEquals($aliases['myTrait::method']['visibility'], ReflectionMethod::IS_PRIVATE); } public function testAddTraitAliasExceptionInvalidMethodFormat() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Format: $method must be in the format of trait::method' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('method', 'useMe'); } public function testAddTraitAliasExceptionInvalidMethodTraitDoesNotExist() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid trait: Trait does not exists on this class' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('unknown::method', 'useMe'); } public function testAddTraitAliasExceptionMethodAlreadyExists() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Alias: Method name already exists on this class.' ); $classGenerator->addMethod('methodOne'); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('myTrait::method', 'methodOne'); } public function testAddTraitAliasExceptionInvalidVisibilityValue() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Type: $visibility must of ReflectionMethod::IS_PUBLIC,' . ' ReflectionMethod::IS_PRIVATE or ReflectionMethod::IS_PROTECTED' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('myTrait::method', 'methodOne', 'public'); } public function testAddTraitAliasExceptionInvalidAliasArgument() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Alias: $alias must be a string or array.' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitAlias('myTrait::method', new ClassGenerator, 'public'); } public function testCanAddTraitOverride() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTraits(array('myTrait', 'histTrait')); $classGenerator->addTraitOverride('myTrait::foo', 'hisTrait'); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides), 1); $this->assertEquals(key($overrides), 'myTrait::foo'); $this->assertEquals($overrides['myTrait::foo'][0], 'hisTrait'); } public function testCanAddMultipleTraitOverrides() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTraits(array('myTrait', 'histTrait', 'thatTrait')); $classGenerator->addTraitOverride('myTrait::foo', array('hisTrait', 'thatTrait')); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides['myTrait::foo']), 2); $this->assertEquals($overrides['myTrait::foo'][1], 'thatTrait'); } public function testAddTraitOverrideExceptionInvalidMethodFormat() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Format: $method must be in the format of trait::method' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitOverride('method', 'useMe'); } public function testAddTraitOverrideExceptionInvalidMethodTraitDoesNotExist() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid trait: Trait does not exists on this class' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitOverride('unknown::method', 'useMe'); } public function testAddTraitOverrideExceptionInvalidTraitName() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Missing required argument "traitName" for $method' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitOverride(array('method' => 'foo'), 'test'); } public function testAddTraitOverrideExceptionInvalidTraitToReplaceArgument() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Invalid Argument: $traitToReplace must be a string or array of strings' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitOverride('myTrait::method', array('methodOne', 4)); } public function testAddTraitOverrideExceptionInvalidMethodArgInArray() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $this->setExpectedException( 'Zend\Code\Generator\Exception\InvalidArgumentException', 'Missing required argument "method" for $method' ); $classGenerator->addTrait('myTrait'); $classGenerator->addTraitOverride(array('traitName' => 'myTrait'), 'test'); } public function testCanRemoveTraitOverride() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTraits(array('myTrait', 'histTrait', 'thatTrait')); $classGenerator->addTraitOverride('myTrait::foo', array('hisTrait', 'thatTrait')); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides['myTrait::foo']), 2); $classGenerator->removeTraitOverride('myTrait::foo', 'hisTrait'); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides['myTrait::foo']), 1); $this->assertEquals($overrides['myTrait::foo'][1], 'thatTrait'); } public function testCanRemoveAllTraitOverrides() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->addTraits(array('myTrait', 'histTrait', 'thatTrait')); $classGenerator->addTraitOverride('myTrait::foo', array('hisTrait', 'thatTrait')); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides['myTrait::foo']), 2); $classGenerator->removeTraitOverride('myTrait::foo'); $overrides = $classGenerator->getTraitOverrides(); $this->assertEquals(count($overrides), 0); } /** * @group generate */ public function testUseTraitGeneration() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->setName('myClass'); $classGenerator->addTrait('myTrait'); $classGenerator->addTrait('hisTrait'); $classGenerator->addTrait('thatTrait'); $output = <<<'CODE' class myClass { use myTrait, hisTrait, thatTrait; } CODE; $this->assertEquals($classGenerator->generate(), $output); } /** * @group generate */ public function testTraitGenerationWithAliasesAndOverrides() { if (version_compare(PHP_VERSION, '5.4', 'lt')) { $this->markTestSkipped('This test requires PHP version 5.4+'); } $classGenerator = new ClassGenerator(); $classGenerator->setName('myClass'); $classGenerator->addTrait('myTrait'); $classGenerator->addTrait('hisTrait'); $classGenerator->addTrait('thatTrait'); $classGenerator->addTraitAlias("hisTrait::foo", "test", ReflectionMethod::IS_PUBLIC); $classGenerator->addTraitOverride('myTrait::bar', array('hisTrait', 'thatTrait')); $output = <<<'CODE' class myClass { use myTrait, hisTrait, thatTrait { hisTrait::foo as public test; myTrait::bar insteadof hisTrait; myTrait::bar insteadof thatTrait; } } CODE; $this->assertEquals($classGenerator->generate(), $output); } public function testGenerateWithFinalFlag() { $classGenerator = ClassGenerator::fromArray(array( 'name' => 'SomeClass', 'flags' => ClassGenerator::FLAG_FINAL )); $expectedOutput = <<<EOS final class SomeClass { } EOS; $output = $classGenerator->generate(); $this->assertEquals($expectedOutput, $output, $output); } }
bsd-3-clause
riaf/ethna
class/Action/UnitTest.php
1167
<?php /** * UnitTest.php * * @author Takuya Ookubo <sfio@sakura.ai.to> * @license http://www.opensource.org/licenses/bsd-license.php The BSD License * @package Ethna * @version $Id$ */ /** * __ethna_unittest__フォームの実装 * * @author Takuya Ookubo <sfio@sakura.ai.to> * @access public * @package Ethna */ class Ethna_Form_UnitTest extends Ethna_ActionForm { /** * @access private * @var array フォーム値定義 */ var $form = array( ); } /** * __ethna_unittest__アクションの実装 * * @author Takuya Ookubo <sfio@sakura.ai.to> * @access public * @package Ethna */ class Ethna_Action_UnitTest extends Ethna_ActionClass { /** * __ethna_unittest__アクションの前処理 * * @access public * @return string Forward先(正常終了ならnull) */ function prepare() { return null; } /** * __ethna_unittest__アクションの実装 * * @access public * @return string 遷移名 */ function perform() { return '__ethna_unittest__'; } }
bsd-3-clause
Team3574/RKellyBot
src/edu/wpi/first/wpilibj/templates/commands/PizzaBoxTiltSeventy.java
1071
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; /** * * @author team3574 */ public class PizzaBoxTiltSeventy extends CommandBase { public PizzaBoxTiltSeventy() { // Use requires() here to declare subsystem dependencies requires(thePizzaBoxTilt); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { if(thePizzaBoxTilt.getLimitSwitchSeventy()==true){ thePizzaBoxTilt.setSetpoint(thePizzaBoxTilt.getSetpoint()-25); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
u-root/u-root
vendor/src.elv.sh/pkg/cli/tk/codearea_render.go
2863
package tk import ( "src.elv.sh/pkg/cli/term" "src.elv.sh/pkg/ui" "src.elv.sh/pkg/wcwidth" ) // View model, calculated from State and used for rendering. type view struct { prompt ui.Text rprompt ui.Text code ui.Text dot int errors []error } var stylingForPending = ui.Underlined func getView(w *codeArea) *view { s := w.CopyState() code, pFrom, pTo := patchPending(s.Buffer, s.Pending) styledCode, errors := w.Highlighter(code.Content) if pFrom < pTo { // Apply stylingForPending to [pFrom, pTo) parts := styledCode.Partition(pFrom, pTo) pending := ui.StyleText(parts[1], stylingForPending) styledCode = ui.Concat(parts[0], pending, parts[2]) } var rprompt ui.Text if !s.HideRPrompt { rprompt = w.RPrompt() } return &view{w.Prompt(), rprompt, styledCode, code.Dot, errors} } func patchPending(c CodeBuffer, p PendingCode) (CodeBuffer, int, int) { if p.From > p.To || p.From < 0 || p.To > len(c.Content) { // Invalid Pending. return c, 0, 0 } if p.From == p.To && p.Content == "" { return c, 0, 0 } newContent := c.Content[:p.From] + p.Content + c.Content[p.To:] newDot := 0 switch { case c.Dot < p.From: // Dot is before the replaced region. Keep it. newDot = c.Dot case c.Dot >= p.From && c.Dot < p.To: // Dot is within the replaced region. Place the dot at the end. newDot = p.From + len(p.Content) case c.Dot >= p.To: // Dot is after the replaced region. Maintain the relative position of // the dot. newDot = c.Dot - (p.To - p.From) + len(p.Content) } return CodeBuffer{Content: newContent, Dot: newDot}, p.From, p.From + len(p.Content) } func renderView(v *view, buf *term.BufferBuilder) { buf.EagerWrap = true buf.WriteStyled(v.prompt) if len(buf.Lines) == 1 && buf.Col*2 < buf.Width { buf.Indent = buf.Col } parts := v.code.Partition(v.dot) buf. WriteStyled(parts[0]). SetDotHere(). WriteStyled(parts[1]) buf.EagerWrap = false buf.Indent = 0 // Handle rprompts with newlines. if rpromptWidth := styledWcswidth(v.rprompt); rpromptWidth > 0 { padding := buf.Width - buf.Col - rpromptWidth if padding >= 1 { buf.WriteSpaces(padding) buf.WriteStyled(v.rprompt) } } if len(v.errors) > 0 { for _, err := range v.errors { buf.Newline() buf.Write(err.Error()) } } } func truncateToHeight(b *term.Buffer, maxHeight int) { switch { case len(b.Lines) <= maxHeight: // We can show all line; do nothing. case b.Dot.Line < maxHeight: // We can show all lines before the cursor, and as many lines after the // cursor as we can, adding up to maxHeight. b.TrimToLines(0, maxHeight) default: // We can show maxHeight lines before and including the cursor line. b.TrimToLines(b.Dot.Line-maxHeight+1, b.Dot.Line+1) } } func styledWcswidth(t ui.Text) int { w := 0 for _, seg := range t { w += wcwidth.Of(seg.Text) } return w }
bsd-3-clause
staranjeet/fjord
fjord/feedback/tests/__init__.py
1878
import factory from fjord.base import browsers from fjord.feedback.models import ( Product, Response, ResponseContext, ResponseEmail, ResponsePI ) USER_AGENT = 'Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/17.0 Firefox/17.0' class ProductFactory(factory.DjangoModelFactory): class Meta: model = Product display_name = u'Firefox' db_name = factory.LazyAttribute(lambda a: a.display_name) notes = u'' slug = u'firefox' enabled = True on_dashboard = True on_picker = True browser_data_browser = u'' class ResponseFactory(factory.DjangoModelFactory): class Meta: model = Response happy = True, url = u'' description = u'So awesome!' user_agent = USER_AGENT browser = factory.LazyAttribute( lambda a: browsers.parse_ua(a.user_agent).browser) browser_version = factory.LazyAttribute( lambda a: browsers.parse_ua(a.user_agent).browser_version) platform = factory.LazyAttribute( lambda a: browsers.parse_ua(a.user_agent).platform) product = factory.LazyAttribute( lambda a: Response.infer_product( browsers.parse_ua(a.user_agent))) channel = u'stable' version = factory.LazyAttribute( lambda a: browsers.parse_ua(a.user_agent).browser_version) locale = u'en-US' api = None class ResponseEmailFactory(factory.DjangoModelFactory): class Meta: model = ResponseEmail opinion = factory.SubFactory(ResponseFactory) email = 'joe@example.com' class ResponseContextFactory(factory.DjangoModelFactory): class Meta: model = ResponseContext opinion = factory.SubFactory(ResponseFactory) data = '{}' class ResponsePIFactory(factory.DjangoModelFactory): class Meta: model = ResponsePI opinion = factory.SubFactory(ResponseFactory) data = '{}'
bsd-3-clause
pfumagalli/couldit-autoexport
src/main/java/it/could/util/encoding/URICharacters.java
11243
/* ========================================================================== * * Copyright (c) 2006, Pier Paolo Fumagalli <mailto:pier@betaversion.org> * * All rights reserved. * * ========================================================================== * * * * Redistribution and use in source and binary forms, with or without modifi- * * cation, are permitted provided that the following conditions are met: * * * * - Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * - Neither the name of Pier Fumagalli, nor the names of other contributors * * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * ========================================================================== */ package it.could.util.encoding; /** * <p>An interface containing all the character classes used for encoding the * different parts of an URI, as specified by * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC-2396</a>.</p> * * @author <a href="http://could.it/">Pier Fumagalli</a> */ public interface URICharacters { /* ====================================================================== */ /* CHARACTER CLASSES */ /* ====================================================================== */ /** <p>The alphabet of lower-case characters (RFC-2396 Section 1.6).</p> */ public static final char CLASS_LOWER_CASE_ALPHA[] = "abcdefghijklmnopqrstuvwxyz".toCharArray(); /** <p>The alphabet of upper-case characters (RFC-2396 Section 1.6).</p> */ public static final char CLASS_UPPER_CASE_ALPHA[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); /** <p>The union of upper and lower case letters (RFC-2396 Section 1.6).</p> */ public static final char CLASS_ALPHA[] = new StringBuffer() .append(CLASS_LOWER_CASE_ALPHA) .append(CLASS_UPPER_CASE_ALPHA) .toString().toCharArray(); /** <p>All numerical digits (RFC-2396 Section 1.6).</p> */ public static final char CLASS_DIGIT[] = "0123456789".toCharArray(); /** <p>The union of all letters and digits (RFC-2396 Section 1.6).</p> */ public static final char CLASS_ALPHANUMERIC[] = new StringBuffer() .append(CLASS_ALPHA) .append(CLASS_DIGIT) .toString().toCharArray(); /** <p>Mark characters (RFC-2396 Section 2.2).</p> */ public static final char CLASS_MARK[] = "-_.!~*'()".toCharArray(); /** <p>Characters for hexadecimal digits (RFC-2396 Section 2.4.1).</p> */ public static final char CLASS_HEX[] = new StringBuffer() .append(CLASS_DIGIT) .append("abcdefABCDEF") .toString().toCharArray(); /** <p>All reserved characters (RFC-2396 Section 1.6).</p> */ public static final char CLASS_RESERVED[] = ";/?:@&=+$,".toCharArray(); /** <p>All unreserved characters (RFC-2396 Section 2.3).</p> */ public static final char CLASS_UNRESERVED[] = new StringBuffer() .append(CLASS_ALPHANUMERIC) .append(CLASS_MARK) .toString().toCharArray(); /** <p>All characters representable in a URI (RFC-2396 Section 2).</p> */ public static final char CLASS_URI_CHARACTERS[] = new StringBuffer() .append(CLASS_RESERVED) .append(CLASS_UNRESERVED) .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN SCHEMAS */ /* ====================================================================== */ /** <p>The characters allowed as the start of a scheme (RFC-2396 Section 3.1).</p> */ public static final char SCHEME_START[] = CLASS_ALPHA; /** <p>The characters allowed after the first one in a scheme (RFC-2396 Section 3.1).</p> */ public static final char SCHEME_CHARS[] = new StringBuffer() .append(CLASS_ALPHANUMERIC) .append("+-.") .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN AUTHORITIES */ /* ====================================================================== */ /** <p>The characters allowed in an authority user name (RFC-2396 Section 3.2).</p> */ public static final char AUTHORITY_USER[] = new StringBuffer() .append(CLASS_UNRESERVED) .append(";&=$,") .toString().toCharArray(); /** <p>The characters allowed in an authority password (RFC-2396 Section 3.2).</p> */ public static final char AUTHORITY_PASS[] = AUTHORITY_USER; /** <p>The characters allowed in an authority host name (RFC-2396 Section 3.2).</p> */ public static final char AUTHORITY_HOST[] = new StringBuffer() .append(CLASS_ALPHANUMERIC) .append("-.") .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN PATHS */ /* ====================================================================== */ /** <p>The characters allowed in a path element (RFC-2396 Section 3.3).</p> */ public static final char PATH[] = new StringBuffer() .append(CLASS_UNRESERVED) .append("/?:@$,") .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN QUERY */ /* ====================================================================== */ /** <p>The characters allowed in the query (RFC-2396 Section 3.4).</p> */ public static final char QUERY[] = new StringBuffer() .append(CLASS_UNRESERVED) .append("&=") .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN PARAMETERS */ /* ====================================================================== */ /** <p>The characters allowed in a parameter name (RFC-2396 Section 3.3/3.4).</p> */ public static final char PARAMETER_NAME[] = new StringBuffer() .append(CLASS_UNRESERVED) .append(":@$,") .toString().toCharArray(); /** <p>The characters allowed in a parameter value (RFC-2396 Section 3.3/3.4).</p> */ public static final char PARAMETER_VALUE[] = PARAMETER_NAME; /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN FRAGMENTS */ /* ====================================================================== */ /** <p>The characters allowed in a fragment (RFC-2396 Section 4.1).</p> */ public static final char FRAGMENT[] = new StringBuffer() .append(CLASS_UNRESERVED) .append(";/?:@&=$,") .toString().toCharArray(); /* ====================================================================== */ /* CHARACTERS ALLOWABLE IN OPAQUE PARTS */ /* ====================================================================== */ /** <p>The characters allowed at the start of an opaque part (RFC-2396 Section 3).</p> */ public static final char OPAQUE_START[] = new StringBuffer() .append(CLASS_UNRESERVED) .append(";?:@&=+$,") .toString().toCharArray(); /** <p>The characters allowed after the first one in an opaque part (RFC-2396 Section 3).</p> */ public static final char OPAQUE_CHARS[] = new StringBuffer() .append(OPAQUE_START) .append("/") .toString().toCharArray(); }
bsd-3-clause
espadrine/opera
chromium/src/third_party/accessibility-developer-tools/src/js/Constants.js
26071
// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('axs.constants'); goog.provide('axs.constants.Severity'); goog.provide('axs.constants.AuditResult'); /** @type {Object.<string, Object>} */ axs.constants.ARIA_ROLES = { "alert": { "namefrom": [ "author" ], "parent": [ "region" ] }, "alertdialog": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "alert", "dialog" ] }, "application": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "landmark" ] }, "article": { "namefrom": [ "author" ], "parent": [ "document", "region" ] }, "banner": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "button": { "childpresentational": true, "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "command" ], "properties": [ "aria-expanded", "aria-pressed" ] }, "checkbox": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "input" ], "requiredProperties": [ "aria-checked" ], "properties": [ "aria-checked" ] }, "columnheader": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "gridcell", "sectionhead", "widget" ], "properties": [ "aria-sort" ] }, "combobox": { "mustcontain": [ "listbox", "textbox" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "select" ], "requiredProperties": [ "aria-expanded" ], "properties": [ "aria-expanded", "aria-autocomplete", "aria-required" ] }, "command": { "abstract": true, "namefrom": [ "author" ], "parent": [ "widget" ] }, "complementary": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "composite": { "abstract": true, "childpresentational": false, "namefrom": [ "author" ], "parent": [ "widget" ], "properties": [ "aria-activedescendant" ] }, "contentinfo": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "definition": { "namefrom": [ "author" ], "parent": [ "section" ] }, "dialog": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "window" ] }, "directory": { "namefrom": [ "contents", "author" ], "parent": [ "list" ] }, "document": { "namefrom": [ " author" ], "namerequired": true, "parent": [ "structure" ], "properties": [ "aria-expanded" ] }, "form": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "grid": { "mustcontain": [ "row", "rowgroup" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "composite", "region" ], "properties": [ "aria-level", "aria-multiselectable", "aria-readonly" ] }, "gridcell": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "section", "widget" ], "properties": [ "aria-readonly", "aria-required", "aria-selected" ] }, "group": { "namefrom": [ " author" ], "parent": [ "section" ], "properties": [ "aria-activedescendant" ] }, "heading": { "namerequired": true, "parent": [ "sectionhead" ], "properties": [ "aria-level" ] }, "img": { "childpresentational": true, "namefrom": [ "author" ], "namerequired": true, "parent": [ "section" ] }, "input": { "abstract": true, "namefrom": [ "author" ], "parent": [ "widget" ] }, "landmark": { "abstract": true, "namefrom": [ "contents", "author" ], "namerequired": false, "parent": [ "region" ] }, "link": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "command" ], "properties": [ "aria-expanded" ] }, "list": { "mustcontain": [ "group", "listitem" ], "namefrom": [ "author" ], "parent": [ "region" ] }, "listbox": { "mustcontain": [ "option" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "list", "select" ], "properties": [ "aria-multiselectable", "aria-required" ] }, "listitem": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "section" ], "properties": [ "aria-level", "aria-posinset", "aria-setsize" ] }, "log": { "namefrom": [ " author" ], "namerequired": true, "parent": [ "region" ] }, "main": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "marquee": { "namerequired": true, "parent": [ "section" ] }, "math": { "childpresentational": true, "namefrom": [ "author" ], "parent": [ "section" ] }, "menu": { "mustcontain": [ "group", "menuitemradio", "menuitem", "menuitemcheckbox" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "list", "select" ] }, "menubar": { "namefrom": [ "author" ], "parent": [ "menu" ] }, "menuitem": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "command" ] }, "menuitemcheckbox": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "checkbox", "menuitem" ] }, "menuitemradio": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "menuitemcheckbox", "radio" ] }, "navigation": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "note": { "namefrom": [ "author" ], "parent": [ "section" ] }, "option": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "input" ], "properties": [ "aria-checked", "aria-posinset", "aria-selected", "aria-setsize" ] }, "presentation": { "parent": [ "structure" ] }, "progressbar": { "childpresentational": true, "namefrom": [ "author" ], "namerequired": true, "parent": [ "range" ] }, "radio": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "checkbox", "option" ] }, "radiogroup": { "mustcontain": [ "radio" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "select" ], "properties": [ "aria-required" ] }, "range": { "abstract": true, "namefrom": [ "author" ], "parent": [ "widget" ], "properties": [ "aria-valuemax", "aria-valuemin", "aria-valuenow", "aria-valuetext" ] }, "region": { "namefrom": [ " author" ], "parent": [ "section" ] }, "roletype": { "abstract": true, "properties": [ "aria-atomic", "aria-busy", "aria-controls", "aria-describedby", "aria-disabled", "aria-dropeffect", "aria-flowto", "aria-grabbed", "aria-haspopup", "aria-hidden", "aria-invalid", "aria-label", "aria-labelledby", "aria-live", "aria-owns", "aria-relevant" ] }, "row": { "mustcontain": [ "columnheader", "gridcell", "rowheader" ], "namefrom": [ "contents", "author" ], "parent": [ "group", "widget" ], "properties": [ "aria-level", "aria-selected" ] }, "rowgroup": { "mustcontain": [ "row" ], "namefrom": [ "contents", "author" ], "parent": [ "group" ] }, "rowheader": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "gridcell", "sectionhead", "widget" ], "properties": [ "aria-sort" ] }, "search": { "namefrom": [ "author" ], "parent": [ "landmark" ] }, "section": { "abstract": true, "namefrom": [ "contents", "author" ], "parent": [ "structure" ], "properties": [ "aria-expanded" ] }, "sectionhead": { "abstract": true, "namefrom": [ "contents", "author" ], "parent": [ "structure" ], "properties": [ "aria-expanded" ] }, "select": { "abstract": true, "namefrom": [ "author" ], "parent": [ "composite", "group", "input" ] }, "separator": { "childpresentational": true, "namefrom": [ "author" ], "parent": [ "structure" ], "properties": [ "aria-expanded", "aria-orientation" ] }, "scrollbar": { "childpresentational": true, "namefrom": [ "author" ], "namerequired": false, "parent": [ "input", "range" ], "requiredProperties": [ "aria-controls", "aria-orientation", "aria-valuemax", "aria-valuemin", "aria-valuenow" ], "properties": [ "aria-controls", "aria-orientation", "aria-valuemax", "aria-valuemin", "aria-valuenow" ] }, "slider": { "childpresentational": true, "namefrom": [ "author" ], "namerequired": true, "parent": [ "input", "range" ], "requiredProperties": [ "aria-valuemax", "aria-valuemin", "aria-valuenow" ], "properties": [ "aria-valuemax", "aria-valuemin", "aria-valuenow", "aria-orientation" ] }, "spinbutton": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "input", "range" ], "requiredProperties": [ "aria-valuemax", "aria-valuemin", "aria-valuenow" ], "properties": [ "aria-valuemax", "aria-valuemin", "aria-valuenow", "aria-required" ] }, "status": { "parent": [ "region" ] }, "structure": { "abstract": true, "parent": [ "roletype" ] }, "tab": { "namefrom": [ "contents", "author" ], "parent": [ "sectionhead", "widget" ], "properties": [ "aria-selected" ] }, "tablist": { "mustcontain": [ "tab" ], "namefrom": [ "author" ], "parent": [ "composite", "directory" ], "properties": [ "aria-level" ] }, "tabpanel": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "region" ] }, "textbox": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "input" ], "properties": [ "aria-activedescendant", "aria-autocomplete", "aria-multiline", "aria-readonly", "aria-required" ] }, "timer": { "namefrom": [ "author" ], "namerequired": true, "parent": [ "status" ] }, "toolbar": { "namefrom": [ "author" ], "parent": [ "group" ] }, "tooltip": { "namerequired": true, "parent": [ "section" ] }, "tree": { "mustcontain": [ "group", "treeitem" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "select" ], "properties": [ "aria-multiselectable", "aria-required" ] }, "treegrid": { "mustcontain": [ "row" ], "namefrom": [ "author" ], "namerequired": true, "parent": [ "grid", "tree" ] }, "treeitem": { "namefrom": [ "contents", "author" ], "namerequired": true, "parent": [ "listitem", "option" ] }, "widget": { "abstract": true, "parent": [ "roletype" ] }, "window": { "abstract": true, "namefrom": [ " author" ], "parent": [ "roletype" ], "properties": [ "aria-expanded" ] } }; axs.constants.WIDGET_ROLES = {}; // TODO make a AriaRole object etc. for (var roleName in axs.constants.ARIA_ROLES) { var role = axs.constants.ARIA_ROLES[roleName]; // Inherit all properties and requiredProperties from parent hierarchy. function addAllPropertiesToSet(role, propertiesName, propertiesSet) { var properties = role[propertiesName] if (properties) { for (var i = 0; i < properties.length; i++) propertiesSet[properties[i]] = true; } if (role['parent']) { var parents = role['parent']; for (var j = 0; j < parents.length; j++) { var parentRoleName = parents[j]; addAllPropertiesToSet(axs.constants.ARIA_ROLES[parentRoleName], propertiesName, propertiesSet); } } } var propertiesSet = {}; addAllPropertiesToSet(role, 'properties', propertiesSet); role['propertiesSet'] = propertiesSet; var requiredPropertiesSet = {}; addAllPropertiesToSet(role, 'requiredProperties', requiredPropertiesSet); role['requiredPropertiesSet'] = requiredPropertiesSet; // Squash parent hierarchy on to role object function addAllParentRolesToSet(role, set) { if (!role['parent']) return; var parents = role['parent']; for (var j = 0; j < parents.length; j++) { var parentRoleName = parents[j]; set[parentRoleName] = true; addAllParentRolesToSet(axs.constants.ARIA_ROLES[parentRoleName], set); } } var parentRolesSet = {}; addAllParentRolesToSet(role, parentRolesSet); role['allParentRolesSet'] = parentRolesSet; if ('widget' in parentRolesSet) axs.constants.WIDGET_ROLES[roleName] = role; } /** @type {Object.<string, Object>} */ axs.constants.ARIA_PROPERTIES = { "activedescendant": { "type": "property", "valueType": "idref" }, "atomic": { "type": "property", "valueType": "true-false" }, "autocomplete": { "type": "property", "valueType": "token", "defaultValue": "none", "values": [ "inline", "list", "both", "none" ] }, "busy": { "type": "state", "valueType": "true-false" }, "checked": { "type": "state", "valueType": "tristate" }, "controls": { "type": "property", "valueType": "idref_list" }, "describedby": { "type": "property", "valueType": "idref_list" }, "disabled": { "type": "state", "valueType": "true-false" }, "dropeffect": { "type": "property", "valueType": "token_list", "defaultValue": "none", "values": [ "copy", "move", "link", "execute", "popup", "none" ] }, "expanded": { "type": "state", "valueType": "true-false-undefined" }, "flowto": { "type": "property", "valueType": "idref_list" }, "grabbed": { "type": "state", "valueType": "true-false-undefined" }, "haspopup": { "type": "property", "valueType": "true-false" }, "hidden": { "type": "state", "valueType": "true-false" }, "invalid": { "type": "state", "valueType": "token", "defaultValue": "false", "values": [ "grammar", "false", "spelling", "true" ] }, "label": { "type": "property", "valueType": "string" }, "labelledby": { "type": "property", "valueType": "idref_list" }, "level": { "type": "property", "valueType": "integer" }, "live": { "type": "property", "valueType": "token", "defaultValue": "off", "values": [ "off", "polite", "assertive" ] }, "multiline": { "type": "property", "valueType": "true-false" }, "multiselectable": { "type": "property", "valueType": "true-false" }, "orientation": { "type": "property", "valueType": "token", "defaultValue": "horizontal", "values": [ "vertical", "horizontal" ] }, "owns": { "type": "property", "valueType": "idref_list" }, "posinset": { "type": "property", "valueType": "integer" }, "pressed": { "type": "state", "valueType": "tristate" }, "readonly": { "type": "property", "valueType": "true-false" }, "relevant": { "type": "property", "valueType": "token_list", "defaultValue": "additions", "values": [ "additions", "removals", "text", "all", "additions" ] }, "required": { "type": "property", "valueType": "true-false" }, "selected": { "type": "state", "valueType": "true-false-undefined" }, "setsize": { "type": "property", "valueType": "integer" }, "sort": { "type": "property", "valueType": "token", "defaultValue": "none", "values": [ "ascending", "descending", "none", "other" ] }, "valuemax": { "type": "property", "valueType": "number" }, "valuemin": { "type": "property", "valueType": "number" }, "valuenow": { "type": "property", "valueType": "number" }, "valuetext": { "type": "property", "valueType": "string" } }; /** * All of the states and properties which apply globally. */ axs.constants.GLOBAL_PROPERTIES = [ "aria-atomic", "aria-busy", // (state) "aria-controls", "aria-describedby", "aria-disabled", // (state) "aria-dropeffect", "aria-flowto", "aria-grabbed", // (state) "aria-haspopup", "aria-hidden", // (state) "aria-invalid", // (state) "aria-label", "aria-labelledby", "aria-live", "aria-owns", "aria-relevant" ]; /** * A constant indicating no role name. * @type {string} */ axs.constants.NO_ROLE_NAME = ' '; /** * A mapping from ARIA role names to their message ids. * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/aria_util.js * @type {Object.<string, string>} */ axs.constants.WIDGET_ROLE_TO_NAME = { 'alert' : 'aria_role_alert', 'alertdialog' : 'aria_role_alertdialog', 'button' : 'aria_role_button', 'checkbox' : 'aria_role_checkbox', 'columnheader' : 'aria_role_columnheader', 'combobox' : 'aria_role_combobox', 'dialog' : 'aria_role_dialog', 'grid' : 'aria_role_grid', 'gridcell' : 'aria_role_gridcell', 'link' : 'aria_role_link', 'listbox' : 'aria_role_listbox', 'log' : 'aria_role_log', 'marquee' : 'aria_role_marquee', 'menu' : 'aria_role_menu', 'menubar' : 'aria_role_menubar', 'menuitem' : 'aria_role_menuitem', 'menuitemcheckbox' : 'aria_role_menuitemcheckbox', 'menuitemradio' : 'aria_role_menuitemradio', 'option' : axs.constants.NO_ROLE_NAME, 'progressbar' : 'aria_role_progressbar', 'radio' : 'aria_role_radio', 'radiogroup' : 'aria_role_radiogroup', 'rowheader' : 'aria_role_rowheader', 'scrollbar' : 'aria_role_scrollbar', 'slider' : 'aria_role_slider', 'spinbutton' : 'aria_role_spinbutton', 'status' : 'aria_role_status', 'tab' : 'aria_role_tab', 'tabpanel' : 'aria_role_tabpanel', 'textbox' : 'aria_role_textbox', 'timer' : 'aria_role_timer', 'toolbar' : 'aria_role_toolbar', 'tooltip' : 'aria_role_tooltip', 'treeitem' : 'aria_role_treeitem' }; /** * @type {Object.<string, string>} * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/aria_util.js */ axs.constants.STRUCTURE_ROLE_TO_NAME = { 'article' : 'aria_role_article', 'application' : 'aria_role_application', 'banner' : 'aria_role_banner', 'columnheader' : 'aria_role_columnheader', 'complementary' : 'aria_role_complementary', 'contentinfo' : 'aria_role_contentinfo', 'definition' : 'aria_role_definition', 'directory' : 'aria_role_directory', 'document' : 'aria_role_document', 'form' : 'aria_role_form', 'group' : 'aria_role_group', 'heading' : 'aria_role_heading', 'img' : 'aria_role_img', 'list' : 'aria_role_list', 'listitem' : 'aria_role_listitem', 'main' : 'aria_role_main', 'math' : 'aria_role_math', 'navigation' : 'aria_role_navigation', 'note' : 'aria_role_note', 'region' : 'aria_role_region', 'rowheader' : 'aria_role_rowheader', 'search' : 'aria_role_search', 'separator' : 'aria_role_separator' }; /** * @type {Array.<Object>} * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/aria_util.js */ axs.constants.ATTRIBUTE_VALUE_TO_STATUS = [ { name: 'aria-autocomplete', values: {'inline' : 'aria_autocomplete_inline', 'list' : 'aria_autocomplete_list', 'both' : 'aria_autocomplete_both'} }, { name: 'aria-checked', values: {'true' : 'aria_checked_true', 'false' : 'aria_checked_false', 'mixed' : 'aria_checked_mixed'} }, { name: 'aria-disabled', values: {'true' : 'aria_disabled_true'} }, { name: 'aria-expanded', values: {'true' : 'aria_expanded_true', 'false' : 'aria_expanded_false'} }, { name: 'aria-invalid', values: {'true' : 'aria_invalid_true', 'grammar' : 'aria_invalid_grammar', 'spelling' : 'aria_invalid_spelling'} }, { name: 'aria-multiline', values: {'true' : 'aria_multiline_true'} }, { name: 'aria-multiselectable', values: {'true' : 'aria_multiselectable_true'} }, { name: 'aria-pressed', values: {'true' : 'aria_pressed_true', 'false' : 'aria_pressed_false', 'mixed' : 'aria_pressed_mixed'} }, { name: 'aria-readonly', values: {'true' : 'aria_readonly_true'} }, { name: 'aria-required', values: {'true' : 'aria_required_true'} }, { name: 'aria-selected', values: {'true' : 'aria_selected_true', 'false' : 'aria_selected_false'} } ]; /** * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/dom_util.js * @type {Object} */ axs.constants.INPUT_TYPE_TO_INFORMATION_TABLE_MSG = { 'button' : 'input_type_button', 'checkbox' : 'input_type_checkbox', 'color' : 'input_type_color', 'datetime' : 'input_type_datetime', 'datetime-local' : 'input_type_datetime_local', 'date' : 'input_type_date', 'email' : 'input_type_email', 'file' : 'input_type_file', 'image' : 'input_type_image', 'month' : 'input_type_month', 'number' : 'input_type_number', 'password' : 'input_type_password', 'radio' : 'input_type_radio', 'range' : 'input_type_range', 'reset' : 'input_type_reset', 'search' : 'input_type_search', 'submit' : 'input_type_submit', 'tel' : 'input_type_tel', 'text' : 'input_type_text', 'url' : 'input_type_url', 'week' : 'input_type_week' }; /** * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/dom_util.js * @type {Object} */ axs.constants.TAG_TO_INFORMATION_TABLE_VERBOSE_MSG = { 'A' : 'tag_link', 'BUTTON' : 'tag_button', 'H1' : 'tag_h1', 'H2' : 'tag_h2', 'H3' : 'tag_h3', 'H4' : 'tag_h4', 'H5' : 'tag_h5', 'H6' : 'tag_h6', 'LI' : 'tag_li', 'OL' : 'tag_ol', 'SELECT' : 'tag_select', 'TEXTAREA' : 'tag_textarea', 'UL' : 'tag_ul', 'SECTION' : 'tag_section', 'NAV' : 'tag_nav', 'ARTICLE' : 'tag_article', 'ASIDE' : 'tag_aside', 'HGROUP' : 'tag_hgroup', 'HEADER' : 'tag_header', 'FOOTER' : 'tag_footer', 'TIME' : 'tag_time', 'MARK' : 'tag_mark' }; /** * Copied from ChromeVox: * http://code.google.com/p/google-axs-chrome/source/browse/trunk/chromevox/common/dom_util.js * @type {Object} */ axs.constants.TAG_TO_INFORMATION_TABLE_BRIEF_MSG = { 'BUTTON' : 'tag_button', 'SELECT' : 'tag_select', 'TEXTAREA' : 'tag_textarea' }; axs.constants.MIXED_VALUES = { "true": true, "false": true, "mixed": true } // pull values lists into sets for (var propertyName in axs.constants.ARIA_PROPERTIES) { var propertyDetails = axs.constants.ARIA_PROPERTIES[propertyName]; if (!propertyDetails.values) continue; var valuesSet = {}; for (var i = 0; i < propertyDetails.values.length; i++) valuesSet[propertyDetails.values[i]] = true; propertyDetails.valuesSet = valuesSet; } /** @enum {string} */ axs.constants.Severity = { Info: 'Info', Warning: 'Warning', Severe: 'Severe' }; /** @enum {string} */ axs.constants.AuditResult = { PASS: 'PASS', FAIL: 'FAIL', NA: 'NA' };
bsd-3-clause
Instagram/wal-e
tests/test_log_help.py
1496
import re from wal_e import log_help def sanitize_log(log): return re.sub(r'time=[0-9T:\-\.]+ pid=\d+', 'time=2012-01-01T00.1234-00 pid=1234', log) def test_nonexisting_socket(tmpdir, monkeypatch): # Must not raise an exception, silently failing is preferred for # now. monkeypatch.setattr(log_help, 'HANDLERS', []) log_help.configure(syslog_address=tmpdir.join('bogus')) def test_format_structured_info(): zero = {}, 'time=2012-01-01T00.1234-00 pid=1234' one = ({'hello': 'world'}, u'time=2012-01-01T00.1234-00 pid=1234 hello=world') many = ({'hello': 'world', 'goodbye': 'world'}, u'time=2012-01-01T00.1234-00 pid=1234 goodbye=world hello=world') for d, expect in [zero, one, many]: result = log_help.WalELogger._fmt_structured(d) assert sanitize_log(result) == expect def test_fmt_logline_simple(): out = log_help.WalELogger.fmt_logline( 'The message', 'The detail', 'The hint', {'structured-data': 'yes'}) out = sanitize_log(out) assert out == """MSG: The message DETAIL: The detail HINT: The hint STRUCTURED: time=2012-01-01T00.1234-00 pid=1234 structured-data=yes""" # Try without structured data out = log_help.WalELogger.fmt_logline( 'The message', 'The detail', 'The hint') out = sanitize_log(out) assert out == """MSG: The message DETAIL: The detail HINT: The hint STRUCTURED: time=2012-01-01T00.1234-00 pid=1234"""
bsd-3-clause
alexeyzimarev/Projac
src/Paramol.Tests/SqlClient/ParameterCountLimitedExceeded.cs
203945
using Paramol.SqlClient; namespace Paramol.Tests.SqlClient { public class ParameterCountLimitedExceeded { public static readonly ParameterCountLimitedExceeded Instance = new ParameterCountLimitedExceeded(); private ParameterCountLimitedExceeded() { } public IDbParameterValue P1 { get { return TSql.Int(0); } } public IDbParameterValue P2 { get { return TSql.Int(0); } } public IDbParameterValue P3 { get { return TSql.Int(0); } } public IDbParameterValue P4 { get { return TSql.Int(0); } } public IDbParameterValue P5 { get { return TSql.Int(0); } } public IDbParameterValue P6 { get { return TSql.Int(0); } } public IDbParameterValue P7 { get { return TSql.Int(0); } } public IDbParameterValue P8 { get { return TSql.Int(0); } } public IDbParameterValue P9 { get { return TSql.Int(0); } } public IDbParameterValue P10 { get { return TSql.Int(0); } } public IDbParameterValue P11 { get { return TSql.Int(0); } } public IDbParameterValue P12 { get { return TSql.Int(0); } } public IDbParameterValue P13 { get { return TSql.Int(0); } } public IDbParameterValue P14 { get { return TSql.Int(0); } } public IDbParameterValue P15 { get { return TSql.Int(0); } } public IDbParameterValue P16 { get { return TSql.Int(0); } } public IDbParameterValue P17 { get { return TSql.Int(0); } } public IDbParameterValue P18 { get { return TSql.Int(0); } } public IDbParameterValue P19 { get { return TSql.Int(0); } } public IDbParameterValue P20 { get { return TSql.Int(0); } } public IDbParameterValue P21 { get { return TSql.Int(0); } } public IDbParameterValue P22 { get { return TSql.Int(0); } } public IDbParameterValue P23 { get { return TSql.Int(0); } } public IDbParameterValue P24 { get { return TSql.Int(0); } } public IDbParameterValue P25 { get { return TSql.Int(0); } } public IDbParameterValue P26 { get { return TSql.Int(0); } } public IDbParameterValue P27 { get { return TSql.Int(0); } } public IDbParameterValue P28 { get { return TSql.Int(0); } } public IDbParameterValue P29 { get { return TSql.Int(0); } } public IDbParameterValue P30 { get { return TSql.Int(0); } } public IDbParameterValue P31 { get { return TSql.Int(0); } } public IDbParameterValue P32 { get { return TSql.Int(0); } } public IDbParameterValue P33 { get { return TSql.Int(0); } } public IDbParameterValue P34 { get { return TSql.Int(0); } } public IDbParameterValue P35 { get { return TSql.Int(0); } } public IDbParameterValue P36 { get { return TSql.Int(0); } } public IDbParameterValue P37 { get { return TSql.Int(0); } } public IDbParameterValue P38 { get { return TSql.Int(0); } } public IDbParameterValue P39 { get { return TSql.Int(0); } } public IDbParameterValue P40 { get { return TSql.Int(0); } } public IDbParameterValue P41 { get { return TSql.Int(0); } } public IDbParameterValue P42 { get { return TSql.Int(0); } } public IDbParameterValue P43 { get { return TSql.Int(0); } } public IDbParameterValue P44 { get { return TSql.Int(0); } } public IDbParameterValue P45 { get { return TSql.Int(0); } } public IDbParameterValue P46 { get { return TSql.Int(0); } } public IDbParameterValue P47 { get { return TSql.Int(0); } } public IDbParameterValue P48 { get { return TSql.Int(0); } } public IDbParameterValue P49 { get { return TSql.Int(0); } } public IDbParameterValue P50 { get { return TSql.Int(0); } } public IDbParameterValue P51 { get { return TSql.Int(0); } } public IDbParameterValue P52 { get { return TSql.Int(0); } } public IDbParameterValue P53 { get { return TSql.Int(0); } } public IDbParameterValue P54 { get { return TSql.Int(0); } } public IDbParameterValue P55 { get { return TSql.Int(0); } } public IDbParameterValue P56 { get { return TSql.Int(0); } } public IDbParameterValue P57 { get { return TSql.Int(0); } } public IDbParameterValue P58 { get { return TSql.Int(0); } } public IDbParameterValue P59 { get { return TSql.Int(0); } } public IDbParameterValue P60 { get { return TSql.Int(0); } } public IDbParameterValue P61 { get { return TSql.Int(0); } } public IDbParameterValue P62 { get { return TSql.Int(0); } } public IDbParameterValue P63 { get { return TSql.Int(0); } } public IDbParameterValue P64 { get { return TSql.Int(0); } } public IDbParameterValue P65 { get { return TSql.Int(0); } } public IDbParameterValue P66 { get { return TSql.Int(0); } } public IDbParameterValue P67 { get { return TSql.Int(0); } } public IDbParameterValue P68 { get { return TSql.Int(0); } } public IDbParameterValue P69 { get { return TSql.Int(0); } } public IDbParameterValue P70 { get { return TSql.Int(0); } } public IDbParameterValue P71 { get { return TSql.Int(0); } } public IDbParameterValue P72 { get { return TSql.Int(0); } } public IDbParameterValue P73 { get { return TSql.Int(0); } } public IDbParameterValue P74 { get { return TSql.Int(0); } } public IDbParameterValue P75 { get { return TSql.Int(0); } } public IDbParameterValue P76 { get { return TSql.Int(0); } } public IDbParameterValue P77 { get { return TSql.Int(0); } } public IDbParameterValue P78 { get { return TSql.Int(0); } } public IDbParameterValue P79 { get { return TSql.Int(0); } } public IDbParameterValue P80 { get { return TSql.Int(0); } } public IDbParameterValue P81 { get { return TSql.Int(0); } } public IDbParameterValue P82 { get { return TSql.Int(0); } } public IDbParameterValue P83 { get { return TSql.Int(0); } } public IDbParameterValue P84 { get { return TSql.Int(0); } } public IDbParameterValue P85 { get { return TSql.Int(0); } } public IDbParameterValue P86 { get { return TSql.Int(0); } } public IDbParameterValue P87 { get { return TSql.Int(0); } } public IDbParameterValue P88 { get { return TSql.Int(0); } } public IDbParameterValue P89 { get { return TSql.Int(0); } } public IDbParameterValue P90 { get { return TSql.Int(0); } } public IDbParameterValue P91 { get { return TSql.Int(0); } } public IDbParameterValue P92 { get { return TSql.Int(0); } } public IDbParameterValue P93 { get { return TSql.Int(0); } } public IDbParameterValue P94 { get { return TSql.Int(0); } } public IDbParameterValue P95 { get { return TSql.Int(0); } } public IDbParameterValue P96 { get { return TSql.Int(0); } } public IDbParameterValue P97 { get { return TSql.Int(0); } } public IDbParameterValue P98 { get { return TSql.Int(0); } } public IDbParameterValue P99 { get { return TSql.Int(0); } } public IDbParameterValue P100 { get { return TSql.Int(0); } } public IDbParameterValue P101 { get { return TSql.Int(0); } } public IDbParameterValue P102 { get { return TSql.Int(0); } } public IDbParameterValue P103 { get { return TSql.Int(0); } } public IDbParameterValue P104 { get { return TSql.Int(0); } } public IDbParameterValue P105 { get { return TSql.Int(0); } } public IDbParameterValue P106 { get { return TSql.Int(0); } } public IDbParameterValue P107 { get { return TSql.Int(0); } } public IDbParameterValue P108 { get { return TSql.Int(0); } } public IDbParameterValue P109 { get { return TSql.Int(0); } } public IDbParameterValue P110 { get { return TSql.Int(0); } } public IDbParameterValue P111 { get { return TSql.Int(0); } } public IDbParameterValue P112 { get { return TSql.Int(0); } } public IDbParameterValue P113 { get { return TSql.Int(0); } } public IDbParameterValue P114 { get { return TSql.Int(0); } } public IDbParameterValue P115 { get { return TSql.Int(0); } } public IDbParameterValue P116 { get { return TSql.Int(0); } } public IDbParameterValue P117 { get { return TSql.Int(0); } } public IDbParameterValue P118 { get { return TSql.Int(0); } } public IDbParameterValue P119 { get { return TSql.Int(0); } } public IDbParameterValue P120 { get { return TSql.Int(0); } } public IDbParameterValue P121 { get { return TSql.Int(0); } } public IDbParameterValue P122 { get { return TSql.Int(0); } } public IDbParameterValue P123 { get { return TSql.Int(0); } } public IDbParameterValue P124 { get { return TSql.Int(0); } } public IDbParameterValue P125 { get { return TSql.Int(0); } } public IDbParameterValue P126 { get { return TSql.Int(0); } } public IDbParameterValue P127 { get { return TSql.Int(0); } } public IDbParameterValue P128 { get { return TSql.Int(0); } } public IDbParameterValue P129 { get { return TSql.Int(0); } } public IDbParameterValue P130 { get { return TSql.Int(0); } } public IDbParameterValue P131 { get { return TSql.Int(0); } } public IDbParameterValue P132 { get { return TSql.Int(0); } } public IDbParameterValue P133 { get { return TSql.Int(0); } } public IDbParameterValue P134 { get { return TSql.Int(0); } } public IDbParameterValue P135 { get { return TSql.Int(0); } } public IDbParameterValue P136 { get { return TSql.Int(0); } } public IDbParameterValue P137 { get { return TSql.Int(0); } } public IDbParameterValue P138 { get { return TSql.Int(0); } } public IDbParameterValue P139 { get { return TSql.Int(0); } } public IDbParameterValue P140 { get { return TSql.Int(0); } } public IDbParameterValue P141 { get { return TSql.Int(0); } } public IDbParameterValue P142 { get { return TSql.Int(0); } } public IDbParameterValue P143 { get { return TSql.Int(0); } } public IDbParameterValue P144 { get { return TSql.Int(0); } } public IDbParameterValue P145 { get { return TSql.Int(0); } } public IDbParameterValue P146 { get { return TSql.Int(0); } } public IDbParameterValue P147 { get { return TSql.Int(0); } } public IDbParameterValue P148 { get { return TSql.Int(0); } } public IDbParameterValue P149 { get { return TSql.Int(0); } } public IDbParameterValue P150 { get { return TSql.Int(0); } } public IDbParameterValue P151 { get { return TSql.Int(0); } } public IDbParameterValue P152 { get { return TSql.Int(0); } } public IDbParameterValue P153 { get { return TSql.Int(0); } } public IDbParameterValue P154 { get { return TSql.Int(0); } } public IDbParameterValue P155 { get { return TSql.Int(0); } } public IDbParameterValue P156 { get { return TSql.Int(0); } } public IDbParameterValue P157 { get { return TSql.Int(0); } } public IDbParameterValue P158 { get { return TSql.Int(0); } } public IDbParameterValue P159 { get { return TSql.Int(0); } } public IDbParameterValue P160 { get { return TSql.Int(0); } } public IDbParameterValue P161 { get { return TSql.Int(0); } } public IDbParameterValue P162 { get { return TSql.Int(0); } } public IDbParameterValue P163 { get { return TSql.Int(0); } } public IDbParameterValue P164 { get { return TSql.Int(0); } } public IDbParameterValue P165 { get { return TSql.Int(0); } } public IDbParameterValue P166 { get { return TSql.Int(0); } } public IDbParameterValue P167 { get { return TSql.Int(0); } } public IDbParameterValue P168 { get { return TSql.Int(0); } } public IDbParameterValue P169 { get { return TSql.Int(0); } } public IDbParameterValue P170 { get { return TSql.Int(0); } } public IDbParameterValue P171 { get { return TSql.Int(0); } } public IDbParameterValue P172 { get { return TSql.Int(0); } } public IDbParameterValue P173 { get { return TSql.Int(0); } } public IDbParameterValue P174 { get { return TSql.Int(0); } } public IDbParameterValue P175 { get { return TSql.Int(0); } } public IDbParameterValue P176 { get { return TSql.Int(0); } } public IDbParameterValue P177 { get { return TSql.Int(0); } } public IDbParameterValue P178 { get { return TSql.Int(0); } } public IDbParameterValue P179 { get { return TSql.Int(0); } } public IDbParameterValue P180 { get { return TSql.Int(0); } } public IDbParameterValue P181 { get { return TSql.Int(0); } } public IDbParameterValue P182 { get { return TSql.Int(0); } } public IDbParameterValue P183 { get { return TSql.Int(0); } } public IDbParameterValue P184 { get { return TSql.Int(0); } } public IDbParameterValue P185 { get { return TSql.Int(0); } } public IDbParameterValue P186 { get { return TSql.Int(0); } } public IDbParameterValue P187 { get { return TSql.Int(0); } } public IDbParameterValue P188 { get { return TSql.Int(0); } } public IDbParameterValue P189 { get { return TSql.Int(0); } } public IDbParameterValue P190 { get { return TSql.Int(0); } } public IDbParameterValue P191 { get { return TSql.Int(0); } } public IDbParameterValue P192 { get { return TSql.Int(0); } } public IDbParameterValue P193 { get { return TSql.Int(0); } } public IDbParameterValue P194 { get { return TSql.Int(0); } } public IDbParameterValue P195 { get { return TSql.Int(0); } } public IDbParameterValue P196 { get { return TSql.Int(0); } } public IDbParameterValue P197 { get { return TSql.Int(0); } } public IDbParameterValue P198 { get { return TSql.Int(0); } } public IDbParameterValue P199 { get { return TSql.Int(0); } } public IDbParameterValue P200 { get { return TSql.Int(0); } } public IDbParameterValue P201 { get { return TSql.Int(0); } } public IDbParameterValue P202 { get { return TSql.Int(0); } } public IDbParameterValue P203 { get { return TSql.Int(0); } } public IDbParameterValue P204 { get { return TSql.Int(0); } } public IDbParameterValue P205 { get { return TSql.Int(0); } } public IDbParameterValue P206 { get { return TSql.Int(0); } } public IDbParameterValue P207 { get { return TSql.Int(0); } } public IDbParameterValue P208 { get { return TSql.Int(0); } } public IDbParameterValue P209 { get { return TSql.Int(0); } } public IDbParameterValue P210 { get { return TSql.Int(0); } } public IDbParameterValue P211 { get { return TSql.Int(0); } } public IDbParameterValue P212 { get { return TSql.Int(0); } } public IDbParameterValue P213 { get { return TSql.Int(0); } } public IDbParameterValue P214 { get { return TSql.Int(0); } } public IDbParameterValue P215 { get { return TSql.Int(0); } } public IDbParameterValue P216 { get { return TSql.Int(0); } } public IDbParameterValue P217 { get { return TSql.Int(0); } } public IDbParameterValue P218 { get { return TSql.Int(0); } } public IDbParameterValue P219 { get { return TSql.Int(0); } } public IDbParameterValue P220 { get { return TSql.Int(0); } } public IDbParameterValue P221 { get { return TSql.Int(0); } } public IDbParameterValue P222 { get { return TSql.Int(0); } } public IDbParameterValue P223 { get { return TSql.Int(0); } } public IDbParameterValue P224 { get { return TSql.Int(0); } } public IDbParameterValue P225 { get { return TSql.Int(0); } } public IDbParameterValue P226 { get { return TSql.Int(0); } } public IDbParameterValue P227 { get { return TSql.Int(0); } } public IDbParameterValue P228 { get { return TSql.Int(0); } } public IDbParameterValue P229 { get { return TSql.Int(0); } } public IDbParameterValue P230 { get { return TSql.Int(0); } } public IDbParameterValue P231 { get { return TSql.Int(0); } } public IDbParameterValue P232 { get { return TSql.Int(0); } } public IDbParameterValue P233 { get { return TSql.Int(0); } } public IDbParameterValue P234 { get { return TSql.Int(0); } } public IDbParameterValue P235 { get { return TSql.Int(0); } } public IDbParameterValue P236 { get { return TSql.Int(0); } } public IDbParameterValue P237 { get { return TSql.Int(0); } } public IDbParameterValue P238 { get { return TSql.Int(0); } } public IDbParameterValue P239 { get { return TSql.Int(0); } } public IDbParameterValue P240 { get { return TSql.Int(0); } } public IDbParameterValue P241 { get { return TSql.Int(0); } } public IDbParameterValue P242 { get { return TSql.Int(0); } } public IDbParameterValue P243 { get { return TSql.Int(0); } } public IDbParameterValue P244 { get { return TSql.Int(0); } } public IDbParameterValue P245 { get { return TSql.Int(0); } } public IDbParameterValue P246 { get { return TSql.Int(0); } } public IDbParameterValue P247 { get { return TSql.Int(0); } } public IDbParameterValue P248 { get { return TSql.Int(0); } } public IDbParameterValue P249 { get { return TSql.Int(0); } } public IDbParameterValue P250 { get { return TSql.Int(0); } } public IDbParameterValue P251 { get { return TSql.Int(0); } } public IDbParameterValue P252 { get { return TSql.Int(0); } } public IDbParameterValue P253 { get { return TSql.Int(0); } } public IDbParameterValue P254 { get { return TSql.Int(0); } } public IDbParameterValue P255 { get { return TSql.Int(0); } } public IDbParameterValue P256 { get { return TSql.Int(0); } } public IDbParameterValue P257 { get { return TSql.Int(0); } } public IDbParameterValue P258 { get { return TSql.Int(0); } } public IDbParameterValue P259 { get { return TSql.Int(0); } } public IDbParameterValue P260 { get { return TSql.Int(0); } } public IDbParameterValue P261 { get { return TSql.Int(0); } } public IDbParameterValue P262 { get { return TSql.Int(0); } } public IDbParameterValue P263 { get { return TSql.Int(0); } } public IDbParameterValue P264 { get { return TSql.Int(0); } } public IDbParameterValue P265 { get { return TSql.Int(0); } } public IDbParameterValue P266 { get { return TSql.Int(0); } } public IDbParameterValue P267 { get { return TSql.Int(0); } } public IDbParameterValue P268 { get { return TSql.Int(0); } } public IDbParameterValue P269 { get { return TSql.Int(0); } } public IDbParameterValue P270 { get { return TSql.Int(0); } } public IDbParameterValue P271 { get { return TSql.Int(0); } } public IDbParameterValue P272 { get { return TSql.Int(0); } } public IDbParameterValue P273 { get { return TSql.Int(0); } } public IDbParameterValue P274 { get { return TSql.Int(0); } } public IDbParameterValue P275 { get { return TSql.Int(0); } } public IDbParameterValue P276 { get { return TSql.Int(0); } } public IDbParameterValue P277 { get { return TSql.Int(0); } } public IDbParameterValue P278 { get { return TSql.Int(0); } } public IDbParameterValue P279 { get { return TSql.Int(0); } } public IDbParameterValue P280 { get { return TSql.Int(0); } } public IDbParameterValue P281 { get { return TSql.Int(0); } } public IDbParameterValue P282 { get { return TSql.Int(0); } } public IDbParameterValue P283 { get { return TSql.Int(0); } } public IDbParameterValue P284 { get { return TSql.Int(0); } } public IDbParameterValue P285 { get { return TSql.Int(0); } } public IDbParameterValue P286 { get { return TSql.Int(0); } } public IDbParameterValue P287 { get { return TSql.Int(0); } } public IDbParameterValue P288 { get { return TSql.Int(0); } } public IDbParameterValue P289 { get { return TSql.Int(0); } } public IDbParameterValue P290 { get { return TSql.Int(0); } } public IDbParameterValue P291 { get { return TSql.Int(0); } } public IDbParameterValue P292 { get { return TSql.Int(0); } } public IDbParameterValue P293 { get { return TSql.Int(0); } } public IDbParameterValue P294 { get { return TSql.Int(0); } } public IDbParameterValue P295 { get { return TSql.Int(0); } } public IDbParameterValue P296 { get { return TSql.Int(0); } } public IDbParameterValue P297 { get { return TSql.Int(0); } } public IDbParameterValue P298 { get { return TSql.Int(0); } } public IDbParameterValue P299 { get { return TSql.Int(0); } } public IDbParameterValue P300 { get { return TSql.Int(0); } } public IDbParameterValue P301 { get { return TSql.Int(0); } } public IDbParameterValue P302 { get { return TSql.Int(0); } } public IDbParameterValue P303 { get { return TSql.Int(0); } } public IDbParameterValue P304 { get { return TSql.Int(0); } } public IDbParameterValue P305 { get { return TSql.Int(0); } } public IDbParameterValue P306 { get { return TSql.Int(0); } } public IDbParameterValue P307 { get { return TSql.Int(0); } } public IDbParameterValue P308 { get { return TSql.Int(0); } } public IDbParameterValue P309 { get { return TSql.Int(0); } } public IDbParameterValue P310 { get { return TSql.Int(0); } } public IDbParameterValue P311 { get { return TSql.Int(0); } } public IDbParameterValue P312 { get { return TSql.Int(0); } } public IDbParameterValue P313 { get { return TSql.Int(0); } } public IDbParameterValue P314 { get { return TSql.Int(0); } } public IDbParameterValue P315 { get { return TSql.Int(0); } } public IDbParameterValue P316 { get { return TSql.Int(0); } } public IDbParameterValue P317 { get { return TSql.Int(0); } } public IDbParameterValue P318 { get { return TSql.Int(0); } } public IDbParameterValue P319 { get { return TSql.Int(0); } } public IDbParameterValue P320 { get { return TSql.Int(0); } } public IDbParameterValue P321 { get { return TSql.Int(0); } } public IDbParameterValue P322 { get { return TSql.Int(0); } } public IDbParameterValue P323 { get { return TSql.Int(0); } } public IDbParameterValue P324 { get { return TSql.Int(0); } } public IDbParameterValue P325 { get { return TSql.Int(0); } } public IDbParameterValue P326 { get { return TSql.Int(0); } } public IDbParameterValue P327 { get { return TSql.Int(0); } } public IDbParameterValue P328 { get { return TSql.Int(0); } } public IDbParameterValue P329 { get { return TSql.Int(0); } } public IDbParameterValue P330 { get { return TSql.Int(0); } } public IDbParameterValue P331 { get { return TSql.Int(0); } } public IDbParameterValue P332 { get { return TSql.Int(0); } } public IDbParameterValue P333 { get { return TSql.Int(0); } } public IDbParameterValue P334 { get { return TSql.Int(0); } } public IDbParameterValue P335 { get { return TSql.Int(0); } } public IDbParameterValue P336 { get { return TSql.Int(0); } } public IDbParameterValue P337 { get { return TSql.Int(0); } } public IDbParameterValue P338 { get { return TSql.Int(0); } } public IDbParameterValue P339 { get { return TSql.Int(0); } } public IDbParameterValue P340 { get { return TSql.Int(0); } } public IDbParameterValue P341 { get { return TSql.Int(0); } } public IDbParameterValue P342 { get { return TSql.Int(0); } } public IDbParameterValue P343 { get { return TSql.Int(0); } } public IDbParameterValue P344 { get { return TSql.Int(0); } } public IDbParameterValue P345 { get { return TSql.Int(0); } } public IDbParameterValue P346 { get { return TSql.Int(0); } } public IDbParameterValue P347 { get { return TSql.Int(0); } } public IDbParameterValue P348 { get { return TSql.Int(0); } } public IDbParameterValue P349 { get { return TSql.Int(0); } } public IDbParameterValue P350 { get { return TSql.Int(0); } } public IDbParameterValue P351 { get { return TSql.Int(0); } } public IDbParameterValue P352 { get { return TSql.Int(0); } } public IDbParameterValue P353 { get { return TSql.Int(0); } } public IDbParameterValue P354 { get { return TSql.Int(0); } } public IDbParameterValue P355 { get { return TSql.Int(0); } } public IDbParameterValue P356 { get { return TSql.Int(0); } } public IDbParameterValue P357 { get { return TSql.Int(0); } } public IDbParameterValue P358 { get { return TSql.Int(0); } } public IDbParameterValue P359 { get { return TSql.Int(0); } } public IDbParameterValue P360 { get { return TSql.Int(0); } } public IDbParameterValue P361 { get { return TSql.Int(0); } } public IDbParameterValue P362 { get { return TSql.Int(0); } } public IDbParameterValue P363 { get { return TSql.Int(0); } } public IDbParameterValue P364 { get { return TSql.Int(0); } } public IDbParameterValue P365 { get { return TSql.Int(0); } } public IDbParameterValue P366 { get { return TSql.Int(0); } } public IDbParameterValue P367 { get { return TSql.Int(0); } } public IDbParameterValue P368 { get { return TSql.Int(0); } } public IDbParameterValue P369 { get { return TSql.Int(0); } } public IDbParameterValue P370 { get { return TSql.Int(0); } } public IDbParameterValue P371 { get { return TSql.Int(0); } } public IDbParameterValue P372 { get { return TSql.Int(0); } } public IDbParameterValue P373 { get { return TSql.Int(0); } } public IDbParameterValue P374 { get { return TSql.Int(0); } } public IDbParameterValue P375 { get { return TSql.Int(0); } } public IDbParameterValue P376 { get { return TSql.Int(0); } } public IDbParameterValue P377 { get { return TSql.Int(0); } } public IDbParameterValue P378 { get { return TSql.Int(0); } } public IDbParameterValue P379 { get { return TSql.Int(0); } } public IDbParameterValue P380 { get { return TSql.Int(0); } } public IDbParameterValue P381 { get { return TSql.Int(0); } } public IDbParameterValue P382 { get { return TSql.Int(0); } } public IDbParameterValue P383 { get { return TSql.Int(0); } } public IDbParameterValue P384 { get { return TSql.Int(0); } } public IDbParameterValue P385 { get { return TSql.Int(0); } } public IDbParameterValue P386 { get { return TSql.Int(0); } } public IDbParameterValue P387 { get { return TSql.Int(0); } } public IDbParameterValue P388 { get { return TSql.Int(0); } } public IDbParameterValue P389 { get { return TSql.Int(0); } } public IDbParameterValue P390 { get { return TSql.Int(0); } } public IDbParameterValue P391 { get { return TSql.Int(0); } } public IDbParameterValue P392 { get { return TSql.Int(0); } } public IDbParameterValue P393 { get { return TSql.Int(0); } } public IDbParameterValue P394 { get { return TSql.Int(0); } } public IDbParameterValue P395 { get { return TSql.Int(0); } } public IDbParameterValue P396 { get { return TSql.Int(0); } } public IDbParameterValue P397 { get { return TSql.Int(0); } } public IDbParameterValue P398 { get { return TSql.Int(0); } } public IDbParameterValue P399 { get { return TSql.Int(0); } } public IDbParameterValue P400 { get { return TSql.Int(0); } } public IDbParameterValue P401 { get { return TSql.Int(0); } } public IDbParameterValue P402 { get { return TSql.Int(0); } } public IDbParameterValue P403 { get { return TSql.Int(0); } } public IDbParameterValue P404 { get { return TSql.Int(0); } } public IDbParameterValue P405 { get { return TSql.Int(0); } } public IDbParameterValue P406 { get { return TSql.Int(0); } } public IDbParameterValue P407 { get { return TSql.Int(0); } } public IDbParameterValue P408 { get { return TSql.Int(0); } } public IDbParameterValue P409 { get { return TSql.Int(0); } } public IDbParameterValue P410 { get { return TSql.Int(0); } } public IDbParameterValue P411 { get { return TSql.Int(0); } } public IDbParameterValue P412 { get { return TSql.Int(0); } } public IDbParameterValue P413 { get { return TSql.Int(0); } } public IDbParameterValue P414 { get { return TSql.Int(0); } } public IDbParameterValue P415 { get { return TSql.Int(0); } } public IDbParameterValue P416 { get { return TSql.Int(0); } } public IDbParameterValue P417 { get { return TSql.Int(0); } } public IDbParameterValue P418 { get { return TSql.Int(0); } } public IDbParameterValue P419 { get { return TSql.Int(0); } } public IDbParameterValue P420 { get { return TSql.Int(0); } } public IDbParameterValue P421 { get { return TSql.Int(0); } } public IDbParameterValue P422 { get { return TSql.Int(0); } } public IDbParameterValue P423 { get { return TSql.Int(0); } } public IDbParameterValue P424 { get { return TSql.Int(0); } } public IDbParameterValue P425 { get { return TSql.Int(0); } } public IDbParameterValue P426 { get { return TSql.Int(0); } } public IDbParameterValue P427 { get { return TSql.Int(0); } } public IDbParameterValue P428 { get { return TSql.Int(0); } } public IDbParameterValue P429 { get { return TSql.Int(0); } } public IDbParameterValue P430 { get { return TSql.Int(0); } } public IDbParameterValue P431 { get { return TSql.Int(0); } } public IDbParameterValue P432 { get { return TSql.Int(0); } } public IDbParameterValue P433 { get { return TSql.Int(0); } } public IDbParameterValue P434 { get { return TSql.Int(0); } } public IDbParameterValue P435 { get { return TSql.Int(0); } } public IDbParameterValue P436 { get { return TSql.Int(0); } } public IDbParameterValue P437 { get { return TSql.Int(0); } } public IDbParameterValue P438 { get { return TSql.Int(0); } } public IDbParameterValue P439 { get { return TSql.Int(0); } } public IDbParameterValue P440 { get { return TSql.Int(0); } } public IDbParameterValue P441 { get { return TSql.Int(0); } } public IDbParameterValue P442 { get { return TSql.Int(0); } } public IDbParameterValue P443 { get { return TSql.Int(0); } } public IDbParameterValue P444 { get { return TSql.Int(0); } } public IDbParameterValue P445 { get { return TSql.Int(0); } } public IDbParameterValue P446 { get { return TSql.Int(0); } } public IDbParameterValue P447 { get { return TSql.Int(0); } } public IDbParameterValue P448 { get { return TSql.Int(0); } } public IDbParameterValue P449 { get { return TSql.Int(0); } } public IDbParameterValue P450 { get { return TSql.Int(0); } } public IDbParameterValue P451 { get { return TSql.Int(0); } } public IDbParameterValue P452 { get { return TSql.Int(0); } } public IDbParameterValue P453 { get { return TSql.Int(0); } } public IDbParameterValue P454 { get { return TSql.Int(0); } } public IDbParameterValue P455 { get { return TSql.Int(0); } } public IDbParameterValue P456 { get { return TSql.Int(0); } } public IDbParameterValue P457 { get { return TSql.Int(0); } } public IDbParameterValue P458 { get { return TSql.Int(0); } } public IDbParameterValue P459 { get { return TSql.Int(0); } } public IDbParameterValue P460 { get { return TSql.Int(0); } } public IDbParameterValue P461 { get { return TSql.Int(0); } } public IDbParameterValue P462 { get { return TSql.Int(0); } } public IDbParameterValue P463 { get { return TSql.Int(0); } } public IDbParameterValue P464 { get { return TSql.Int(0); } } public IDbParameterValue P465 { get { return TSql.Int(0); } } public IDbParameterValue P466 { get { return TSql.Int(0); } } public IDbParameterValue P467 { get { return TSql.Int(0); } } public IDbParameterValue P468 { get { return TSql.Int(0); } } public IDbParameterValue P469 { get { return TSql.Int(0); } } public IDbParameterValue P470 { get { return TSql.Int(0); } } public IDbParameterValue P471 { get { return TSql.Int(0); } } public IDbParameterValue P472 { get { return TSql.Int(0); } } public IDbParameterValue P473 { get { return TSql.Int(0); } } public IDbParameterValue P474 { get { return TSql.Int(0); } } public IDbParameterValue P475 { get { return TSql.Int(0); } } public IDbParameterValue P476 { get { return TSql.Int(0); } } public IDbParameterValue P477 { get { return TSql.Int(0); } } public IDbParameterValue P478 { get { return TSql.Int(0); } } public IDbParameterValue P479 { get { return TSql.Int(0); } } public IDbParameterValue P480 { get { return TSql.Int(0); } } public IDbParameterValue P481 { get { return TSql.Int(0); } } public IDbParameterValue P482 { get { return TSql.Int(0); } } public IDbParameterValue P483 { get { return TSql.Int(0); } } public IDbParameterValue P484 { get { return TSql.Int(0); } } public IDbParameterValue P485 { get { return TSql.Int(0); } } public IDbParameterValue P486 { get { return TSql.Int(0); } } public IDbParameterValue P487 { get { return TSql.Int(0); } } public IDbParameterValue P488 { get { return TSql.Int(0); } } public IDbParameterValue P489 { get { return TSql.Int(0); } } public IDbParameterValue P490 { get { return TSql.Int(0); } } public IDbParameterValue P491 { get { return TSql.Int(0); } } public IDbParameterValue P492 { get { return TSql.Int(0); } } public IDbParameterValue P493 { get { return TSql.Int(0); } } public IDbParameterValue P494 { get { return TSql.Int(0); } } public IDbParameterValue P495 { get { return TSql.Int(0); } } public IDbParameterValue P496 { get { return TSql.Int(0); } } public IDbParameterValue P497 { get { return TSql.Int(0); } } public IDbParameterValue P498 { get { return TSql.Int(0); } } public IDbParameterValue P499 { get { return TSql.Int(0); } } public IDbParameterValue P500 { get { return TSql.Int(0); } } public IDbParameterValue P501 { get { return TSql.Int(0); } } public IDbParameterValue P502 { get { return TSql.Int(0); } } public IDbParameterValue P503 { get { return TSql.Int(0); } } public IDbParameterValue P504 { get { return TSql.Int(0); } } public IDbParameterValue P505 { get { return TSql.Int(0); } } public IDbParameterValue P506 { get { return TSql.Int(0); } } public IDbParameterValue P507 { get { return TSql.Int(0); } } public IDbParameterValue P508 { get { return TSql.Int(0); } } public IDbParameterValue P509 { get { return TSql.Int(0); } } public IDbParameterValue P510 { get { return TSql.Int(0); } } public IDbParameterValue P511 { get { return TSql.Int(0); } } public IDbParameterValue P512 { get { return TSql.Int(0); } } public IDbParameterValue P513 { get { return TSql.Int(0); } } public IDbParameterValue P514 { get { return TSql.Int(0); } } public IDbParameterValue P515 { get { return TSql.Int(0); } } public IDbParameterValue P516 { get { return TSql.Int(0); } } public IDbParameterValue P517 { get { return TSql.Int(0); } } public IDbParameterValue P518 { get { return TSql.Int(0); } } public IDbParameterValue P519 { get { return TSql.Int(0); } } public IDbParameterValue P520 { get { return TSql.Int(0); } } public IDbParameterValue P521 { get { return TSql.Int(0); } } public IDbParameterValue P522 { get { return TSql.Int(0); } } public IDbParameterValue P523 { get { return TSql.Int(0); } } public IDbParameterValue P524 { get { return TSql.Int(0); } } public IDbParameterValue P525 { get { return TSql.Int(0); } } public IDbParameterValue P526 { get { return TSql.Int(0); } } public IDbParameterValue P527 { get { return TSql.Int(0); } } public IDbParameterValue P528 { get { return TSql.Int(0); } } public IDbParameterValue P529 { get { return TSql.Int(0); } } public IDbParameterValue P530 { get { return TSql.Int(0); } } public IDbParameterValue P531 { get { return TSql.Int(0); } } public IDbParameterValue P532 { get { return TSql.Int(0); } } public IDbParameterValue P533 { get { return TSql.Int(0); } } public IDbParameterValue P534 { get { return TSql.Int(0); } } public IDbParameterValue P535 { get { return TSql.Int(0); } } public IDbParameterValue P536 { get { return TSql.Int(0); } } public IDbParameterValue P537 { get { return TSql.Int(0); } } public IDbParameterValue P538 { get { return TSql.Int(0); } } public IDbParameterValue P539 { get { return TSql.Int(0); } } public IDbParameterValue P540 { get { return TSql.Int(0); } } public IDbParameterValue P541 { get { return TSql.Int(0); } } public IDbParameterValue P542 { get { return TSql.Int(0); } } public IDbParameterValue P543 { get { return TSql.Int(0); } } public IDbParameterValue P544 { get { return TSql.Int(0); } } public IDbParameterValue P545 { get { return TSql.Int(0); } } public IDbParameterValue P546 { get { return TSql.Int(0); } } public IDbParameterValue P547 { get { return TSql.Int(0); } } public IDbParameterValue P548 { get { return TSql.Int(0); } } public IDbParameterValue P549 { get { return TSql.Int(0); } } public IDbParameterValue P550 { get { return TSql.Int(0); } } public IDbParameterValue P551 { get { return TSql.Int(0); } } public IDbParameterValue P552 { get { return TSql.Int(0); } } public IDbParameterValue P553 { get { return TSql.Int(0); } } public IDbParameterValue P554 { get { return TSql.Int(0); } } public IDbParameterValue P555 { get { return TSql.Int(0); } } public IDbParameterValue P556 { get { return TSql.Int(0); } } public IDbParameterValue P557 { get { return TSql.Int(0); } } public IDbParameterValue P558 { get { return TSql.Int(0); } } public IDbParameterValue P559 { get { return TSql.Int(0); } } public IDbParameterValue P560 { get { return TSql.Int(0); } } public IDbParameterValue P561 { get { return TSql.Int(0); } } public IDbParameterValue P562 { get { return TSql.Int(0); } } public IDbParameterValue P563 { get { return TSql.Int(0); } } public IDbParameterValue P564 { get { return TSql.Int(0); } } public IDbParameterValue P565 { get { return TSql.Int(0); } } public IDbParameterValue P566 { get { return TSql.Int(0); } } public IDbParameterValue P567 { get { return TSql.Int(0); } } public IDbParameterValue P568 { get { return TSql.Int(0); } } public IDbParameterValue P569 { get { return TSql.Int(0); } } public IDbParameterValue P570 { get { return TSql.Int(0); } } public IDbParameterValue P571 { get { return TSql.Int(0); } } public IDbParameterValue P572 { get { return TSql.Int(0); } } public IDbParameterValue P573 { get { return TSql.Int(0); } } public IDbParameterValue P574 { get { return TSql.Int(0); } } public IDbParameterValue P575 { get { return TSql.Int(0); } } public IDbParameterValue P576 { get { return TSql.Int(0); } } public IDbParameterValue P577 { get { return TSql.Int(0); } } public IDbParameterValue P578 { get { return TSql.Int(0); } } public IDbParameterValue P579 { get { return TSql.Int(0); } } public IDbParameterValue P580 { get { return TSql.Int(0); } } public IDbParameterValue P581 { get { return TSql.Int(0); } } public IDbParameterValue P582 { get { return TSql.Int(0); } } public IDbParameterValue P583 { get { return TSql.Int(0); } } public IDbParameterValue P584 { get { return TSql.Int(0); } } public IDbParameterValue P585 { get { return TSql.Int(0); } } public IDbParameterValue P586 { get { return TSql.Int(0); } } public IDbParameterValue P587 { get { return TSql.Int(0); } } public IDbParameterValue P588 { get { return TSql.Int(0); } } public IDbParameterValue P589 { get { return TSql.Int(0); } } public IDbParameterValue P590 { get { return TSql.Int(0); } } public IDbParameterValue P591 { get { return TSql.Int(0); } } public IDbParameterValue P592 { get { return TSql.Int(0); } } public IDbParameterValue P593 { get { return TSql.Int(0); } } public IDbParameterValue P594 { get { return TSql.Int(0); } } public IDbParameterValue P595 { get { return TSql.Int(0); } } public IDbParameterValue P596 { get { return TSql.Int(0); } } public IDbParameterValue P597 { get { return TSql.Int(0); } } public IDbParameterValue P598 { get { return TSql.Int(0); } } public IDbParameterValue P599 { get { return TSql.Int(0); } } public IDbParameterValue P600 { get { return TSql.Int(0); } } public IDbParameterValue P601 { get { return TSql.Int(0); } } public IDbParameterValue P602 { get { return TSql.Int(0); } } public IDbParameterValue P603 { get { return TSql.Int(0); } } public IDbParameterValue P604 { get { return TSql.Int(0); } } public IDbParameterValue P605 { get { return TSql.Int(0); } } public IDbParameterValue P606 { get { return TSql.Int(0); } } public IDbParameterValue P607 { get { return TSql.Int(0); } } public IDbParameterValue P608 { get { return TSql.Int(0); } } public IDbParameterValue P609 { get { return TSql.Int(0); } } public IDbParameterValue P610 { get { return TSql.Int(0); } } public IDbParameterValue P611 { get { return TSql.Int(0); } } public IDbParameterValue P612 { get { return TSql.Int(0); } } public IDbParameterValue P613 { get { return TSql.Int(0); } } public IDbParameterValue P614 { get { return TSql.Int(0); } } public IDbParameterValue P615 { get { return TSql.Int(0); } } public IDbParameterValue P616 { get { return TSql.Int(0); } } public IDbParameterValue P617 { get { return TSql.Int(0); } } public IDbParameterValue P618 { get { return TSql.Int(0); } } public IDbParameterValue P619 { get { return TSql.Int(0); } } public IDbParameterValue P620 { get { return TSql.Int(0); } } public IDbParameterValue P621 { get { return TSql.Int(0); } } public IDbParameterValue P622 { get { return TSql.Int(0); } } public IDbParameterValue P623 { get { return TSql.Int(0); } } public IDbParameterValue P624 { get { return TSql.Int(0); } } public IDbParameterValue P625 { get { return TSql.Int(0); } } public IDbParameterValue P626 { get { return TSql.Int(0); } } public IDbParameterValue P627 { get { return TSql.Int(0); } } public IDbParameterValue P628 { get { return TSql.Int(0); } } public IDbParameterValue P629 { get { return TSql.Int(0); } } public IDbParameterValue P630 { get { return TSql.Int(0); } } public IDbParameterValue P631 { get { return TSql.Int(0); } } public IDbParameterValue P632 { get { return TSql.Int(0); } } public IDbParameterValue P633 { get { return TSql.Int(0); } } public IDbParameterValue P634 { get { return TSql.Int(0); } } public IDbParameterValue P635 { get { return TSql.Int(0); } } public IDbParameterValue P636 { get { return TSql.Int(0); } } public IDbParameterValue P637 { get { return TSql.Int(0); } } public IDbParameterValue P638 { get { return TSql.Int(0); } } public IDbParameterValue P639 { get { return TSql.Int(0); } } public IDbParameterValue P640 { get { return TSql.Int(0); } } public IDbParameterValue P641 { get { return TSql.Int(0); } } public IDbParameterValue P642 { get { return TSql.Int(0); } } public IDbParameterValue P643 { get { return TSql.Int(0); } } public IDbParameterValue P644 { get { return TSql.Int(0); } } public IDbParameterValue P645 { get { return TSql.Int(0); } } public IDbParameterValue P646 { get { return TSql.Int(0); } } public IDbParameterValue P647 { get { return TSql.Int(0); } } public IDbParameterValue P648 { get { return TSql.Int(0); } } public IDbParameterValue P649 { get { return TSql.Int(0); } } public IDbParameterValue P650 { get { return TSql.Int(0); } } public IDbParameterValue P651 { get { return TSql.Int(0); } } public IDbParameterValue P652 { get { return TSql.Int(0); } } public IDbParameterValue P653 { get { return TSql.Int(0); } } public IDbParameterValue P654 { get { return TSql.Int(0); } } public IDbParameterValue P655 { get { return TSql.Int(0); } } public IDbParameterValue P656 { get { return TSql.Int(0); } } public IDbParameterValue P657 { get { return TSql.Int(0); } } public IDbParameterValue P658 { get { return TSql.Int(0); } } public IDbParameterValue P659 { get { return TSql.Int(0); } } public IDbParameterValue P660 { get { return TSql.Int(0); } } public IDbParameterValue P661 { get { return TSql.Int(0); } } public IDbParameterValue P662 { get { return TSql.Int(0); } } public IDbParameterValue P663 { get { return TSql.Int(0); } } public IDbParameterValue P664 { get { return TSql.Int(0); } } public IDbParameterValue P665 { get { return TSql.Int(0); } } public IDbParameterValue P666 { get { return TSql.Int(0); } } public IDbParameterValue P667 { get { return TSql.Int(0); } } public IDbParameterValue P668 { get { return TSql.Int(0); } } public IDbParameterValue P669 { get { return TSql.Int(0); } } public IDbParameterValue P670 { get { return TSql.Int(0); } } public IDbParameterValue P671 { get { return TSql.Int(0); } } public IDbParameterValue P672 { get { return TSql.Int(0); } } public IDbParameterValue P673 { get { return TSql.Int(0); } } public IDbParameterValue P674 { get { return TSql.Int(0); } } public IDbParameterValue P675 { get { return TSql.Int(0); } } public IDbParameterValue P676 { get { return TSql.Int(0); } } public IDbParameterValue P677 { get { return TSql.Int(0); } } public IDbParameterValue P678 { get { return TSql.Int(0); } } public IDbParameterValue P679 { get { return TSql.Int(0); } } public IDbParameterValue P680 { get { return TSql.Int(0); } } public IDbParameterValue P681 { get { return TSql.Int(0); } } public IDbParameterValue P682 { get { return TSql.Int(0); } } public IDbParameterValue P683 { get { return TSql.Int(0); } } public IDbParameterValue P684 { get { return TSql.Int(0); } } public IDbParameterValue P685 { get { return TSql.Int(0); } } public IDbParameterValue P686 { get { return TSql.Int(0); } } public IDbParameterValue P687 { get { return TSql.Int(0); } } public IDbParameterValue P688 { get { return TSql.Int(0); } } public IDbParameterValue P689 { get { return TSql.Int(0); } } public IDbParameterValue P690 { get { return TSql.Int(0); } } public IDbParameterValue P691 { get { return TSql.Int(0); } } public IDbParameterValue P692 { get { return TSql.Int(0); } } public IDbParameterValue P693 { get { return TSql.Int(0); } } public IDbParameterValue P694 { get { return TSql.Int(0); } } public IDbParameterValue P695 { get { return TSql.Int(0); } } public IDbParameterValue P696 { get { return TSql.Int(0); } } public IDbParameterValue P697 { get { return TSql.Int(0); } } public IDbParameterValue P698 { get { return TSql.Int(0); } } public IDbParameterValue P699 { get { return TSql.Int(0); } } public IDbParameterValue P700 { get { return TSql.Int(0); } } public IDbParameterValue P701 { get { return TSql.Int(0); } } public IDbParameterValue P702 { get { return TSql.Int(0); } } public IDbParameterValue P703 { get { return TSql.Int(0); } } public IDbParameterValue P704 { get { return TSql.Int(0); } } public IDbParameterValue P705 { get { return TSql.Int(0); } } public IDbParameterValue P706 { get { return TSql.Int(0); } } public IDbParameterValue P707 { get { return TSql.Int(0); } } public IDbParameterValue P708 { get { return TSql.Int(0); } } public IDbParameterValue P709 { get { return TSql.Int(0); } } public IDbParameterValue P710 { get { return TSql.Int(0); } } public IDbParameterValue P711 { get { return TSql.Int(0); } } public IDbParameterValue P712 { get { return TSql.Int(0); } } public IDbParameterValue P713 { get { return TSql.Int(0); } } public IDbParameterValue P714 { get { return TSql.Int(0); } } public IDbParameterValue P715 { get { return TSql.Int(0); } } public IDbParameterValue P716 { get { return TSql.Int(0); } } public IDbParameterValue P717 { get { return TSql.Int(0); } } public IDbParameterValue P718 { get { return TSql.Int(0); } } public IDbParameterValue P719 { get { return TSql.Int(0); } } public IDbParameterValue P720 { get { return TSql.Int(0); } } public IDbParameterValue P721 { get { return TSql.Int(0); } } public IDbParameterValue P722 { get { return TSql.Int(0); } } public IDbParameterValue P723 { get { return TSql.Int(0); } } public IDbParameterValue P724 { get { return TSql.Int(0); } } public IDbParameterValue P725 { get { return TSql.Int(0); } } public IDbParameterValue P726 { get { return TSql.Int(0); } } public IDbParameterValue P727 { get { return TSql.Int(0); } } public IDbParameterValue P728 { get { return TSql.Int(0); } } public IDbParameterValue P729 { get { return TSql.Int(0); } } public IDbParameterValue P730 { get { return TSql.Int(0); } } public IDbParameterValue P731 { get { return TSql.Int(0); } } public IDbParameterValue P732 { get { return TSql.Int(0); } } public IDbParameterValue P733 { get { return TSql.Int(0); } } public IDbParameterValue P734 { get { return TSql.Int(0); } } public IDbParameterValue P735 { get { return TSql.Int(0); } } public IDbParameterValue P736 { get { return TSql.Int(0); } } public IDbParameterValue P737 { get { return TSql.Int(0); } } public IDbParameterValue P738 { get { return TSql.Int(0); } } public IDbParameterValue P739 { get { return TSql.Int(0); } } public IDbParameterValue P740 { get { return TSql.Int(0); } } public IDbParameterValue P741 { get { return TSql.Int(0); } } public IDbParameterValue P742 { get { return TSql.Int(0); } } public IDbParameterValue P743 { get { return TSql.Int(0); } } public IDbParameterValue P744 { get { return TSql.Int(0); } } public IDbParameterValue P745 { get { return TSql.Int(0); } } public IDbParameterValue P746 { get { return TSql.Int(0); } } public IDbParameterValue P747 { get { return TSql.Int(0); } } public IDbParameterValue P748 { get { return TSql.Int(0); } } public IDbParameterValue P749 { get { return TSql.Int(0); } } public IDbParameterValue P750 { get { return TSql.Int(0); } } public IDbParameterValue P751 { get { return TSql.Int(0); } } public IDbParameterValue P752 { get { return TSql.Int(0); } } public IDbParameterValue P753 { get { return TSql.Int(0); } } public IDbParameterValue P754 { get { return TSql.Int(0); } } public IDbParameterValue P755 { get { return TSql.Int(0); } } public IDbParameterValue P756 { get { return TSql.Int(0); } } public IDbParameterValue P757 { get { return TSql.Int(0); } } public IDbParameterValue P758 { get { return TSql.Int(0); } } public IDbParameterValue P759 { get { return TSql.Int(0); } } public IDbParameterValue P760 { get { return TSql.Int(0); } } public IDbParameterValue P761 { get { return TSql.Int(0); } } public IDbParameterValue P762 { get { return TSql.Int(0); } } public IDbParameterValue P763 { get { return TSql.Int(0); } } public IDbParameterValue P764 { get { return TSql.Int(0); } } public IDbParameterValue P765 { get { return TSql.Int(0); } } public IDbParameterValue P766 { get { return TSql.Int(0); } } public IDbParameterValue P767 { get { return TSql.Int(0); } } public IDbParameterValue P768 { get { return TSql.Int(0); } } public IDbParameterValue P769 { get { return TSql.Int(0); } } public IDbParameterValue P770 { get { return TSql.Int(0); } } public IDbParameterValue P771 { get { return TSql.Int(0); } } public IDbParameterValue P772 { get { return TSql.Int(0); } } public IDbParameterValue P773 { get { return TSql.Int(0); } } public IDbParameterValue P774 { get { return TSql.Int(0); } } public IDbParameterValue P775 { get { return TSql.Int(0); } } public IDbParameterValue P776 { get { return TSql.Int(0); } } public IDbParameterValue P777 { get { return TSql.Int(0); } } public IDbParameterValue P778 { get { return TSql.Int(0); } } public IDbParameterValue P779 { get { return TSql.Int(0); } } public IDbParameterValue P780 { get { return TSql.Int(0); } } public IDbParameterValue P781 { get { return TSql.Int(0); } } public IDbParameterValue P782 { get { return TSql.Int(0); } } public IDbParameterValue P783 { get { return TSql.Int(0); } } public IDbParameterValue P784 { get { return TSql.Int(0); } } public IDbParameterValue P785 { get { return TSql.Int(0); } } public IDbParameterValue P786 { get { return TSql.Int(0); } } public IDbParameterValue P787 { get { return TSql.Int(0); } } public IDbParameterValue P788 { get { return TSql.Int(0); } } public IDbParameterValue P789 { get { return TSql.Int(0); } } public IDbParameterValue P790 { get { return TSql.Int(0); } } public IDbParameterValue P791 { get { return TSql.Int(0); } } public IDbParameterValue P792 { get { return TSql.Int(0); } } public IDbParameterValue P793 { get { return TSql.Int(0); } } public IDbParameterValue P794 { get { return TSql.Int(0); } } public IDbParameterValue P795 { get { return TSql.Int(0); } } public IDbParameterValue P796 { get { return TSql.Int(0); } } public IDbParameterValue P797 { get { return TSql.Int(0); } } public IDbParameterValue P798 { get { return TSql.Int(0); } } public IDbParameterValue P799 { get { return TSql.Int(0); } } public IDbParameterValue P800 { get { return TSql.Int(0); } } public IDbParameterValue P801 { get { return TSql.Int(0); } } public IDbParameterValue P802 { get { return TSql.Int(0); } } public IDbParameterValue P803 { get { return TSql.Int(0); } } public IDbParameterValue P804 { get { return TSql.Int(0); } } public IDbParameterValue P805 { get { return TSql.Int(0); } } public IDbParameterValue P806 { get { return TSql.Int(0); } } public IDbParameterValue P807 { get { return TSql.Int(0); } } public IDbParameterValue P808 { get { return TSql.Int(0); } } public IDbParameterValue P809 { get { return TSql.Int(0); } } public IDbParameterValue P810 { get { return TSql.Int(0); } } public IDbParameterValue P811 { get { return TSql.Int(0); } } public IDbParameterValue P812 { get { return TSql.Int(0); } } public IDbParameterValue P813 { get { return TSql.Int(0); } } public IDbParameterValue P814 { get { return TSql.Int(0); } } public IDbParameterValue P815 { get { return TSql.Int(0); } } public IDbParameterValue P816 { get { return TSql.Int(0); } } public IDbParameterValue P817 { get { return TSql.Int(0); } } public IDbParameterValue P818 { get { return TSql.Int(0); } } public IDbParameterValue P819 { get { return TSql.Int(0); } } public IDbParameterValue P820 { get { return TSql.Int(0); } } public IDbParameterValue P821 { get { return TSql.Int(0); } } public IDbParameterValue P822 { get { return TSql.Int(0); } } public IDbParameterValue P823 { get { return TSql.Int(0); } } public IDbParameterValue P824 { get { return TSql.Int(0); } } public IDbParameterValue P825 { get { return TSql.Int(0); } } public IDbParameterValue P826 { get { return TSql.Int(0); } } public IDbParameterValue P827 { get { return TSql.Int(0); } } public IDbParameterValue P828 { get { return TSql.Int(0); } } public IDbParameterValue P829 { get { return TSql.Int(0); } } public IDbParameterValue P830 { get { return TSql.Int(0); } } public IDbParameterValue P831 { get { return TSql.Int(0); } } public IDbParameterValue P832 { get { return TSql.Int(0); } } public IDbParameterValue P833 { get { return TSql.Int(0); } } public IDbParameterValue P834 { get { return TSql.Int(0); } } public IDbParameterValue P835 { get { return TSql.Int(0); } } public IDbParameterValue P836 { get { return TSql.Int(0); } } public IDbParameterValue P837 { get { return TSql.Int(0); } } public IDbParameterValue P838 { get { return TSql.Int(0); } } public IDbParameterValue P839 { get { return TSql.Int(0); } } public IDbParameterValue P840 { get { return TSql.Int(0); } } public IDbParameterValue P841 { get { return TSql.Int(0); } } public IDbParameterValue P842 { get { return TSql.Int(0); } } public IDbParameterValue P843 { get { return TSql.Int(0); } } public IDbParameterValue P844 { get { return TSql.Int(0); } } public IDbParameterValue P845 { get { return TSql.Int(0); } } public IDbParameterValue P846 { get { return TSql.Int(0); } } public IDbParameterValue P847 { get { return TSql.Int(0); } } public IDbParameterValue P848 { get { return TSql.Int(0); } } public IDbParameterValue P849 { get { return TSql.Int(0); } } public IDbParameterValue P850 { get { return TSql.Int(0); } } public IDbParameterValue P851 { get { return TSql.Int(0); } } public IDbParameterValue P852 { get { return TSql.Int(0); } } public IDbParameterValue P853 { get { return TSql.Int(0); } } public IDbParameterValue P854 { get { return TSql.Int(0); } } public IDbParameterValue P855 { get { return TSql.Int(0); } } public IDbParameterValue P856 { get { return TSql.Int(0); } } public IDbParameterValue P857 { get { return TSql.Int(0); } } public IDbParameterValue P858 { get { return TSql.Int(0); } } public IDbParameterValue P859 { get { return TSql.Int(0); } } public IDbParameterValue P860 { get { return TSql.Int(0); } } public IDbParameterValue P861 { get { return TSql.Int(0); } } public IDbParameterValue P862 { get { return TSql.Int(0); } } public IDbParameterValue P863 { get { return TSql.Int(0); } } public IDbParameterValue P864 { get { return TSql.Int(0); } } public IDbParameterValue P865 { get { return TSql.Int(0); } } public IDbParameterValue P866 { get { return TSql.Int(0); } } public IDbParameterValue P867 { get { return TSql.Int(0); } } public IDbParameterValue P868 { get { return TSql.Int(0); } } public IDbParameterValue P869 { get { return TSql.Int(0); } } public IDbParameterValue P870 { get { return TSql.Int(0); } } public IDbParameterValue P871 { get { return TSql.Int(0); } } public IDbParameterValue P872 { get { return TSql.Int(0); } } public IDbParameterValue P873 { get { return TSql.Int(0); } } public IDbParameterValue P874 { get { return TSql.Int(0); } } public IDbParameterValue P875 { get { return TSql.Int(0); } } public IDbParameterValue P876 { get { return TSql.Int(0); } } public IDbParameterValue P877 { get { return TSql.Int(0); } } public IDbParameterValue P878 { get { return TSql.Int(0); } } public IDbParameterValue P879 { get { return TSql.Int(0); } } public IDbParameterValue P880 { get { return TSql.Int(0); } } public IDbParameterValue P881 { get { return TSql.Int(0); } } public IDbParameterValue P882 { get { return TSql.Int(0); } } public IDbParameterValue P883 { get { return TSql.Int(0); } } public IDbParameterValue P884 { get { return TSql.Int(0); } } public IDbParameterValue P885 { get { return TSql.Int(0); } } public IDbParameterValue P886 { get { return TSql.Int(0); } } public IDbParameterValue P887 { get { return TSql.Int(0); } } public IDbParameterValue P888 { get { return TSql.Int(0); } } public IDbParameterValue P889 { get { return TSql.Int(0); } } public IDbParameterValue P890 { get { return TSql.Int(0); } } public IDbParameterValue P891 { get { return TSql.Int(0); } } public IDbParameterValue P892 { get { return TSql.Int(0); } } public IDbParameterValue P893 { get { return TSql.Int(0); } } public IDbParameterValue P894 { get { return TSql.Int(0); } } public IDbParameterValue P895 { get { return TSql.Int(0); } } public IDbParameterValue P896 { get { return TSql.Int(0); } } public IDbParameterValue P897 { get { return TSql.Int(0); } } public IDbParameterValue P898 { get { return TSql.Int(0); } } public IDbParameterValue P899 { get { return TSql.Int(0); } } public IDbParameterValue P900 { get { return TSql.Int(0); } } public IDbParameterValue P901 { get { return TSql.Int(0); } } public IDbParameterValue P902 { get { return TSql.Int(0); } } public IDbParameterValue P903 { get { return TSql.Int(0); } } public IDbParameterValue P904 { get { return TSql.Int(0); } } public IDbParameterValue P905 { get { return TSql.Int(0); } } public IDbParameterValue P906 { get { return TSql.Int(0); } } public IDbParameterValue P907 { get { return TSql.Int(0); } } public IDbParameterValue P908 { get { return TSql.Int(0); } } public IDbParameterValue P909 { get { return TSql.Int(0); } } public IDbParameterValue P910 { get { return TSql.Int(0); } } public IDbParameterValue P911 { get { return TSql.Int(0); } } public IDbParameterValue P912 { get { return TSql.Int(0); } } public IDbParameterValue P913 { get { return TSql.Int(0); } } public IDbParameterValue P914 { get { return TSql.Int(0); } } public IDbParameterValue P915 { get { return TSql.Int(0); } } public IDbParameterValue P916 { get { return TSql.Int(0); } } public IDbParameterValue P917 { get { return TSql.Int(0); } } public IDbParameterValue P918 { get { return TSql.Int(0); } } public IDbParameterValue P919 { get { return TSql.Int(0); } } public IDbParameterValue P920 { get { return TSql.Int(0); } } public IDbParameterValue P921 { get { return TSql.Int(0); } } public IDbParameterValue P922 { get { return TSql.Int(0); } } public IDbParameterValue P923 { get { return TSql.Int(0); } } public IDbParameterValue P924 { get { return TSql.Int(0); } } public IDbParameterValue P925 { get { return TSql.Int(0); } } public IDbParameterValue P926 { get { return TSql.Int(0); } } public IDbParameterValue P927 { get { return TSql.Int(0); } } public IDbParameterValue P928 { get { return TSql.Int(0); } } public IDbParameterValue P929 { get { return TSql.Int(0); } } public IDbParameterValue P930 { get { return TSql.Int(0); } } public IDbParameterValue P931 { get { return TSql.Int(0); } } public IDbParameterValue P932 { get { return TSql.Int(0); } } public IDbParameterValue P933 { get { return TSql.Int(0); } } public IDbParameterValue P934 { get { return TSql.Int(0); } } public IDbParameterValue P935 { get { return TSql.Int(0); } } public IDbParameterValue P936 { get { return TSql.Int(0); } } public IDbParameterValue P937 { get { return TSql.Int(0); } } public IDbParameterValue P938 { get { return TSql.Int(0); } } public IDbParameterValue P939 { get { return TSql.Int(0); } } public IDbParameterValue P940 { get { return TSql.Int(0); } } public IDbParameterValue P941 { get { return TSql.Int(0); } } public IDbParameterValue P942 { get { return TSql.Int(0); } } public IDbParameterValue P943 { get { return TSql.Int(0); } } public IDbParameterValue P944 { get { return TSql.Int(0); } } public IDbParameterValue P945 { get { return TSql.Int(0); } } public IDbParameterValue P946 { get { return TSql.Int(0); } } public IDbParameterValue P947 { get { return TSql.Int(0); } } public IDbParameterValue P948 { get { return TSql.Int(0); } } public IDbParameterValue P949 { get { return TSql.Int(0); } } public IDbParameterValue P950 { get { return TSql.Int(0); } } public IDbParameterValue P951 { get { return TSql.Int(0); } } public IDbParameterValue P952 { get { return TSql.Int(0); } } public IDbParameterValue P953 { get { return TSql.Int(0); } } public IDbParameterValue P954 { get { return TSql.Int(0); } } public IDbParameterValue P955 { get { return TSql.Int(0); } } public IDbParameterValue P956 { get { return TSql.Int(0); } } public IDbParameterValue P957 { get { return TSql.Int(0); } } public IDbParameterValue P958 { get { return TSql.Int(0); } } public IDbParameterValue P959 { get { return TSql.Int(0); } } public IDbParameterValue P960 { get { return TSql.Int(0); } } public IDbParameterValue P961 { get { return TSql.Int(0); } } public IDbParameterValue P962 { get { return TSql.Int(0); } } public IDbParameterValue P963 { get { return TSql.Int(0); } } public IDbParameterValue P964 { get { return TSql.Int(0); } } public IDbParameterValue P965 { get { return TSql.Int(0); } } public IDbParameterValue P966 { get { return TSql.Int(0); } } public IDbParameterValue P967 { get { return TSql.Int(0); } } public IDbParameterValue P968 { get { return TSql.Int(0); } } public IDbParameterValue P969 { get { return TSql.Int(0); } } public IDbParameterValue P970 { get { return TSql.Int(0); } } public IDbParameterValue P971 { get { return TSql.Int(0); } } public IDbParameterValue P972 { get { return TSql.Int(0); } } public IDbParameterValue P973 { get { return TSql.Int(0); } } public IDbParameterValue P974 { get { return TSql.Int(0); } } public IDbParameterValue P975 { get { return TSql.Int(0); } } public IDbParameterValue P976 { get { return TSql.Int(0); } } public IDbParameterValue P977 { get { return TSql.Int(0); } } public IDbParameterValue P978 { get { return TSql.Int(0); } } public IDbParameterValue P979 { get { return TSql.Int(0); } } public IDbParameterValue P980 { get { return TSql.Int(0); } } public IDbParameterValue P981 { get { return TSql.Int(0); } } public IDbParameterValue P982 { get { return TSql.Int(0); } } public IDbParameterValue P983 { get { return TSql.Int(0); } } public IDbParameterValue P984 { get { return TSql.Int(0); } } public IDbParameterValue P985 { get { return TSql.Int(0); } } public IDbParameterValue P986 { get { return TSql.Int(0); } } public IDbParameterValue P987 { get { return TSql.Int(0); } } public IDbParameterValue P988 { get { return TSql.Int(0); } } public IDbParameterValue P989 { get { return TSql.Int(0); } } public IDbParameterValue P990 { get { return TSql.Int(0); } } public IDbParameterValue P991 { get { return TSql.Int(0); } } public IDbParameterValue P992 { get { return TSql.Int(0); } } public IDbParameterValue P993 { get { return TSql.Int(0); } } public IDbParameterValue P994 { get { return TSql.Int(0); } } public IDbParameterValue P995 { get { return TSql.Int(0); } } public IDbParameterValue P996 { get { return TSql.Int(0); } } public IDbParameterValue P997 { get { return TSql.Int(0); } } public IDbParameterValue P998 { get { return TSql.Int(0); } } public IDbParameterValue P999 { get { return TSql.Int(0); } } public IDbParameterValue P1000 { get { return TSql.Int(0); } } public IDbParameterValue P1001 { get { return TSql.Int(0); } } public IDbParameterValue P1002 { get { return TSql.Int(0); } } public IDbParameterValue P1003 { get { return TSql.Int(0); } } public IDbParameterValue P1004 { get { return TSql.Int(0); } } public IDbParameterValue P1005 { get { return TSql.Int(0); } } public IDbParameterValue P1006 { get { return TSql.Int(0); } } public IDbParameterValue P1007 { get { return TSql.Int(0); } } public IDbParameterValue P1008 { get { return TSql.Int(0); } } public IDbParameterValue P1009 { get { return TSql.Int(0); } } public IDbParameterValue P1010 { get { return TSql.Int(0); } } public IDbParameterValue P1011 { get { return TSql.Int(0); } } public IDbParameterValue P1012 { get { return TSql.Int(0); } } public IDbParameterValue P1013 { get { return TSql.Int(0); } } public IDbParameterValue P1014 { get { return TSql.Int(0); } } public IDbParameterValue P1015 { get { return TSql.Int(0); } } public IDbParameterValue P1016 { get { return TSql.Int(0); } } public IDbParameterValue P1017 { get { return TSql.Int(0); } } public IDbParameterValue P1018 { get { return TSql.Int(0); } } public IDbParameterValue P1019 { get { return TSql.Int(0); } } public IDbParameterValue P1020 { get { return TSql.Int(0); } } public IDbParameterValue P1021 { get { return TSql.Int(0); } } public IDbParameterValue P1022 { get { return TSql.Int(0); } } public IDbParameterValue P1023 { get { return TSql.Int(0); } } public IDbParameterValue P1024 { get { return TSql.Int(0); } } public IDbParameterValue P1025 { get { return TSql.Int(0); } } public IDbParameterValue P1026 { get { return TSql.Int(0); } } public IDbParameterValue P1027 { get { return TSql.Int(0); } } public IDbParameterValue P1028 { get { return TSql.Int(0); } } public IDbParameterValue P1029 { get { return TSql.Int(0); } } public IDbParameterValue P1030 { get { return TSql.Int(0); } } public IDbParameterValue P1031 { get { return TSql.Int(0); } } public IDbParameterValue P1032 { get { return TSql.Int(0); } } public IDbParameterValue P1033 { get { return TSql.Int(0); } } public IDbParameterValue P1034 { get { return TSql.Int(0); } } public IDbParameterValue P1035 { get { return TSql.Int(0); } } public IDbParameterValue P1036 { get { return TSql.Int(0); } } public IDbParameterValue P1037 { get { return TSql.Int(0); } } public IDbParameterValue P1038 { get { return TSql.Int(0); } } public IDbParameterValue P1039 { get { return TSql.Int(0); } } public IDbParameterValue P1040 { get { return TSql.Int(0); } } public IDbParameterValue P1041 { get { return TSql.Int(0); } } public IDbParameterValue P1042 { get { return TSql.Int(0); } } public IDbParameterValue P1043 { get { return TSql.Int(0); } } public IDbParameterValue P1044 { get { return TSql.Int(0); } } public IDbParameterValue P1045 { get { return TSql.Int(0); } } public IDbParameterValue P1046 { get { return TSql.Int(0); } } public IDbParameterValue P1047 { get { return TSql.Int(0); } } public IDbParameterValue P1048 { get { return TSql.Int(0); } } public IDbParameterValue P1049 { get { return TSql.Int(0); } } public IDbParameterValue P1050 { get { return TSql.Int(0); } } public IDbParameterValue P1051 { get { return TSql.Int(0); } } public IDbParameterValue P1052 { get { return TSql.Int(0); } } public IDbParameterValue P1053 { get { return TSql.Int(0); } } public IDbParameterValue P1054 { get { return TSql.Int(0); } } public IDbParameterValue P1055 { get { return TSql.Int(0); } } public IDbParameterValue P1056 { get { return TSql.Int(0); } } public IDbParameterValue P1057 { get { return TSql.Int(0); } } public IDbParameterValue P1058 { get { return TSql.Int(0); } } public IDbParameterValue P1059 { get { return TSql.Int(0); } } public IDbParameterValue P1060 { get { return TSql.Int(0); } } public IDbParameterValue P1061 { get { return TSql.Int(0); } } public IDbParameterValue P1062 { get { return TSql.Int(0); } } public IDbParameterValue P1063 { get { return TSql.Int(0); } } public IDbParameterValue P1064 { get { return TSql.Int(0); } } public IDbParameterValue P1065 { get { return TSql.Int(0); } } public IDbParameterValue P1066 { get { return TSql.Int(0); } } public IDbParameterValue P1067 { get { return TSql.Int(0); } } public IDbParameterValue P1068 { get { return TSql.Int(0); } } public IDbParameterValue P1069 { get { return TSql.Int(0); } } public IDbParameterValue P1070 { get { return TSql.Int(0); } } public IDbParameterValue P1071 { get { return TSql.Int(0); } } public IDbParameterValue P1072 { get { return TSql.Int(0); } } public IDbParameterValue P1073 { get { return TSql.Int(0); } } public IDbParameterValue P1074 { get { return TSql.Int(0); } } public IDbParameterValue P1075 { get { return TSql.Int(0); } } public IDbParameterValue P1076 { get { return TSql.Int(0); } } public IDbParameterValue P1077 { get { return TSql.Int(0); } } public IDbParameterValue P1078 { get { return TSql.Int(0); } } public IDbParameterValue P1079 { get { return TSql.Int(0); } } public IDbParameterValue P1080 { get { return TSql.Int(0); } } public IDbParameterValue P1081 { get { return TSql.Int(0); } } public IDbParameterValue P1082 { get { return TSql.Int(0); } } public IDbParameterValue P1083 { get { return TSql.Int(0); } } public IDbParameterValue P1084 { get { return TSql.Int(0); } } public IDbParameterValue P1085 { get { return TSql.Int(0); } } public IDbParameterValue P1086 { get { return TSql.Int(0); } } public IDbParameterValue P1087 { get { return TSql.Int(0); } } public IDbParameterValue P1088 { get { return TSql.Int(0); } } public IDbParameterValue P1089 { get { return TSql.Int(0); } } public IDbParameterValue P1090 { get { return TSql.Int(0); } } public IDbParameterValue P1091 { get { return TSql.Int(0); } } public IDbParameterValue P1092 { get { return TSql.Int(0); } } public IDbParameterValue P1093 { get { return TSql.Int(0); } } public IDbParameterValue P1094 { get { return TSql.Int(0); } } public IDbParameterValue P1095 { get { return TSql.Int(0); } } public IDbParameterValue P1096 { get { return TSql.Int(0); } } public IDbParameterValue P1097 { get { return TSql.Int(0); } } public IDbParameterValue P1098 { get { return TSql.Int(0); } } public IDbParameterValue P1099 { get { return TSql.Int(0); } } public IDbParameterValue P1100 { get { return TSql.Int(0); } } public IDbParameterValue P1101 { get { return TSql.Int(0); } } public IDbParameterValue P1102 { get { return TSql.Int(0); } } public IDbParameterValue P1103 { get { return TSql.Int(0); } } public IDbParameterValue P1104 { get { return TSql.Int(0); } } public IDbParameterValue P1105 { get { return TSql.Int(0); } } public IDbParameterValue P1106 { get { return TSql.Int(0); } } public IDbParameterValue P1107 { get { return TSql.Int(0); } } public IDbParameterValue P1108 { get { return TSql.Int(0); } } public IDbParameterValue P1109 { get { return TSql.Int(0); } } public IDbParameterValue P1110 { get { return TSql.Int(0); } } public IDbParameterValue P1111 { get { return TSql.Int(0); } } public IDbParameterValue P1112 { get { return TSql.Int(0); } } public IDbParameterValue P1113 { get { return TSql.Int(0); } } public IDbParameterValue P1114 { get { return TSql.Int(0); } } public IDbParameterValue P1115 { get { return TSql.Int(0); } } public IDbParameterValue P1116 { get { return TSql.Int(0); } } public IDbParameterValue P1117 { get { return TSql.Int(0); } } public IDbParameterValue P1118 { get { return TSql.Int(0); } } public IDbParameterValue P1119 { get { return TSql.Int(0); } } public IDbParameterValue P1120 { get { return TSql.Int(0); } } public IDbParameterValue P1121 { get { return TSql.Int(0); } } public IDbParameterValue P1122 { get { return TSql.Int(0); } } public IDbParameterValue P1123 { get { return TSql.Int(0); } } public IDbParameterValue P1124 { get { return TSql.Int(0); } } public IDbParameterValue P1125 { get { return TSql.Int(0); } } public IDbParameterValue P1126 { get { return TSql.Int(0); } } public IDbParameterValue P1127 { get { return TSql.Int(0); } } public IDbParameterValue P1128 { get { return TSql.Int(0); } } public IDbParameterValue P1129 { get { return TSql.Int(0); } } public IDbParameterValue P1130 { get { return TSql.Int(0); } } public IDbParameterValue P1131 { get { return TSql.Int(0); } } public IDbParameterValue P1132 { get { return TSql.Int(0); } } public IDbParameterValue P1133 { get { return TSql.Int(0); } } public IDbParameterValue P1134 { get { return TSql.Int(0); } } public IDbParameterValue P1135 { get { return TSql.Int(0); } } public IDbParameterValue P1136 { get { return TSql.Int(0); } } public IDbParameterValue P1137 { get { return TSql.Int(0); } } public IDbParameterValue P1138 { get { return TSql.Int(0); } } public IDbParameterValue P1139 { get { return TSql.Int(0); } } public IDbParameterValue P1140 { get { return TSql.Int(0); } } public IDbParameterValue P1141 { get { return TSql.Int(0); } } public IDbParameterValue P1142 { get { return TSql.Int(0); } } public IDbParameterValue P1143 { get { return TSql.Int(0); } } public IDbParameterValue P1144 { get { return TSql.Int(0); } } public IDbParameterValue P1145 { get { return TSql.Int(0); } } public IDbParameterValue P1146 { get { return TSql.Int(0); } } public IDbParameterValue P1147 { get { return TSql.Int(0); } } public IDbParameterValue P1148 { get { return TSql.Int(0); } } public IDbParameterValue P1149 { get { return TSql.Int(0); } } public IDbParameterValue P1150 { get { return TSql.Int(0); } } public IDbParameterValue P1151 { get { return TSql.Int(0); } } public IDbParameterValue P1152 { get { return TSql.Int(0); } } public IDbParameterValue P1153 { get { return TSql.Int(0); } } public IDbParameterValue P1154 { get { return TSql.Int(0); } } public IDbParameterValue P1155 { get { return TSql.Int(0); } } public IDbParameterValue P1156 { get { return TSql.Int(0); } } public IDbParameterValue P1157 { get { return TSql.Int(0); } } public IDbParameterValue P1158 { get { return TSql.Int(0); } } public IDbParameterValue P1159 { get { return TSql.Int(0); } } public IDbParameterValue P1160 { get { return TSql.Int(0); } } public IDbParameterValue P1161 { get { return TSql.Int(0); } } public IDbParameterValue P1162 { get { return TSql.Int(0); } } public IDbParameterValue P1163 { get { return TSql.Int(0); } } public IDbParameterValue P1164 { get { return TSql.Int(0); } } public IDbParameterValue P1165 { get { return TSql.Int(0); } } public IDbParameterValue P1166 { get { return TSql.Int(0); } } public IDbParameterValue P1167 { get { return TSql.Int(0); } } public IDbParameterValue P1168 { get { return TSql.Int(0); } } public IDbParameterValue P1169 { get { return TSql.Int(0); } } public IDbParameterValue P1170 { get { return TSql.Int(0); } } public IDbParameterValue P1171 { get { return TSql.Int(0); } } public IDbParameterValue P1172 { get { return TSql.Int(0); } } public IDbParameterValue P1173 { get { return TSql.Int(0); } } public IDbParameterValue P1174 { get { return TSql.Int(0); } } public IDbParameterValue P1175 { get { return TSql.Int(0); } } public IDbParameterValue P1176 { get { return TSql.Int(0); } } public IDbParameterValue P1177 { get { return TSql.Int(0); } } public IDbParameterValue P1178 { get { return TSql.Int(0); } } public IDbParameterValue P1179 { get { return TSql.Int(0); } } public IDbParameterValue P1180 { get { return TSql.Int(0); } } public IDbParameterValue P1181 { get { return TSql.Int(0); } } public IDbParameterValue P1182 { get { return TSql.Int(0); } } public IDbParameterValue P1183 { get { return TSql.Int(0); } } public IDbParameterValue P1184 { get { return TSql.Int(0); } } public IDbParameterValue P1185 { get { return TSql.Int(0); } } public IDbParameterValue P1186 { get { return TSql.Int(0); } } public IDbParameterValue P1187 { get { return TSql.Int(0); } } public IDbParameterValue P1188 { get { return TSql.Int(0); } } public IDbParameterValue P1189 { get { return TSql.Int(0); } } public IDbParameterValue P1190 { get { return TSql.Int(0); } } public IDbParameterValue P1191 { get { return TSql.Int(0); } } public IDbParameterValue P1192 { get { return TSql.Int(0); } } public IDbParameterValue P1193 { get { return TSql.Int(0); } } public IDbParameterValue P1194 { get { return TSql.Int(0); } } public IDbParameterValue P1195 { get { return TSql.Int(0); } } public IDbParameterValue P1196 { get { return TSql.Int(0); } } public IDbParameterValue P1197 { get { return TSql.Int(0); } } public IDbParameterValue P1198 { get { return TSql.Int(0); } } public IDbParameterValue P1199 { get { return TSql.Int(0); } } public IDbParameterValue P1200 { get { return TSql.Int(0); } } public IDbParameterValue P1201 { get { return TSql.Int(0); } } public IDbParameterValue P1202 { get { return TSql.Int(0); } } public IDbParameterValue P1203 { get { return TSql.Int(0); } } public IDbParameterValue P1204 { get { return TSql.Int(0); } } public IDbParameterValue P1205 { get { return TSql.Int(0); } } public IDbParameterValue P1206 { get { return TSql.Int(0); } } public IDbParameterValue P1207 { get { return TSql.Int(0); } } public IDbParameterValue P1208 { get { return TSql.Int(0); } } public IDbParameterValue P1209 { get { return TSql.Int(0); } } public IDbParameterValue P1210 { get { return TSql.Int(0); } } public IDbParameterValue P1211 { get { return TSql.Int(0); } } public IDbParameterValue P1212 { get { return TSql.Int(0); } } public IDbParameterValue P1213 { get { return TSql.Int(0); } } public IDbParameterValue P1214 { get { return TSql.Int(0); } } public IDbParameterValue P1215 { get { return TSql.Int(0); } } public IDbParameterValue P1216 { get { return TSql.Int(0); } } public IDbParameterValue P1217 { get { return TSql.Int(0); } } public IDbParameterValue P1218 { get { return TSql.Int(0); } } public IDbParameterValue P1219 { get { return TSql.Int(0); } } public IDbParameterValue P1220 { get { return TSql.Int(0); } } public IDbParameterValue P1221 { get { return TSql.Int(0); } } public IDbParameterValue P1222 { get { return TSql.Int(0); } } public IDbParameterValue P1223 { get { return TSql.Int(0); } } public IDbParameterValue P1224 { get { return TSql.Int(0); } } public IDbParameterValue P1225 { get { return TSql.Int(0); } } public IDbParameterValue P1226 { get { return TSql.Int(0); } } public IDbParameterValue P1227 { get { return TSql.Int(0); } } public IDbParameterValue P1228 { get { return TSql.Int(0); } } public IDbParameterValue P1229 { get { return TSql.Int(0); } } public IDbParameterValue P1230 { get { return TSql.Int(0); } } public IDbParameterValue P1231 { get { return TSql.Int(0); } } public IDbParameterValue P1232 { get { return TSql.Int(0); } } public IDbParameterValue P1233 { get { return TSql.Int(0); } } public IDbParameterValue P1234 { get { return TSql.Int(0); } } public IDbParameterValue P1235 { get { return TSql.Int(0); } } public IDbParameterValue P1236 { get { return TSql.Int(0); } } public IDbParameterValue P1237 { get { return TSql.Int(0); } } public IDbParameterValue P1238 { get { return TSql.Int(0); } } public IDbParameterValue P1239 { get { return TSql.Int(0); } } public IDbParameterValue P1240 { get { return TSql.Int(0); } } public IDbParameterValue P1241 { get { return TSql.Int(0); } } public IDbParameterValue P1242 { get { return TSql.Int(0); } } public IDbParameterValue P1243 { get { return TSql.Int(0); } } public IDbParameterValue P1244 { get { return TSql.Int(0); } } public IDbParameterValue P1245 { get { return TSql.Int(0); } } public IDbParameterValue P1246 { get { return TSql.Int(0); } } public IDbParameterValue P1247 { get { return TSql.Int(0); } } public IDbParameterValue P1248 { get { return TSql.Int(0); } } public IDbParameterValue P1249 { get { return TSql.Int(0); } } public IDbParameterValue P1250 { get { return TSql.Int(0); } } public IDbParameterValue P1251 { get { return TSql.Int(0); } } public IDbParameterValue P1252 { get { return TSql.Int(0); } } public IDbParameterValue P1253 { get { return TSql.Int(0); } } public IDbParameterValue P1254 { get { return TSql.Int(0); } } public IDbParameterValue P1255 { get { return TSql.Int(0); } } public IDbParameterValue P1256 { get { return TSql.Int(0); } } public IDbParameterValue P1257 { get { return TSql.Int(0); } } public IDbParameterValue P1258 { get { return TSql.Int(0); } } public IDbParameterValue P1259 { get { return TSql.Int(0); } } public IDbParameterValue P1260 { get { return TSql.Int(0); } } public IDbParameterValue P1261 { get { return TSql.Int(0); } } public IDbParameterValue P1262 { get { return TSql.Int(0); } } public IDbParameterValue P1263 { get { return TSql.Int(0); } } public IDbParameterValue P1264 { get { return TSql.Int(0); } } public IDbParameterValue P1265 { get { return TSql.Int(0); } } public IDbParameterValue P1266 { get { return TSql.Int(0); } } public IDbParameterValue P1267 { get { return TSql.Int(0); } } public IDbParameterValue P1268 { get { return TSql.Int(0); } } public IDbParameterValue P1269 { get { return TSql.Int(0); } } public IDbParameterValue P1270 { get { return TSql.Int(0); } } public IDbParameterValue P1271 { get { return TSql.Int(0); } } public IDbParameterValue P1272 { get { return TSql.Int(0); } } public IDbParameterValue P1273 { get { return TSql.Int(0); } } public IDbParameterValue P1274 { get { return TSql.Int(0); } } public IDbParameterValue P1275 { get { return TSql.Int(0); } } public IDbParameterValue P1276 { get { return TSql.Int(0); } } public IDbParameterValue P1277 { get { return TSql.Int(0); } } public IDbParameterValue P1278 { get { return TSql.Int(0); } } public IDbParameterValue P1279 { get { return TSql.Int(0); } } public IDbParameterValue P1280 { get { return TSql.Int(0); } } public IDbParameterValue P1281 { get { return TSql.Int(0); } } public IDbParameterValue P1282 { get { return TSql.Int(0); } } public IDbParameterValue P1283 { get { return TSql.Int(0); } } public IDbParameterValue P1284 { get { return TSql.Int(0); } } public IDbParameterValue P1285 { get { return TSql.Int(0); } } public IDbParameterValue P1286 { get { return TSql.Int(0); } } public IDbParameterValue P1287 { get { return TSql.Int(0); } } public IDbParameterValue P1288 { get { return TSql.Int(0); } } public IDbParameterValue P1289 { get { return TSql.Int(0); } } public IDbParameterValue P1290 { get { return TSql.Int(0); } } public IDbParameterValue P1291 { get { return TSql.Int(0); } } public IDbParameterValue P1292 { get { return TSql.Int(0); } } public IDbParameterValue P1293 { get { return TSql.Int(0); } } public IDbParameterValue P1294 { get { return TSql.Int(0); } } public IDbParameterValue P1295 { get { return TSql.Int(0); } } public IDbParameterValue P1296 { get { return TSql.Int(0); } } public IDbParameterValue P1297 { get { return TSql.Int(0); } } public IDbParameterValue P1298 { get { return TSql.Int(0); } } public IDbParameterValue P1299 { get { return TSql.Int(0); } } public IDbParameterValue P1300 { get { return TSql.Int(0); } } public IDbParameterValue P1301 { get { return TSql.Int(0); } } public IDbParameterValue P1302 { get { return TSql.Int(0); } } public IDbParameterValue P1303 { get { return TSql.Int(0); } } public IDbParameterValue P1304 { get { return TSql.Int(0); } } public IDbParameterValue P1305 { get { return TSql.Int(0); } } public IDbParameterValue P1306 { get { return TSql.Int(0); } } public IDbParameterValue P1307 { get { return TSql.Int(0); } } public IDbParameterValue P1308 { get { return TSql.Int(0); } } public IDbParameterValue P1309 { get { return TSql.Int(0); } } public IDbParameterValue P1310 { get { return TSql.Int(0); } } public IDbParameterValue P1311 { get { return TSql.Int(0); } } public IDbParameterValue P1312 { get { return TSql.Int(0); } } public IDbParameterValue P1313 { get { return TSql.Int(0); } } public IDbParameterValue P1314 { get { return TSql.Int(0); } } public IDbParameterValue P1315 { get { return TSql.Int(0); } } public IDbParameterValue P1316 { get { return TSql.Int(0); } } public IDbParameterValue P1317 { get { return TSql.Int(0); } } public IDbParameterValue P1318 { get { return TSql.Int(0); } } public IDbParameterValue P1319 { get { return TSql.Int(0); } } public IDbParameterValue P1320 { get { return TSql.Int(0); } } public IDbParameterValue P1321 { get { return TSql.Int(0); } } public IDbParameterValue P1322 { get { return TSql.Int(0); } } public IDbParameterValue P1323 { get { return TSql.Int(0); } } public IDbParameterValue P1324 { get { return TSql.Int(0); } } public IDbParameterValue P1325 { get { return TSql.Int(0); } } public IDbParameterValue P1326 { get { return TSql.Int(0); } } public IDbParameterValue P1327 { get { return TSql.Int(0); } } public IDbParameterValue P1328 { get { return TSql.Int(0); } } public IDbParameterValue P1329 { get { return TSql.Int(0); } } public IDbParameterValue P1330 { get { return TSql.Int(0); } } public IDbParameterValue P1331 { get { return TSql.Int(0); } } public IDbParameterValue P1332 { get { return TSql.Int(0); } } public IDbParameterValue P1333 { get { return TSql.Int(0); } } public IDbParameterValue P1334 { get { return TSql.Int(0); } } public IDbParameterValue P1335 { get { return TSql.Int(0); } } public IDbParameterValue P1336 { get { return TSql.Int(0); } } public IDbParameterValue P1337 { get { return TSql.Int(0); } } public IDbParameterValue P1338 { get { return TSql.Int(0); } } public IDbParameterValue P1339 { get { return TSql.Int(0); } } public IDbParameterValue P1340 { get { return TSql.Int(0); } } public IDbParameterValue P1341 { get { return TSql.Int(0); } } public IDbParameterValue P1342 { get { return TSql.Int(0); } } public IDbParameterValue P1343 { get { return TSql.Int(0); } } public IDbParameterValue P1344 { get { return TSql.Int(0); } } public IDbParameterValue P1345 { get { return TSql.Int(0); } } public IDbParameterValue P1346 { get { return TSql.Int(0); } } public IDbParameterValue P1347 { get { return TSql.Int(0); } } public IDbParameterValue P1348 { get { return TSql.Int(0); } } public IDbParameterValue P1349 { get { return TSql.Int(0); } } public IDbParameterValue P1350 { get { return TSql.Int(0); } } public IDbParameterValue P1351 { get { return TSql.Int(0); } } public IDbParameterValue P1352 { get { return TSql.Int(0); } } public IDbParameterValue P1353 { get { return TSql.Int(0); } } public IDbParameterValue P1354 { get { return TSql.Int(0); } } public IDbParameterValue P1355 { get { return TSql.Int(0); } } public IDbParameterValue P1356 { get { return TSql.Int(0); } } public IDbParameterValue P1357 { get { return TSql.Int(0); } } public IDbParameterValue P1358 { get { return TSql.Int(0); } } public IDbParameterValue P1359 { get { return TSql.Int(0); } } public IDbParameterValue P1360 { get { return TSql.Int(0); } } public IDbParameterValue P1361 { get { return TSql.Int(0); } } public IDbParameterValue P1362 { get { return TSql.Int(0); } } public IDbParameterValue P1363 { get { return TSql.Int(0); } } public IDbParameterValue P1364 { get { return TSql.Int(0); } } public IDbParameterValue P1365 { get { return TSql.Int(0); } } public IDbParameterValue P1366 { get { return TSql.Int(0); } } public IDbParameterValue P1367 { get { return TSql.Int(0); } } public IDbParameterValue P1368 { get { return TSql.Int(0); } } public IDbParameterValue P1369 { get { return TSql.Int(0); } } public IDbParameterValue P1370 { get { return TSql.Int(0); } } public IDbParameterValue P1371 { get { return TSql.Int(0); } } public IDbParameterValue P1372 { get { return TSql.Int(0); } } public IDbParameterValue P1373 { get { return TSql.Int(0); } } public IDbParameterValue P1374 { get { return TSql.Int(0); } } public IDbParameterValue P1375 { get { return TSql.Int(0); } } public IDbParameterValue P1376 { get { return TSql.Int(0); } } public IDbParameterValue P1377 { get { return TSql.Int(0); } } public IDbParameterValue P1378 { get { return TSql.Int(0); } } public IDbParameterValue P1379 { get { return TSql.Int(0); } } public IDbParameterValue P1380 { get { return TSql.Int(0); } } public IDbParameterValue P1381 { get { return TSql.Int(0); } } public IDbParameterValue P1382 { get { return TSql.Int(0); } } public IDbParameterValue P1383 { get { return TSql.Int(0); } } public IDbParameterValue P1384 { get { return TSql.Int(0); } } public IDbParameterValue P1385 { get { return TSql.Int(0); } } public IDbParameterValue P1386 { get { return TSql.Int(0); } } public IDbParameterValue P1387 { get { return TSql.Int(0); } } public IDbParameterValue P1388 { get { return TSql.Int(0); } } public IDbParameterValue P1389 { get { return TSql.Int(0); } } public IDbParameterValue P1390 { get { return TSql.Int(0); } } public IDbParameterValue P1391 { get { return TSql.Int(0); } } public IDbParameterValue P1392 { get { return TSql.Int(0); } } public IDbParameterValue P1393 { get { return TSql.Int(0); } } public IDbParameterValue P1394 { get { return TSql.Int(0); } } public IDbParameterValue P1395 { get { return TSql.Int(0); } } public IDbParameterValue P1396 { get { return TSql.Int(0); } } public IDbParameterValue P1397 { get { return TSql.Int(0); } } public IDbParameterValue P1398 { get { return TSql.Int(0); } } public IDbParameterValue P1399 { get { return TSql.Int(0); } } public IDbParameterValue P1400 { get { return TSql.Int(0); } } public IDbParameterValue P1401 { get { return TSql.Int(0); } } public IDbParameterValue P1402 { get { return TSql.Int(0); } } public IDbParameterValue P1403 { get { return TSql.Int(0); } } public IDbParameterValue P1404 { get { return TSql.Int(0); } } public IDbParameterValue P1405 { get { return TSql.Int(0); } } public IDbParameterValue P1406 { get { return TSql.Int(0); } } public IDbParameterValue P1407 { get { return TSql.Int(0); } } public IDbParameterValue P1408 { get { return TSql.Int(0); } } public IDbParameterValue P1409 { get { return TSql.Int(0); } } public IDbParameterValue P1410 { get { return TSql.Int(0); } } public IDbParameterValue P1411 { get { return TSql.Int(0); } } public IDbParameterValue P1412 { get { return TSql.Int(0); } } public IDbParameterValue P1413 { get { return TSql.Int(0); } } public IDbParameterValue P1414 { get { return TSql.Int(0); } } public IDbParameterValue P1415 { get { return TSql.Int(0); } } public IDbParameterValue P1416 { get { return TSql.Int(0); } } public IDbParameterValue P1417 { get { return TSql.Int(0); } } public IDbParameterValue P1418 { get { return TSql.Int(0); } } public IDbParameterValue P1419 { get { return TSql.Int(0); } } public IDbParameterValue P1420 { get { return TSql.Int(0); } } public IDbParameterValue P1421 { get { return TSql.Int(0); } } public IDbParameterValue P1422 { get { return TSql.Int(0); } } public IDbParameterValue P1423 { get { return TSql.Int(0); } } public IDbParameterValue P1424 { get { return TSql.Int(0); } } public IDbParameterValue P1425 { get { return TSql.Int(0); } } public IDbParameterValue P1426 { get { return TSql.Int(0); } } public IDbParameterValue P1427 { get { return TSql.Int(0); } } public IDbParameterValue P1428 { get { return TSql.Int(0); } } public IDbParameterValue P1429 { get { return TSql.Int(0); } } public IDbParameterValue P1430 { get { return TSql.Int(0); } } public IDbParameterValue P1431 { get { return TSql.Int(0); } } public IDbParameterValue P1432 { get { return TSql.Int(0); } } public IDbParameterValue P1433 { get { return TSql.Int(0); } } public IDbParameterValue P1434 { get { return TSql.Int(0); } } public IDbParameterValue P1435 { get { return TSql.Int(0); } } public IDbParameterValue P1436 { get { return TSql.Int(0); } } public IDbParameterValue P1437 { get { return TSql.Int(0); } } public IDbParameterValue P1438 { get { return TSql.Int(0); } } public IDbParameterValue P1439 { get { return TSql.Int(0); } } public IDbParameterValue P1440 { get { return TSql.Int(0); } } public IDbParameterValue P1441 { get { return TSql.Int(0); } } public IDbParameterValue P1442 { get { return TSql.Int(0); } } public IDbParameterValue P1443 { get { return TSql.Int(0); } } public IDbParameterValue P1444 { get { return TSql.Int(0); } } public IDbParameterValue P1445 { get { return TSql.Int(0); } } public IDbParameterValue P1446 { get { return TSql.Int(0); } } public IDbParameterValue P1447 { get { return TSql.Int(0); } } public IDbParameterValue P1448 { get { return TSql.Int(0); } } public IDbParameterValue P1449 { get { return TSql.Int(0); } } public IDbParameterValue P1450 { get { return TSql.Int(0); } } public IDbParameterValue P1451 { get { return TSql.Int(0); } } public IDbParameterValue P1452 { get { return TSql.Int(0); } } public IDbParameterValue P1453 { get { return TSql.Int(0); } } public IDbParameterValue P1454 { get { return TSql.Int(0); } } public IDbParameterValue P1455 { get { return TSql.Int(0); } } public IDbParameterValue P1456 { get { return TSql.Int(0); } } public IDbParameterValue P1457 { get { return TSql.Int(0); } } public IDbParameterValue P1458 { get { return TSql.Int(0); } } public IDbParameterValue P1459 { get { return TSql.Int(0); } } public IDbParameterValue P1460 { get { return TSql.Int(0); } } public IDbParameterValue P1461 { get { return TSql.Int(0); } } public IDbParameterValue P1462 { get { return TSql.Int(0); } } public IDbParameterValue P1463 { get { return TSql.Int(0); } } public IDbParameterValue P1464 { get { return TSql.Int(0); } } public IDbParameterValue P1465 { get { return TSql.Int(0); } } public IDbParameterValue P1466 { get { return TSql.Int(0); } } public IDbParameterValue P1467 { get { return TSql.Int(0); } } public IDbParameterValue P1468 { get { return TSql.Int(0); } } public IDbParameterValue P1469 { get { return TSql.Int(0); } } public IDbParameterValue P1470 { get { return TSql.Int(0); } } public IDbParameterValue P1471 { get { return TSql.Int(0); } } public IDbParameterValue P1472 { get { return TSql.Int(0); } } public IDbParameterValue P1473 { get { return TSql.Int(0); } } public IDbParameterValue P1474 { get { return TSql.Int(0); } } public IDbParameterValue P1475 { get { return TSql.Int(0); } } public IDbParameterValue P1476 { get { return TSql.Int(0); } } public IDbParameterValue P1477 { get { return TSql.Int(0); } } public IDbParameterValue P1478 { get { return TSql.Int(0); } } public IDbParameterValue P1479 { get { return TSql.Int(0); } } public IDbParameterValue P1480 { get { return TSql.Int(0); } } public IDbParameterValue P1481 { get { return TSql.Int(0); } } public IDbParameterValue P1482 { get { return TSql.Int(0); } } public IDbParameterValue P1483 { get { return TSql.Int(0); } } public IDbParameterValue P1484 { get { return TSql.Int(0); } } public IDbParameterValue P1485 { get { return TSql.Int(0); } } public IDbParameterValue P1486 { get { return TSql.Int(0); } } public IDbParameterValue P1487 { get { return TSql.Int(0); } } public IDbParameterValue P1488 { get { return TSql.Int(0); } } public IDbParameterValue P1489 { get { return TSql.Int(0); } } public IDbParameterValue P1490 { get { return TSql.Int(0); } } public IDbParameterValue P1491 { get { return TSql.Int(0); } } public IDbParameterValue P1492 { get { return TSql.Int(0); } } public IDbParameterValue P1493 { get { return TSql.Int(0); } } public IDbParameterValue P1494 { get { return TSql.Int(0); } } public IDbParameterValue P1495 { get { return TSql.Int(0); } } public IDbParameterValue P1496 { get { return TSql.Int(0); } } public IDbParameterValue P1497 { get { return TSql.Int(0); } } public IDbParameterValue P1498 { get { return TSql.Int(0); } } public IDbParameterValue P1499 { get { return TSql.Int(0); } } public IDbParameterValue P1500 { get { return TSql.Int(0); } } public IDbParameterValue P1501 { get { return TSql.Int(0); } } public IDbParameterValue P1502 { get { return TSql.Int(0); } } public IDbParameterValue P1503 { get { return TSql.Int(0); } } public IDbParameterValue P1504 { get { return TSql.Int(0); } } public IDbParameterValue P1505 { get { return TSql.Int(0); } } public IDbParameterValue P1506 { get { return TSql.Int(0); } } public IDbParameterValue P1507 { get { return TSql.Int(0); } } public IDbParameterValue P1508 { get { return TSql.Int(0); } } public IDbParameterValue P1509 { get { return TSql.Int(0); } } public IDbParameterValue P1510 { get { return TSql.Int(0); } } public IDbParameterValue P1511 { get { return TSql.Int(0); } } public IDbParameterValue P1512 { get { return TSql.Int(0); } } public IDbParameterValue P1513 { get { return TSql.Int(0); } } public IDbParameterValue P1514 { get { return TSql.Int(0); } } public IDbParameterValue P1515 { get { return TSql.Int(0); } } public IDbParameterValue P1516 { get { return TSql.Int(0); } } public IDbParameterValue P1517 { get { return TSql.Int(0); } } public IDbParameterValue P1518 { get { return TSql.Int(0); } } public IDbParameterValue P1519 { get { return TSql.Int(0); } } public IDbParameterValue P1520 { get { return TSql.Int(0); } } public IDbParameterValue P1521 { get { return TSql.Int(0); } } public IDbParameterValue P1522 { get { return TSql.Int(0); } } public IDbParameterValue P1523 { get { return TSql.Int(0); } } public IDbParameterValue P1524 { get { return TSql.Int(0); } } public IDbParameterValue P1525 { get { return TSql.Int(0); } } public IDbParameterValue P1526 { get { return TSql.Int(0); } } public IDbParameterValue P1527 { get { return TSql.Int(0); } } public IDbParameterValue P1528 { get { return TSql.Int(0); } } public IDbParameterValue P1529 { get { return TSql.Int(0); } } public IDbParameterValue P1530 { get { return TSql.Int(0); } } public IDbParameterValue P1531 { get { return TSql.Int(0); } } public IDbParameterValue P1532 { get { return TSql.Int(0); } } public IDbParameterValue P1533 { get { return TSql.Int(0); } } public IDbParameterValue P1534 { get { return TSql.Int(0); } } public IDbParameterValue P1535 { get { return TSql.Int(0); } } public IDbParameterValue P1536 { get { return TSql.Int(0); } } public IDbParameterValue P1537 { get { return TSql.Int(0); } } public IDbParameterValue P1538 { get { return TSql.Int(0); } } public IDbParameterValue P1539 { get { return TSql.Int(0); } } public IDbParameterValue P1540 { get { return TSql.Int(0); } } public IDbParameterValue P1541 { get { return TSql.Int(0); } } public IDbParameterValue P1542 { get { return TSql.Int(0); } } public IDbParameterValue P1543 { get { return TSql.Int(0); } } public IDbParameterValue P1544 { get { return TSql.Int(0); } } public IDbParameterValue P1545 { get { return TSql.Int(0); } } public IDbParameterValue P1546 { get { return TSql.Int(0); } } public IDbParameterValue P1547 { get { return TSql.Int(0); } } public IDbParameterValue P1548 { get { return TSql.Int(0); } } public IDbParameterValue P1549 { get { return TSql.Int(0); } } public IDbParameterValue P1550 { get { return TSql.Int(0); } } public IDbParameterValue P1551 { get { return TSql.Int(0); } } public IDbParameterValue P1552 { get { return TSql.Int(0); } } public IDbParameterValue P1553 { get { return TSql.Int(0); } } public IDbParameterValue P1554 { get { return TSql.Int(0); } } public IDbParameterValue P1555 { get { return TSql.Int(0); } } public IDbParameterValue P1556 { get { return TSql.Int(0); } } public IDbParameterValue P1557 { get { return TSql.Int(0); } } public IDbParameterValue P1558 { get { return TSql.Int(0); } } public IDbParameterValue P1559 { get { return TSql.Int(0); } } public IDbParameterValue P1560 { get { return TSql.Int(0); } } public IDbParameterValue P1561 { get { return TSql.Int(0); } } public IDbParameterValue P1562 { get { return TSql.Int(0); } } public IDbParameterValue P1563 { get { return TSql.Int(0); } } public IDbParameterValue P1564 { get { return TSql.Int(0); } } public IDbParameterValue P1565 { get { return TSql.Int(0); } } public IDbParameterValue P1566 { get { return TSql.Int(0); } } public IDbParameterValue P1567 { get { return TSql.Int(0); } } public IDbParameterValue P1568 { get { return TSql.Int(0); } } public IDbParameterValue P1569 { get { return TSql.Int(0); } } public IDbParameterValue P1570 { get { return TSql.Int(0); } } public IDbParameterValue P1571 { get { return TSql.Int(0); } } public IDbParameterValue P1572 { get { return TSql.Int(0); } } public IDbParameterValue P1573 { get { return TSql.Int(0); } } public IDbParameterValue P1574 { get { return TSql.Int(0); } } public IDbParameterValue P1575 { get { return TSql.Int(0); } } public IDbParameterValue P1576 { get { return TSql.Int(0); } } public IDbParameterValue P1577 { get { return TSql.Int(0); } } public IDbParameterValue P1578 { get { return TSql.Int(0); } } public IDbParameterValue P1579 { get { return TSql.Int(0); } } public IDbParameterValue P1580 { get { return TSql.Int(0); } } public IDbParameterValue P1581 { get { return TSql.Int(0); } } public IDbParameterValue P1582 { get { return TSql.Int(0); } } public IDbParameterValue P1583 { get { return TSql.Int(0); } } public IDbParameterValue P1584 { get { return TSql.Int(0); } } public IDbParameterValue P1585 { get { return TSql.Int(0); } } public IDbParameterValue P1586 { get { return TSql.Int(0); } } public IDbParameterValue P1587 { get { return TSql.Int(0); } } public IDbParameterValue P1588 { get { return TSql.Int(0); } } public IDbParameterValue P1589 { get { return TSql.Int(0); } } public IDbParameterValue P1590 { get { return TSql.Int(0); } } public IDbParameterValue P1591 { get { return TSql.Int(0); } } public IDbParameterValue P1592 { get { return TSql.Int(0); } } public IDbParameterValue P1593 { get { return TSql.Int(0); } } public IDbParameterValue P1594 { get { return TSql.Int(0); } } public IDbParameterValue P1595 { get { return TSql.Int(0); } } public IDbParameterValue P1596 { get { return TSql.Int(0); } } public IDbParameterValue P1597 { get { return TSql.Int(0); } } public IDbParameterValue P1598 { get { return TSql.Int(0); } } public IDbParameterValue P1599 { get { return TSql.Int(0); } } public IDbParameterValue P1600 { get { return TSql.Int(0); } } public IDbParameterValue P1601 { get { return TSql.Int(0); } } public IDbParameterValue P1602 { get { return TSql.Int(0); } } public IDbParameterValue P1603 { get { return TSql.Int(0); } } public IDbParameterValue P1604 { get { return TSql.Int(0); } } public IDbParameterValue P1605 { get { return TSql.Int(0); } } public IDbParameterValue P1606 { get { return TSql.Int(0); } } public IDbParameterValue P1607 { get { return TSql.Int(0); } } public IDbParameterValue P1608 { get { return TSql.Int(0); } } public IDbParameterValue P1609 { get { return TSql.Int(0); } } public IDbParameterValue P1610 { get { return TSql.Int(0); } } public IDbParameterValue P1611 { get { return TSql.Int(0); } } public IDbParameterValue P1612 { get { return TSql.Int(0); } } public IDbParameterValue P1613 { get { return TSql.Int(0); } } public IDbParameterValue P1614 { get { return TSql.Int(0); } } public IDbParameterValue P1615 { get { return TSql.Int(0); } } public IDbParameterValue P1616 { get { return TSql.Int(0); } } public IDbParameterValue P1617 { get { return TSql.Int(0); } } public IDbParameterValue P1618 { get { return TSql.Int(0); } } public IDbParameterValue P1619 { get { return TSql.Int(0); } } public IDbParameterValue P1620 { get { return TSql.Int(0); } } public IDbParameterValue P1621 { get { return TSql.Int(0); } } public IDbParameterValue P1622 { get { return TSql.Int(0); } } public IDbParameterValue P1623 { get { return TSql.Int(0); } } public IDbParameterValue P1624 { get { return TSql.Int(0); } } public IDbParameterValue P1625 { get { return TSql.Int(0); } } public IDbParameterValue P1626 { get { return TSql.Int(0); } } public IDbParameterValue P1627 { get { return TSql.Int(0); } } public IDbParameterValue P1628 { get { return TSql.Int(0); } } public IDbParameterValue P1629 { get { return TSql.Int(0); } } public IDbParameterValue P1630 { get { return TSql.Int(0); } } public IDbParameterValue P1631 { get { return TSql.Int(0); } } public IDbParameterValue P1632 { get { return TSql.Int(0); } } public IDbParameterValue P1633 { get { return TSql.Int(0); } } public IDbParameterValue P1634 { get { return TSql.Int(0); } } public IDbParameterValue P1635 { get { return TSql.Int(0); } } public IDbParameterValue P1636 { get { return TSql.Int(0); } } public IDbParameterValue P1637 { get { return TSql.Int(0); } } public IDbParameterValue P1638 { get { return TSql.Int(0); } } public IDbParameterValue P1639 { get { return TSql.Int(0); } } public IDbParameterValue P1640 { get { return TSql.Int(0); } } public IDbParameterValue P1641 { get { return TSql.Int(0); } } public IDbParameterValue P1642 { get { return TSql.Int(0); } } public IDbParameterValue P1643 { get { return TSql.Int(0); } } public IDbParameterValue P1644 { get { return TSql.Int(0); } } public IDbParameterValue P1645 { get { return TSql.Int(0); } } public IDbParameterValue P1646 { get { return TSql.Int(0); } } public IDbParameterValue P1647 { get { return TSql.Int(0); } } public IDbParameterValue P1648 { get { return TSql.Int(0); } } public IDbParameterValue P1649 { get { return TSql.Int(0); } } public IDbParameterValue P1650 { get { return TSql.Int(0); } } public IDbParameterValue P1651 { get { return TSql.Int(0); } } public IDbParameterValue P1652 { get { return TSql.Int(0); } } public IDbParameterValue P1653 { get { return TSql.Int(0); } } public IDbParameterValue P1654 { get { return TSql.Int(0); } } public IDbParameterValue P1655 { get { return TSql.Int(0); } } public IDbParameterValue P1656 { get { return TSql.Int(0); } } public IDbParameterValue P1657 { get { return TSql.Int(0); } } public IDbParameterValue P1658 { get { return TSql.Int(0); } } public IDbParameterValue P1659 { get { return TSql.Int(0); } } public IDbParameterValue P1660 { get { return TSql.Int(0); } } public IDbParameterValue P1661 { get { return TSql.Int(0); } } public IDbParameterValue P1662 { get { return TSql.Int(0); } } public IDbParameterValue P1663 { get { return TSql.Int(0); } } public IDbParameterValue P1664 { get { return TSql.Int(0); } } public IDbParameterValue P1665 { get { return TSql.Int(0); } } public IDbParameterValue P1666 { get { return TSql.Int(0); } } public IDbParameterValue P1667 { get { return TSql.Int(0); } } public IDbParameterValue P1668 { get { return TSql.Int(0); } } public IDbParameterValue P1669 { get { return TSql.Int(0); } } public IDbParameterValue P1670 { get { return TSql.Int(0); } } public IDbParameterValue P1671 { get { return TSql.Int(0); } } public IDbParameterValue P1672 { get { return TSql.Int(0); } } public IDbParameterValue P1673 { get { return TSql.Int(0); } } public IDbParameterValue P1674 { get { return TSql.Int(0); } } public IDbParameterValue P1675 { get { return TSql.Int(0); } } public IDbParameterValue P1676 { get { return TSql.Int(0); } } public IDbParameterValue P1677 { get { return TSql.Int(0); } } public IDbParameterValue P1678 { get { return TSql.Int(0); } } public IDbParameterValue P1679 { get { return TSql.Int(0); } } public IDbParameterValue P1680 { get { return TSql.Int(0); } } public IDbParameterValue P1681 { get { return TSql.Int(0); } } public IDbParameterValue P1682 { get { return TSql.Int(0); } } public IDbParameterValue P1683 { get { return TSql.Int(0); } } public IDbParameterValue P1684 { get { return TSql.Int(0); } } public IDbParameterValue P1685 { get { return TSql.Int(0); } } public IDbParameterValue P1686 { get { return TSql.Int(0); } } public IDbParameterValue P1687 { get { return TSql.Int(0); } } public IDbParameterValue P1688 { get { return TSql.Int(0); } } public IDbParameterValue P1689 { get { return TSql.Int(0); } } public IDbParameterValue P1690 { get { return TSql.Int(0); } } public IDbParameterValue P1691 { get { return TSql.Int(0); } } public IDbParameterValue P1692 { get { return TSql.Int(0); } } public IDbParameterValue P1693 { get { return TSql.Int(0); } } public IDbParameterValue P1694 { get { return TSql.Int(0); } } public IDbParameterValue P1695 { get { return TSql.Int(0); } } public IDbParameterValue P1696 { get { return TSql.Int(0); } } public IDbParameterValue P1697 { get { return TSql.Int(0); } } public IDbParameterValue P1698 { get { return TSql.Int(0); } } public IDbParameterValue P1699 { get { return TSql.Int(0); } } public IDbParameterValue P1700 { get { return TSql.Int(0); } } public IDbParameterValue P1701 { get { return TSql.Int(0); } } public IDbParameterValue P1702 { get { return TSql.Int(0); } } public IDbParameterValue P1703 { get { return TSql.Int(0); } } public IDbParameterValue P1704 { get { return TSql.Int(0); } } public IDbParameterValue P1705 { get { return TSql.Int(0); } } public IDbParameterValue P1706 { get { return TSql.Int(0); } } public IDbParameterValue P1707 { get { return TSql.Int(0); } } public IDbParameterValue P1708 { get { return TSql.Int(0); } } public IDbParameterValue P1709 { get { return TSql.Int(0); } } public IDbParameterValue P1710 { get { return TSql.Int(0); } } public IDbParameterValue P1711 { get { return TSql.Int(0); } } public IDbParameterValue P1712 { get { return TSql.Int(0); } } public IDbParameterValue P1713 { get { return TSql.Int(0); } } public IDbParameterValue P1714 { get { return TSql.Int(0); } } public IDbParameterValue P1715 { get { return TSql.Int(0); } } public IDbParameterValue P1716 { get { return TSql.Int(0); } } public IDbParameterValue P1717 { get { return TSql.Int(0); } } public IDbParameterValue P1718 { get { return TSql.Int(0); } } public IDbParameterValue P1719 { get { return TSql.Int(0); } } public IDbParameterValue P1720 { get { return TSql.Int(0); } } public IDbParameterValue P1721 { get { return TSql.Int(0); } } public IDbParameterValue P1722 { get { return TSql.Int(0); } } public IDbParameterValue P1723 { get { return TSql.Int(0); } } public IDbParameterValue P1724 { get { return TSql.Int(0); } } public IDbParameterValue P1725 { get { return TSql.Int(0); } } public IDbParameterValue P1726 { get { return TSql.Int(0); } } public IDbParameterValue P1727 { get { return TSql.Int(0); } } public IDbParameterValue P1728 { get { return TSql.Int(0); } } public IDbParameterValue P1729 { get { return TSql.Int(0); } } public IDbParameterValue P1730 { get { return TSql.Int(0); } } public IDbParameterValue P1731 { get { return TSql.Int(0); } } public IDbParameterValue P1732 { get { return TSql.Int(0); } } public IDbParameterValue P1733 { get { return TSql.Int(0); } } public IDbParameterValue P1734 { get { return TSql.Int(0); } } public IDbParameterValue P1735 { get { return TSql.Int(0); } } public IDbParameterValue P1736 { get { return TSql.Int(0); } } public IDbParameterValue P1737 { get { return TSql.Int(0); } } public IDbParameterValue P1738 { get { return TSql.Int(0); } } public IDbParameterValue P1739 { get { return TSql.Int(0); } } public IDbParameterValue P1740 { get { return TSql.Int(0); } } public IDbParameterValue P1741 { get { return TSql.Int(0); } } public IDbParameterValue P1742 { get { return TSql.Int(0); } } public IDbParameterValue P1743 { get { return TSql.Int(0); } } public IDbParameterValue P1744 { get { return TSql.Int(0); } } public IDbParameterValue P1745 { get { return TSql.Int(0); } } public IDbParameterValue P1746 { get { return TSql.Int(0); } } public IDbParameterValue P1747 { get { return TSql.Int(0); } } public IDbParameterValue P1748 { get { return TSql.Int(0); } } public IDbParameterValue P1749 { get { return TSql.Int(0); } } public IDbParameterValue P1750 { get { return TSql.Int(0); } } public IDbParameterValue P1751 { get { return TSql.Int(0); } } public IDbParameterValue P1752 { get { return TSql.Int(0); } } public IDbParameterValue P1753 { get { return TSql.Int(0); } } public IDbParameterValue P1754 { get { return TSql.Int(0); } } public IDbParameterValue P1755 { get { return TSql.Int(0); } } public IDbParameterValue P1756 { get { return TSql.Int(0); } } public IDbParameterValue P1757 { get { return TSql.Int(0); } } public IDbParameterValue P1758 { get { return TSql.Int(0); } } public IDbParameterValue P1759 { get { return TSql.Int(0); } } public IDbParameterValue P1760 { get { return TSql.Int(0); } } public IDbParameterValue P1761 { get { return TSql.Int(0); } } public IDbParameterValue P1762 { get { return TSql.Int(0); } } public IDbParameterValue P1763 { get { return TSql.Int(0); } } public IDbParameterValue P1764 { get { return TSql.Int(0); } } public IDbParameterValue P1765 { get { return TSql.Int(0); } } public IDbParameterValue P1766 { get { return TSql.Int(0); } } public IDbParameterValue P1767 { get { return TSql.Int(0); } } public IDbParameterValue P1768 { get { return TSql.Int(0); } } public IDbParameterValue P1769 { get { return TSql.Int(0); } } public IDbParameterValue P1770 { get { return TSql.Int(0); } } public IDbParameterValue P1771 { get { return TSql.Int(0); } } public IDbParameterValue P1772 { get { return TSql.Int(0); } } public IDbParameterValue P1773 { get { return TSql.Int(0); } } public IDbParameterValue P1774 { get { return TSql.Int(0); } } public IDbParameterValue P1775 { get { return TSql.Int(0); } } public IDbParameterValue P1776 { get { return TSql.Int(0); } } public IDbParameterValue P1777 { get { return TSql.Int(0); } } public IDbParameterValue P1778 { get { return TSql.Int(0); } } public IDbParameterValue P1779 { get { return TSql.Int(0); } } public IDbParameterValue P1780 { get { return TSql.Int(0); } } public IDbParameterValue P1781 { get { return TSql.Int(0); } } public IDbParameterValue P1782 { get { return TSql.Int(0); } } public IDbParameterValue P1783 { get { return TSql.Int(0); } } public IDbParameterValue P1784 { get { return TSql.Int(0); } } public IDbParameterValue P1785 { get { return TSql.Int(0); } } public IDbParameterValue P1786 { get { return TSql.Int(0); } } public IDbParameterValue P1787 { get { return TSql.Int(0); } } public IDbParameterValue P1788 { get { return TSql.Int(0); } } public IDbParameterValue P1789 { get { return TSql.Int(0); } } public IDbParameterValue P1790 { get { return TSql.Int(0); } } public IDbParameterValue P1791 { get { return TSql.Int(0); } } public IDbParameterValue P1792 { get { return TSql.Int(0); } } public IDbParameterValue P1793 { get { return TSql.Int(0); } } public IDbParameterValue P1794 { get { return TSql.Int(0); } } public IDbParameterValue P1795 { get { return TSql.Int(0); } } public IDbParameterValue P1796 { get { return TSql.Int(0); } } public IDbParameterValue P1797 { get { return TSql.Int(0); } } public IDbParameterValue P1798 { get { return TSql.Int(0); } } public IDbParameterValue P1799 { get { return TSql.Int(0); } } public IDbParameterValue P1800 { get { return TSql.Int(0); } } public IDbParameterValue P1801 { get { return TSql.Int(0); } } public IDbParameterValue P1802 { get { return TSql.Int(0); } } public IDbParameterValue P1803 { get { return TSql.Int(0); } } public IDbParameterValue P1804 { get { return TSql.Int(0); } } public IDbParameterValue P1805 { get { return TSql.Int(0); } } public IDbParameterValue P1806 { get { return TSql.Int(0); } } public IDbParameterValue P1807 { get { return TSql.Int(0); } } public IDbParameterValue P1808 { get { return TSql.Int(0); } } public IDbParameterValue P1809 { get { return TSql.Int(0); } } public IDbParameterValue P1810 { get { return TSql.Int(0); } } public IDbParameterValue P1811 { get { return TSql.Int(0); } } public IDbParameterValue P1812 { get { return TSql.Int(0); } } public IDbParameterValue P1813 { get { return TSql.Int(0); } } public IDbParameterValue P1814 { get { return TSql.Int(0); } } public IDbParameterValue P1815 { get { return TSql.Int(0); } } public IDbParameterValue P1816 { get { return TSql.Int(0); } } public IDbParameterValue P1817 { get { return TSql.Int(0); } } public IDbParameterValue P1818 { get { return TSql.Int(0); } } public IDbParameterValue P1819 { get { return TSql.Int(0); } } public IDbParameterValue P1820 { get { return TSql.Int(0); } } public IDbParameterValue P1821 { get { return TSql.Int(0); } } public IDbParameterValue P1822 { get { return TSql.Int(0); } } public IDbParameterValue P1823 { get { return TSql.Int(0); } } public IDbParameterValue P1824 { get { return TSql.Int(0); } } public IDbParameterValue P1825 { get { return TSql.Int(0); } } public IDbParameterValue P1826 { get { return TSql.Int(0); } } public IDbParameterValue P1827 { get { return TSql.Int(0); } } public IDbParameterValue P1828 { get { return TSql.Int(0); } } public IDbParameterValue P1829 { get { return TSql.Int(0); } } public IDbParameterValue P1830 { get { return TSql.Int(0); } } public IDbParameterValue P1831 { get { return TSql.Int(0); } } public IDbParameterValue P1832 { get { return TSql.Int(0); } } public IDbParameterValue P1833 { get { return TSql.Int(0); } } public IDbParameterValue P1834 { get { return TSql.Int(0); } } public IDbParameterValue P1835 { get { return TSql.Int(0); } } public IDbParameterValue P1836 { get { return TSql.Int(0); } } public IDbParameterValue P1837 { get { return TSql.Int(0); } } public IDbParameterValue P1838 { get { return TSql.Int(0); } } public IDbParameterValue P1839 { get { return TSql.Int(0); } } public IDbParameterValue P1840 { get { return TSql.Int(0); } } public IDbParameterValue P1841 { get { return TSql.Int(0); } } public IDbParameterValue P1842 { get { return TSql.Int(0); } } public IDbParameterValue P1843 { get { return TSql.Int(0); } } public IDbParameterValue P1844 { get { return TSql.Int(0); } } public IDbParameterValue P1845 { get { return TSql.Int(0); } } public IDbParameterValue P1846 { get { return TSql.Int(0); } } public IDbParameterValue P1847 { get { return TSql.Int(0); } } public IDbParameterValue P1848 { get { return TSql.Int(0); } } public IDbParameterValue P1849 { get { return TSql.Int(0); } } public IDbParameterValue P1850 { get { return TSql.Int(0); } } public IDbParameterValue P1851 { get { return TSql.Int(0); } } public IDbParameterValue P1852 { get { return TSql.Int(0); } } public IDbParameterValue P1853 { get { return TSql.Int(0); } } public IDbParameterValue P1854 { get { return TSql.Int(0); } } public IDbParameterValue P1855 { get { return TSql.Int(0); } } public IDbParameterValue P1856 { get { return TSql.Int(0); } } public IDbParameterValue P1857 { get { return TSql.Int(0); } } public IDbParameterValue P1858 { get { return TSql.Int(0); } } public IDbParameterValue P1859 { get { return TSql.Int(0); } } public IDbParameterValue P1860 { get { return TSql.Int(0); } } public IDbParameterValue P1861 { get { return TSql.Int(0); } } public IDbParameterValue P1862 { get { return TSql.Int(0); } } public IDbParameterValue P1863 { get { return TSql.Int(0); } } public IDbParameterValue P1864 { get { return TSql.Int(0); } } public IDbParameterValue P1865 { get { return TSql.Int(0); } } public IDbParameterValue P1866 { get { return TSql.Int(0); } } public IDbParameterValue P1867 { get { return TSql.Int(0); } } public IDbParameterValue P1868 { get { return TSql.Int(0); } } public IDbParameterValue P1869 { get { return TSql.Int(0); } } public IDbParameterValue P1870 { get { return TSql.Int(0); } } public IDbParameterValue P1871 { get { return TSql.Int(0); } } public IDbParameterValue P1872 { get { return TSql.Int(0); } } public IDbParameterValue P1873 { get { return TSql.Int(0); } } public IDbParameterValue P1874 { get { return TSql.Int(0); } } public IDbParameterValue P1875 { get { return TSql.Int(0); } } public IDbParameterValue P1876 { get { return TSql.Int(0); } } public IDbParameterValue P1877 { get { return TSql.Int(0); } } public IDbParameterValue P1878 { get { return TSql.Int(0); } } public IDbParameterValue P1879 { get { return TSql.Int(0); } } public IDbParameterValue P1880 { get { return TSql.Int(0); } } public IDbParameterValue P1881 { get { return TSql.Int(0); } } public IDbParameterValue P1882 { get { return TSql.Int(0); } } public IDbParameterValue P1883 { get { return TSql.Int(0); } } public IDbParameterValue P1884 { get { return TSql.Int(0); } } public IDbParameterValue P1885 { get { return TSql.Int(0); } } public IDbParameterValue P1886 { get { return TSql.Int(0); } } public IDbParameterValue P1887 { get { return TSql.Int(0); } } public IDbParameterValue P1888 { get { return TSql.Int(0); } } public IDbParameterValue P1889 { get { return TSql.Int(0); } } public IDbParameterValue P1890 { get { return TSql.Int(0); } } public IDbParameterValue P1891 { get { return TSql.Int(0); } } public IDbParameterValue P1892 { get { return TSql.Int(0); } } public IDbParameterValue P1893 { get { return TSql.Int(0); } } public IDbParameterValue P1894 { get { return TSql.Int(0); } } public IDbParameterValue P1895 { get { return TSql.Int(0); } } public IDbParameterValue P1896 { get { return TSql.Int(0); } } public IDbParameterValue P1897 { get { return TSql.Int(0); } } public IDbParameterValue P1898 { get { return TSql.Int(0); } } public IDbParameterValue P1899 { get { return TSql.Int(0); } } public IDbParameterValue P1900 { get { return TSql.Int(0); } } public IDbParameterValue P1901 { get { return TSql.Int(0); } } public IDbParameterValue P1902 { get { return TSql.Int(0); } } public IDbParameterValue P1903 { get { return TSql.Int(0); } } public IDbParameterValue P1904 { get { return TSql.Int(0); } } public IDbParameterValue P1905 { get { return TSql.Int(0); } } public IDbParameterValue P1906 { get { return TSql.Int(0); } } public IDbParameterValue P1907 { get { return TSql.Int(0); } } public IDbParameterValue P1908 { get { return TSql.Int(0); } } public IDbParameterValue P1909 { get { return TSql.Int(0); } } public IDbParameterValue P1910 { get { return TSql.Int(0); } } public IDbParameterValue P1911 { get { return TSql.Int(0); } } public IDbParameterValue P1912 { get { return TSql.Int(0); } } public IDbParameterValue P1913 { get { return TSql.Int(0); } } public IDbParameterValue P1914 { get { return TSql.Int(0); } } public IDbParameterValue P1915 { get { return TSql.Int(0); } } public IDbParameterValue P1916 { get { return TSql.Int(0); } } public IDbParameterValue P1917 { get { return TSql.Int(0); } } public IDbParameterValue P1918 { get { return TSql.Int(0); } } public IDbParameterValue P1919 { get { return TSql.Int(0); } } public IDbParameterValue P1920 { get { return TSql.Int(0); } } public IDbParameterValue P1921 { get { return TSql.Int(0); } } public IDbParameterValue P1922 { get { return TSql.Int(0); } } public IDbParameterValue P1923 { get { return TSql.Int(0); } } public IDbParameterValue P1924 { get { return TSql.Int(0); } } public IDbParameterValue P1925 { get { return TSql.Int(0); } } public IDbParameterValue P1926 { get { return TSql.Int(0); } } public IDbParameterValue P1927 { get { return TSql.Int(0); } } public IDbParameterValue P1928 { get { return TSql.Int(0); } } public IDbParameterValue P1929 { get { return TSql.Int(0); } } public IDbParameterValue P1930 { get { return TSql.Int(0); } } public IDbParameterValue P1931 { get { return TSql.Int(0); } } public IDbParameterValue P1932 { get { return TSql.Int(0); } } public IDbParameterValue P1933 { get { return TSql.Int(0); } } public IDbParameterValue P1934 { get { return TSql.Int(0); } } public IDbParameterValue P1935 { get { return TSql.Int(0); } } public IDbParameterValue P1936 { get { return TSql.Int(0); } } public IDbParameterValue P1937 { get { return TSql.Int(0); } } public IDbParameterValue P1938 { get { return TSql.Int(0); } } public IDbParameterValue P1939 { get { return TSql.Int(0); } } public IDbParameterValue P1940 { get { return TSql.Int(0); } } public IDbParameterValue P1941 { get { return TSql.Int(0); } } public IDbParameterValue P1942 { get { return TSql.Int(0); } } public IDbParameterValue P1943 { get { return TSql.Int(0); } } public IDbParameterValue P1944 { get { return TSql.Int(0); } } public IDbParameterValue P1945 { get { return TSql.Int(0); } } public IDbParameterValue P1946 { get { return TSql.Int(0); } } public IDbParameterValue P1947 { get { return TSql.Int(0); } } public IDbParameterValue P1948 { get { return TSql.Int(0); } } public IDbParameterValue P1949 { get { return TSql.Int(0); } } public IDbParameterValue P1950 { get { return TSql.Int(0); } } public IDbParameterValue P1951 { get { return TSql.Int(0); } } public IDbParameterValue P1952 { get { return TSql.Int(0); } } public IDbParameterValue P1953 { get { return TSql.Int(0); } } public IDbParameterValue P1954 { get { return TSql.Int(0); } } public IDbParameterValue P1955 { get { return TSql.Int(0); } } public IDbParameterValue P1956 { get { return TSql.Int(0); } } public IDbParameterValue P1957 { get { return TSql.Int(0); } } public IDbParameterValue P1958 { get { return TSql.Int(0); } } public IDbParameterValue P1959 { get { return TSql.Int(0); } } public IDbParameterValue P1960 { get { return TSql.Int(0); } } public IDbParameterValue P1961 { get { return TSql.Int(0); } } public IDbParameterValue P1962 { get { return TSql.Int(0); } } public IDbParameterValue P1963 { get { return TSql.Int(0); } } public IDbParameterValue P1964 { get { return TSql.Int(0); } } public IDbParameterValue P1965 { get { return TSql.Int(0); } } public IDbParameterValue P1966 { get { return TSql.Int(0); } } public IDbParameterValue P1967 { get { return TSql.Int(0); } } public IDbParameterValue P1968 { get { return TSql.Int(0); } } public IDbParameterValue P1969 { get { return TSql.Int(0); } } public IDbParameterValue P1970 { get { return TSql.Int(0); } } public IDbParameterValue P1971 { get { return TSql.Int(0); } } public IDbParameterValue P1972 { get { return TSql.Int(0); } } public IDbParameterValue P1973 { get { return TSql.Int(0); } } public IDbParameterValue P1974 { get { return TSql.Int(0); } } public IDbParameterValue P1975 { get { return TSql.Int(0); } } public IDbParameterValue P1976 { get { return TSql.Int(0); } } public IDbParameterValue P1977 { get { return TSql.Int(0); } } public IDbParameterValue P1978 { get { return TSql.Int(0); } } public IDbParameterValue P1979 { get { return TSql.Int(0); } } public IDbParameterValue P1980 { get { return TSql.Int(0); } } public IDbParameterValue P1981 { get { return TSql.Int(0); } } public IDbParameterValue P1982 { get { return TSql.Int(0); } } public IDbParameterValue P1983 { get { return TSql.Int(0); } } public IDbParameterValue P1984 { get { return TSql.Int(0); } } public IDbParameterValue P1985 { get { return TSql.Int(0); } } public IDbParameterValue P1986 { get { return TSql.Int(0); } } public IDbParameterValue P1987 { get { return TSql.Int(0); } } public IDbParameterValue P1988 { get { return TSql.Int(0); } } public IDbParameterValue P1989 { get { return TSql.Int(0); } } public IDbParameterValue P1990 { get { return TSql.Int(0); } } public IDbParameterValue P1991 { get { return TSql.Int(0); } } public IDbParameterValue P1992 { get { return TSql.Int(0); } } public IDbParameterValue P1993 { get { return TSql.Int(0); } } public IDbParameterValue P1994 { get { return TSql.Int(0); } } public IDbParameterValue P1995 { get { return TSql.Int(0); } } public IDbParameterValue P1996 { get { return TSql.Int(0); } } public IDbParameterValue P1997 { get { return TSql.Int(0); } } public IDbParameterValue P1998 { get { return TSql.Int(0); } } public IDbParameterValue P1999 { get { return TSql.Int(0); } } public IDbParameterValue P2000 { get { return TSql.Int(0); } } public IDbParameterValue P2001 { get { return TSql.Int(0); } } public IDbParameterValue P2002 { get { return TSql.Int(0); } } public IDbParameterValue P2003 { get { return TSql.Int(0); } } public IDbParameterValue P2004 { get { return TSql.Int(0); } } public IDbParameterValue P2005 { get { return TSql.Int(0); } } public IDbParameterValue P2006 { get { return TSql.Int(0); } } public IDbParameterValue P2007 { get { return TSql.Int(0); } } public IDbParameterValue P2008 { get { return TSql.Int(0); } } public IDbParameterValue P2009 { get { return TSql.Int(0); } } public IDbParameterValue P2010 { get { return TSql.Int(0); } } public IDbParameterValue P2011 { get { return TSql.Int(0); } } public IDbParameterValue P2012 { get { return TSql.Int(0); } } public IDbParameterValue P2013 { get { return TSql.Int(0); } } public IDbParameterValue P2014 { get { return TSql.Int(0); } } public IDbParameterValue P2015 { get { return TSql.Int(0); } } public IDbParameterValue P2016 { get { return TSql.Int(0); } } public IDbParameterValue P2017 { get { return TSql.Int(0); } } public IDbParameterValue P2018 { get { return TSql.Int(0); } } public IDbParameterValue P2019 { get { return TSql.Int(0); } } public IDbParameterValue P2020 { get { return TSql.Int(0); } } public IDbParameterValue P2021 { get { return TSql.Int(0); } } public IDbParameterValue P2022 { get { return TSql.Int(0); } } public IDbParameterValue P2023 { get { return TSql.Int(0); } } public IDbParameterValue P2024 { get { return TSql.Int(0); } } public IDbParameterValue P2025 { get { return TSql.Int(0); } } public IDbParameterValue P2026 { get { return TSql.Int(0); } } public IDbParameterValue P2027 { get { return TSql.Int(0); } } public IDbParameterValue P2028 { get { return TSql.Int(0); } } public IDbParameterValue P2029 { get { return TSql.Int(0); } } public IDbParameterValue P2030 { get { return TSql.Int(0); } } public IDbParameterValue P2031 { get { return TSql.Int(0); } } public IDbParameterValue P2032 { get { return TSql.Int(0); } } public IDbParameterValue P2033 { get { return TSql.Int(0); } } public IDbParameterValue P2034 { get { return TSql.Int(0); } } public IDbParameterValue P2035 { get { return TSql.Int(0); } } public IDbParameterValue P2036 { get { return TSql.Int(0); } } public IDbParameterValue P2037 { get { return TSql.Int(0); } } public IDbParameterValue P2038 { get { return TSql.Int(0); } } public IDbParameterValue P2039 { get { return TSql.Int(0); } } public IDbParameterValue P2040 { get { return TSql.Int(0); } } public IDbParameterValue P2041 { get { return TSql.Int(0); } } public IDbParameterValue P2042 { get { return TSql.Int(0); } } public IDbParameterValue P2043 { get { return TSql.Int(0); } } public IDbParameterValue P2044 { get { return TSql.Int(0); } } public IDbParameterValue P2045 { get { return TSql.Int(0); } } public IDbParameterValue P2046 { get { return TSql.Int(0); } } public IDbParameterValue P2047 { get { return TSql.Int(0); } } public IDbParameterValue P2048 { get { return TSql.Int(0); } } public IDbParameterValue P2049 { get { return TSql.Int(0); } } public IDbParameterValue P2050 { get { return TSql.Int(0); } } public IDbParameterValue P2051 { get { return TSql.Int(0); } } public IDbParameterValue P2052 { get { return TSql.Int(0); } } public IDbParameterValue P2053 { get { return TSql.Int(0); } } public IDbParameterValue P2054 { get { return TSql.Int(0); } } public IDbParameterValue P2055 { get { return TSql.Int(0); } } public IDbParameterValue P2056 { get { return TSql.Int(0); } } public IDbParameterValue P2057 { get { return TSql.Int(0); } } public IDbParameterValue P2058 { get { return TSql.Int(0); } } public IDbParameterValue P2059 { get { return TSql.Int(0); } } public IDbParameterValue P2060 { get { return TSql.Int(0); } } public IDbParameterValue P2061 { get { return TSql.Int(0); } } public IDbParameterValue P2062 { get { return TSql.Int(0); } } public IDbParameterValue P2063 { get { return TSql.Int(0); } } public IDbParameterValue P2064 { get { return TSql.Int(0); } } public IDbParameterValue P2065 { get { return TSql.Int(0); } } public IDbParameterValue P2066 { get { return TSql.Int(0); } } public IDbParameterValue P2067 { get { return TSql.Int(0); } } public IDbParameterValue P2068 { get { return TSql.Int(0); } } public IDbParameterValue P2069 { get { return TSql.Int(0); } } public IDbParameterValue P2070 { get { return TSql.Int(0); } } public IDbParameterValue P2071 { get { return TSql.Int(0); } } public IDbParameterValue P2072 { get { return TSql.Int(0); } } public IDbParameterValue P2073 { get { return TSql.Int(0); } } public IDbParameterValue P2074 { get { return TSql.Int(0); } } public IDbParameterValue P2075 { get { return TSql.Int(0); } } public IDbParameterValue P2076 { get { return TSql.Int(0); } } public IDbParameterValue P2077 { get { return TSql.Int(0); } } public IDbParameterValue P2078 { get { return TSql.Int(0); } } public IDbParameterValue P2079 { get { return TSql.Int(0); } } public IDbParameterValue P2080 { get { return TSql.Int(0); } } public IDbParameterValue P2081 { get { return TSql.Int(0); } } public IDbParameterValue P2082 { get { return TSql.Int(0); } } public IDbParameterValue P2083 { get { return TSql.Int(0); } } public IDbParameterValue P2084 { get { return TSql.Int(0); } } public IDbParameterValue P2085 { get { return TSql.Int(0); } } public IDbParameterValue P2086 { get { return TSql.Int(0); } } public IDbParameterValue P2087 { get { return TSql.Int(0); } } public IDbParameterValue P2088 { get { return TSql.Int(0); } } public IDbParameterValue P2089 { get { return TSql.Int(0); } } public IDbParameterValue P2090 { get { return TSql.Int(0); } } public IDbParameterValue P2091 { get { return TSql.Int(0); } } public IDbParameterValue P2092 { get { return TSql.Int(0); } } public IDbParameterValue P2093 { get { return TSql.Int(0); } } public IDbParameterValue P2094 { get { return TSql.Int(0); } } public IDbParameterValue P2095 { get { return TSql.Int(0); } } public IDbParameterValue P2096 { get { return TSql.Int(0); } } public IDbParameterValue P2097 { get { return TSql.Int(0); } } public IDbParameterValue P2098 { get { return TSql.Int(0); } } public IDbParameterValue P2099 { get { return TSql.Int(0); } } public IDbParameterValue[] All { get { return new[] { P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P30, P31, P32, P33, P34, P35, P36, P37, P38, P39, P40, P41, P42, P43, P44, P45, P46, P47, P48, P49, P50, P51, P52, P53, P54, P55, P56, P57, P58, P59, P60, P61, P62, P63, P64, P65, P66, P67, P68, P69, P70, P71, P72, P73, P74, P75, P76, P77, P78, P79, P80, P81, P82, P83, P84, P85, P86, P87, P88, P89, P90, P91, P92, P93, P94, P95, P96, P97, P98, P99, P100, P101, P102, P103, P104, P105, P106, P107, P108, P109, P110, P111, P112, P113, P114, P115, P116, P117, P118, P119, P120, P121, P122, P123, P124, P125, P126, P127, P128, P129, P130, P131, P132, P133, P134, P135, P136, P137, P138, P139, P140, P141, P142, P143, P144, P145, P146, P147, P148, P149, P150, P151, P152, P153, P154, P155, P156, P157, P158, P159, P160, P161, P162, P163, P164, P165, P166, P167, P168, P169, P170, P171, P172, P173, P174, P175, P176, P177, P178, P179, P180, P181, P182, P183, P184, P185, P186, P187, P188, P189, P190, P191, P192, P193, P194, P195, P196, P197, P198, P199, P200, P201, P202, P203, P204, P205, P206, P207, P208, P209, P210, P211, P212, P213, P214, P215, P216, P217, P218, P219, P220, P221, P222, P223, P224, P225, P226, P227, P228, P229, P230, P231, P232, P233, P234, P235, P236, P237, P238, P239, P240, P241, P242, P243, P244, P245, P246, P247, P248, P249, P250, P251, P252, P253, P254, P255, P256, P257, P258, P259, P260, P261, P262, P263, P264, P265, P266, P267, P268, P269, P270, P271, P272, P273, P274, P275, P276, P277, P278, P279, P280, P281, P282, P283, P284, P285, P286, P287, P288, P289, P290, P291, P292, P293, P294, P295, P296, P297, P298, P299, P300, P301, P302, P303, P304, P305, P306, P307, P308, P309, P310, P311, P312, P313, P314, P315, P316, P317, P318, P319, P320, P321, P322, P323, P324, P325, P326, P327, P328, P329, P330, P331, P332, P333, P334, P335, P336, P337, P338, P339, P340, P341, P342, P343, P344, P345, P346, P347, P348, P349, P350, P351, P352, P353, P354, P355, P356, P357, P358, P359, P360, P361, P362, P363, P364, P365, P366, P367, P368, P369, P370, P371, P372, P373, P374, P375, P376, P377, P378, P379, P380, P381, P382, P383, P384, P385, P386, P387, P388, P389, P390, P391, P392, P393, P394, P395, P396, P397, P398, P399, P400, P401, P402, P403, P404, P405, P406, P407, P408, P409, P410, P411, P412, P413, P414, P415, P416, P417, P418, P419, P420, P421, P422, P423, P424, P425, P426, P427, P428, P429, P430, P431, P432, P433, P434, P435, P436, P437, P438, P439, P440, P441, P442, P443, P444, P445, P446, P447, P448, P449, P450, P451, P452, P453, P454, P455, P456, P457, P458, P459, P460, P461, P462, P463, P464, P465, P466, P467, P468, P469, P470, P471, P472, P473, P474, P475, P476, P477, P478, P479, P480, P481, P482, P483, P484, P485, P486, P487, P488, P489, P490, P491, P492, P493, P494, P495, P496, P497, P498, P499, P500, P501, P502, P503, P504, P505, P506, P507, P508, P509, P510, P511, P512, P513, P514, P515, P516, P517, P518, P519, P520, P521, P522, P523, P524, P525, P526, P527, P528, P529, P530, P531, P532, P533, P534, P535, P536, P537, P538, P539, P540, P541, P542, P543, P544, P545, P546, P547, P548, P549, P550, P551, P552, P553, P554, P555, P556, P557, P558, P559, P560, P561, P562, P563, P564, P565, P566, P567, P568, P569, P570, P571, P572, P573, P574, P575, P576, P577, P578, P579, P580, P581, P582, P583, P584, P585, P586, P587, P588, P589, P590, P591, P592, P593, P594, P595, P596, P597, P598, P599, P600, P601, P602, P603, P604, P605, P606, P607, P608, P609, P610, P611, P612, P613, P614, P615, P616, P617, P618, P619, P620, P621, P622, P623, P624, P625, P626, P627, P628, P629, P630, P631, P632, P633, P634, P635, P636, P637, P638, P639, P640, P641, P642, P643, P644, P645, P646, P647, P648, P649, P650, P651, P652, P653, P654, P655, P656, P657, P658, P659, P660, P661, P662, P663, P664, P665, P666, P667, P668, P669, P670, P671, P672, P673, P674, P675, P676, P677, P678, P679, P680, P681, P682, P683, P684, P685, P686, P687, P688, P689, P690, P691, P692, P693, P694, P695, P696, P697, P698, P699, P700, P701, P702, P703, P704, P705, P706, P707, P708, P709, P710, P711, P712, P713, P714, P715, P716, P717, P718, P719, P720, P721, P722, P723, P724, P725, P726, P727, P728, P729, P730, P731, P732, P733, P734, P735, P736, P737, P738, P739, P740, P741, P742, P743, P744, P745, P746, P747, P748, P749, P750, P751, P752, P753, P754, P755, P756, P757, P758, P759, P760, P761, P762, P763, P764, P765, P766, P767, P768, P769, P770, P771, P772, P773, P774, P775, P776, P777, P778, P779, P780, P781, P782, P783, P784, P785, P786, P787, P788, P789, P790, P791, P792, P793, P794, P795, P796, P797, P798, P799, P800, P801, P802, P803, P804, P805, P806, P807, P808, P809, P810, P811, P812, P813, P814, P815, P816, P817, P818, P819, P820, P821, P822, P823, P824, P825, P826, P827, P828, P829, P830, P831, P832, P833, P834, P835, P836, P837, P838, P839, P840, P841, P842, P843, P844, P845, P846, P847, P848, P849, P850, P851, P852, P853, P854, P855, P856, P857, P858, P859, P860, P861, P862, P863, P864, P865, P866, P867, P868, P869, P870, P871, P872, P873, P874, P875, P876, P877, P878, P879, P880, P881, P882, P883, P884, P885, P886, P887, P888, P889, P890, P891, P892, P893, P894, P895, P896, P897, P898, P899, P900, P901, P902, P903, P904, P905, P906, P907, P908, P909, P910, P911, P912, P913, P914, P915, P916, P917, P918, P919, P920, P921, P922, P923, P924, P925, P926, P927, P928, P929, P930, P931, P932, P933, P934, P935, P936, P937, P938, P939, P940, P941, P942, P943, P944, P945, P946, P947, P948, P949, P950, P951, P952, P953, P954, P955, P956, P957, P958, P959, P960, P961, P962, P963, P964, P965, P966, P967, P968, P969, P970, P971, P972, P973, P974, P975, P976, P977, P978, P979, P980, P981, P982, P983, P984, P985, P986, P987, P988, P989, P990, P991, P992, P993, P994, P995, P996, P997, P998, P999, P1000, P1001, P1002, P1003, P1004, P1005, P1006, P1007, P1008, P1009, P1010, P1011, P1012, P1013, P1014, P1015, P1016, P1017, P1018, P1019, P1020, P1021, P1022, P1023, P1024, P1025, P1026, P1027, P1028, P1029, P1030, P1031, P1032, P1033, P1034, P1035, P1036, P1037, P1038, P1039, P1040, P1041, P1042, P1043, P1044, P1045, P1046, P1047, P1048, P1049, P1050, P1051, P1052, P1053, P1054, P1055, P1056, P1057, P1058, P1059, P1060, P1061, P1062, P1063, P1064, P1065, P1066, P1067, P1068, P1069, P1070, P1071, P1072, P1073, P1074, P1075, P1076, P1077, P1078, P1079, P1080, P1081, P1082, P1083, P1084, P1085, P1086, P1087, P1088, P1089, P1090, P1091, P1092, P1093, P1094, P1095, P1096, P1097, P1098, P1099, P1100, P1101, P1102, P1103, P1104, P1105, P1106, P1107, P1108, P1109, P1110, P1111, P1112, P1113, P1114, P1115, P1116, P1117, P1118, P1119, P1120, P1121, P1122, P1123, P1124, P1125, P1126, P1127, P1128, P1129, P1130, P1131, P1132, P1133, P1134, P1135, P1136, P1137, P1138, P1139, P1140, P1141, P1142, P1143, P1144, P1145, P1146, P1147, P1148, P1149, P1150, P1151, P1152, P1153, P1154, P1155, P1156, P1157, P1158, P1159, P1160, P1161, P1162, P1163, P1164, P1165, P1166, P1167, P1168, P1169, P1170, P1171, P1172, P1173, P1174, P1175, P1176, P1177, P1178, P1179, P1180, P1181, P1182, P1183, P1184, P1185, P1186, P1187, P1188, P1189, P1190, P1191, P1192, P1193, P1194, P1195, P1196, P1197, P1198, P1199, P1200, P1201, P1202, P1203, P1204, P1205, P1206, P1207, P1208, P1209, P1210, P1211, P1212, P1213, P1214, P1215, P1216, P1217, P1218, P1219, P1220, P1221, P1222, P1223, P1224, P1225, P1226, P1227, P1228, P1229, P1230, P1231, P1232, P1233, P1234, P1235, P1236, P1237, P1238, P1239, P1240, P1241, P1242, P1243, P1244, P1245, P1246, P1247, P1248, P1249, P1250, P1251, P1252, P1253, P1254, P1255, P1256, P1257, P1258, P1259, P1260, P1261, P1262, P1263, P1264, P1265, P1266, P1267, P1268, P1269, P1270, P1271, P1272, P1273, P1274, P1275, P1276, P1277, P1278, P1279, P1280, P1281, P1282, P1283, P1284, P1285, P1286, P1287, P1288, P1289, P1290, P1291, P1292, P1293, P1294, P1295, P1296, P1297, P1298, P1299, P1300, P1301, P1302, P1303, P1304, P1305, P1306, P1307, P1308, P1309, P1310, P1311, P1312, P1313, P1314, P1315, P1316, P1317, P1318, P1319, P1320, P1321, P1322, P1323, P1324, P1325, P1326, P1327, P1328, P1329, P1330, P1331, P1332, P1333, P1334, P1335, P1336, P1337, P1338, P1339, P1340, P1341, P1342, P1343, P1344, P1345, P1346, P1347, P1348, P1349, P1350, P1351, P1352, P1353, P1354, P1355, P1356, P1357, P1358, P1359, P1360, P1361, P1362, P1363, P1364, P1365, P1366, P1367, P1368, P1369, P1370, P1371, P1372, P1373, P1374, P1375, P1376, P1377, P1378, P1379, P1380, P1381, P1382, P1383, P1384, P1385, P1386, P1387, P1388, P1389, P1390, P1391, P1392, P1393, P1394, P1395, P1396, P1397, P1398, P1399, P1400, P1401, P1402, P1403, P1404, P1405, P1406, P1407, P1408, P1409, P1410, P1411, P1412, P1413, P1414, P1415, P1416, P1417, P1418, P1419, P1420, P1421, P1422, P1423, P1424, P1425, P1426, P1427, P1428, P1429, P1430, P1431, P1432, P1433, P1434, P1435, P1436, P1437, P1438, P1439, P1440, P1441, P1442, P1443, P1444, P1445, P1446, P1447, P1448, P1449, P1450, P1451, P1452, P1453, P1454, P1455, P1456, P1457, P1458, P1459, P1460, P1461, P1462, P1463, P1464, P1465, P1466, P1467, P1468, P1469, P1470, P1471, P1472, P1473, P1474, P1475, P1476, P1477, P1478, P1479, P1480, P1481, P1482, P1483, P1484, P1485, P1486, P1487, P1488, P1489, P1490, P1491, P1492, P1493, P1494, P1495, P1496, P1497, P1498, P1499, P1500, P1501, P1502, P1503, P1504, P1505, P1506, P1507, P1508, P1509, P1510, P1511, P1512, P1513, P1514, P1515, P1516, P1517, P1518, P1519, P1520, P1521, P1522, P1523, P1524, P1525, P1526, P1527, P1528, P1529, P1530, P1531, P1532, P1533, P1534, P1535, P1536, P1537, P1538, P1539, P1540, P1541, P1542, P1543, P1544, P1545, P1546, P1547, P1548, P1549, P1550, P1551, P1552, P1553, P1554, P1555, P1556, P1557, P1558, P1559, P1560, P1561, P1562, P1563, P1564, P1565, P1566, P1567, P1568, P1569, P1570, P1571, P1572, P1573, P1574, P1575, P1576, P1577, P1578, P1579, P1580, P1581, P1582, P1583, P1584, P1585, P1586, P1587, P1588, P1589, P1590, P1591, P1592, P1593, P1594, P1595, P1596, P1597, P1598, P1599, P1600, P1601, P1602, P1603, P1604, P1605, P1606, P1607, P1608, P1609, P1610, P1611, P1612, P1613, P1614, P1615, P1616, P1617, P1618, P1619, P1620, P1621, P1622, P1623, P1624, P1625, P1626, P1627, P1628, P1629, P1630, P1631, P1632, P1633, P1634, P1635, P1636, P1637, P1638, P1639, P1640, P1641, P1642, P1643, P1644, P1645, P1646, P1647, P1648, P1649, P1650, P1651, P1652, P1653, P1654, P1655, P1656, P1657, P1658, P1659, P1660, P1661, P1662, P1663, P1664, P1665, P1666, P1667, P1668, P1669, P1670, P1671, P1672, P1673, P1674, P1675, P1676, P1677, P1678, P1679, P1680, P1681, P1682, P1683, P1684, P1685, P1686, P1687, P1688, P1689, P1690, P1691, P1692, P1693, P1694, P1695, P1696, P1697, P1698, P1699, P1700, P1701, P1702, P1703, P1704, P1705, P1706, P1707, P1708, P1709, P1710, P1711, P1712, P1713, P1714, P1715, P1716, P1717, P1718, P1719, P1720, P1721, P1722, P1723, P1724, P1725, P1726, P1727, P1728, P1729, P1730, P1731, P1732, P1733, P1734, P1735, P1736, P1737, P1738, P1739, P1740, P1741, P1742, P1743, P1744, P1745, P1746, P1747, P1748, P1749, P1750, P1751, P1752, P1753, P1754, P1755, P1756, P1757, P1758, P1759, P1760, P1761, P1762, P1763, P1764, P1765, P1766, P1767, P1768, P1769, P1770, P1771, P1772, P1773, P1774, P1775, P1776, P1777, P1778, P1779, P1780, P1781, P1782, P1783, P1784, P1785, P1786, P1787, P1788, P1789, P1790, P1791, P1792, P1793, P1794, P1795, P1796, P1797, P1798, P1799, P1800, P1801, P1802, P1803, P1804, P1805, P1806, P1807, P1808, P1809, P1810, P1811, P1812, P1813, P1814, P1815, P1816, P1817, P1818, P1819, P1820, P1821, P1822, P1823, P1824, P1825, P1826, P1827, P1828, P1829, P1830, P1831, P1832, P1833, P1834, P1835, P1836, P1837, P1838, P1839, P1840, P1841, P1842, P1843, P1844, P1845, P1846, P1847, P1848, P1849, P1850, P1851, P1852, P1853, P1854, P1855, P1856, P1857, P1858, P1859, P1860, P1861, P1862, P1863, P1864, P1865, P1866, P1867, P1868, P1869, P1870, P1871, P1872, P1873, P1874, P1875, P1876, P1877, P1878, P1879, P1880, P1881, P1882, P1883, P1884, P1885, P1886, P1887, P1888, P1889, P1890, P1891, P1892, P1893, P1894, P1895, P1896, P1897, P1898, P1899, P1900, P1901, P1902, P1903, P1904, P1905, P1906, P1907, P1908, P1909, P1910, P1911, P1912, P1913, P1914, P1915, P1916, P1917, P1918, P1919, P1920, P1921, P1922, P1923, P1924, P1925, P1926, P1927, P1928, P1929, P1930, P1931, P1932, P1933, P1934, P1935, P1936, P1937, P1938, P1939, P1940, P1941, P1942, P1943, P1944, P1945, P1946, P1947, P1948, P1949, P1950, P1951, P1952, P1953, P1954, P1955, P1956, P1957, P1958, P1959, P1960, P1961, P1962, P1963, P1964, P1965, P1966, P1967, P1968, P1969, P1970, P1971, P1972, P1973, P1974, P1975, P1976, P1977, P1978, P1979, P1980, P1981, P1982, P1983, P1984, P1985, P1986, P1987, P1988, P1989, P1990, P1991, P1992, P1993, P1994, P1995, P1996, P1997, P1998, P1999, P2000, P2001, P2002, P2003, P2004, P2005, P2006, P2007, P2008, P2009, P2010, P2011, P2012, P2013, P2014, P2015, P2016, P2017, P2018, P2019, P2020, P2021, P2022, P2023, P2024, P2025, P2026, P2027, P2028, P2029, P2030, P2031, P2032, P2033, P2034, P2035, P2036, P2037, P2038, P2039, P2040, P2041, P2042, P2043, P2044, P2045, P2046, P2047, P2048, P2049, P2050, P2051, P2052, P2053, P2054, P2055, P2056, P2057, P2058, P2059, P2060, P2061, P2062, P2063, P2064, P2065, P2066, P2067, P2068, P2069, P2070, P2071, P2072, P2073, P2074, P2075, P2076, P2077, P2078, P2079, P2080, P2081, P2082, P2083, P2084, P2085, P2086, P2087, P2088, P2089, P2090, P2091, P2092, P2093, P2094, P2095, P2096, P2097, P2098, P2099 }; } } } }
bsd-3-clause
pbrunet/pythran
third_party/nt2/arithmetic/include/functions/scalar/adds.hpp
245
#ifndef NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SCALAR_ADDS_HPP_INCLUDED #define NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SCALAR_ADDS_HPP_INCLUDED #include <nt2/arithmetic/functions/adds.hpp> #include <boost/simd/arithmetic/functions/scalar/adds.hpp> #endif
bsd-3-clause
silverstripe/silverstripe-comments
src/Admin/CommentsGridFieldBulkAction/SpamHandler.php
544
<?php namespace SilverStripe\Comments\Admin\CommentsGridFieldBulkAction; use SilverStripe\Comments\Model\Comment; /** * A {@link Handler} for bulk marking comments as spam */ class SpamHandler extends CommentHandler { private static $url_segment = 'spam'; protected $buttonClasses = 'font-icon-cross-mark'; protected $label = 'Spam'; /** * @param Comment $comment * * @return Comment */ public function updateComment($comment) { $comment->markSpam(); return $comment; } }
bsd-3-clause
mylifeafterthat/sgf-project
frontend/views/shop/check-out.php
3800
<?php use yii\helpers\Html; use yii\web\View; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use frontend\assets\CheckoutAsset; use common\widgets\Alert; $this->title= 'Checkout'; CheckoutAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <title><?= Html::encode($this->title) ?></title> <meta charset="<?= Yii::$app->charset ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,900' rel='stylesheet' type='text/css'> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="SHORTCUT ICON" href="" /> <?php $this->head() ?> </head> <body class="checkout-page" data-current-user=""> <?php $this->beginBody() ?> <nav class="navbar navbar-default navbar-fixed-top checkout-page"> <div class="container"> <h2>Checkout Page</h2> </div> </nav> <section class="checkout-content"> <div class="row"> <div class="col-md-6"> <div class="form-checkout"> <?php if(Yii::$app->user->isGuest): ?> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist" > <li role="presentation" class="active"> <a href="#login" aria-controls="login" role="tab" data-toggle="tab"> Login </a> </li> <li role="presentation"> <a href="#register" aria-controls="register" role="tab" data-toggle="tab"> Register </a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="login"> <?=$this->render('_login',['model'=>$model2]);?> </div> <div role="tabpanel" class="tab-pane" id="register"> <?=$this->render('_registration',['model'=>$model]);?> </div> </div> <?php else: echo $this->render('_checkoutForm',['model'=>$model]); endif; ?> </div> </div> <div class="col-md-6"> <div class="form-checkout-right" style="position:fixed;height:100%;overflow:hidden;"> <div class="payment-method-header"> <h3>Your Shopping Cart</h3> </div> <div class="payment-method-header" style="max-height: 70%;overflow-y:scroll;"> <?php echo $this->render('_checkout_cart'); ?> </div> </div> </div> </div> </section> <?php $js = <<<JS $('.payment-method-radio').on('click',function(){ if($(this).attr('checked')){ $(this).attr('checked', false); $(this).data('collapse').collapse('show') }else{ console.log($(this).is(':checked')); $(this).attr('checked', true); } }); JS; $this->registerJS($js,View::POS_READY,'js-1'); ?> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?>
bsd-3-clause
koddsson/cf-ui
packages/cf-builder-pagination/src/PaginationBuilder.js
2839
import React from 'react'; import PropTypes from 'prop-types'; import { Pagination, PaginationItem } from 'cf-component-pagination'; import Icon from 'cf-component-icon'; class PaginationBuilder extends React.Component { render() { const { totalCount: totalItems, page, perPage, infoFormatter, loading, onPageChange } = this.props; const totalPages = Math.ceil(totalItems / perPage); const pageIndex = this.props.page - 1; const start = Math.max(pageIndex * perPage + 1, 1); const end = Math.min(start + perPage - 1, totalItems); const handleClickItem = page => { if (page >= 1 && page <= totalPages) { onPageChange(page); } }; const items = []; let prevWasEllipsis = false; for (let i = 1; i <= totalPages; i++) { if ( // First Page: i === 1 || // Last Page: i === totalPages || // Current Page: i === page || // Within 2 of page: Math.abs(page - i) <= 2 || // Within 3 of page and next to start or end: (Why? Because if we show an ellipsis instead of just a single number then wtf was the point) (Math.abs(page - i) <= 3 && (i === 2 || i === totalPages - 1)) ) { prevWasEllipsis = false; items.push( <PaginationItem key={i} type={loading && page === i ? 'loading' : 'number'} label={'Page ' + i} active={page === i} onClick={() => handleClickItem(i)} > {i} </PaginationItem> ); } else if (!prevWasEllipsis) { prevWasEllipsis = true; items.push( <PaginationItem key={i} type="ellipsis" label={'Page ' + i} onClick={() => null} /> ); } } const info = infoFormatter && infoFormatter(start, end, totalItems); return ( <Pagination info={info}> <PaginationItem type="prev" label="Previous Page" disabled={page === 1} onClick={() => handleClickItem(page - 1)} > <Icon type="caret-left" label={false} /> </PaginationItem> {items} <PaginationItem type="next" label="Next Page" disabled={page === totalPages} onClick={() => handleClickItem(page + 1)} > <Icon type="caret-right" label={false} /> </PaginationItem> </Pagination> ); } } PaginationBuilder.propTypes = { onPageChange: PropTypes.func.isRequired, loading: PropTypes.bool, totalCount: PropTypes.number.isRequired, page: PropTypes.number.isRequired, perPage: PropTypes.number.isRequired, infoFormatter: PropTypes.func }; export default PaginationBuilder;
bsd-3-clause
dneiter/exabgp
lib/exabgp/configuration/experimental/bgp/session.py
3848
# encoding: utf-8 """ session.py Created by Thomas Mangin on 2014-06-22. Copyright (c) 2014-2015 Exa Networks. All rights reserved. """ from exabgp.configuration.experimental.engine.raised import Raised from exabgp.configuration.experimental.engine.section import Section from exabgp.configuration.experimental.engine.parser import ip from exabgp.configuration.experimental.engine.parser import holdtime from exabgp.configuration.experimental.bgp.capability import syntax_capability from exabgp.configuration.experimental.bgp.capability import SectionCapability from exabgp.configuration.experimental.bgp.asn import SectionASN from exabgp.configuration.experimental.bgp.asn import syntax_asn # ============================================================== syntax_session syntax_session = """\ session <name> { %s %s } """ % ( '\n\t'.join((_.replace(' <name>','') for _ in syntax_asn.split('\n'))), '\n\t'.join((_.replace(' <name>','') for _ in syntax_capability.split('\n'))), ) # =============================================================== RaisedSession class RaisedSession (Raised): syntax = syntax_session # ============================================================== SectionSession # class SectionSession (Section): syntax = syntax_session name = 'session' def exit (self, tokeniser): asn = self.extract_anonymous('asn',tokeniser) if asn: if 'asn' in self.content: raise RaisedSession(tokeniser,"can not have amed and anonymous 'asn' in a session") self.content['asn'] = asn if 'asn' not in self.content: raise RaisedSession(tokeniser,"section is missing a 'asn' section") capability = self.extract_anonymous('capability',tokeniser) if capability: if 'capability' in self.content: raise RaisedSession(tokeniser,"can not have amed and anonymous 'capability' in a session") self.content['capability'] = capability if 'capability' not in self.content: raise RaisedSession(tokeniser,"section is missing a 'capability' section") if 'router-id' not in self.content: # 0.0.0.0 is now a invlid router-id so it will be replaced by the bind ip self.content['router-id'] = ip(lambda:'0.0.0.0') if 'hold-time' not in self.content: self.content['hold-time'] = holdtime(lambda:'180') def router_id (self, tokeniser): try: self.content['router-id'] = ip(tokeniser) except ValueError,exc: raise RaisedSession(tokeniser,'could not parse router-id, %s' % str(exc)) def hold_time (self, tokeniser): try: self.content['hold-time'] = holdtime(tokeniser) except ValueError,exc: raise RaisedSession(tokeniser,'could not parse hold-time, %s' % str(exc)) def asn (self, tokeniser): section = self.get_section(SectionASN.name,tokeniser) if section: self.content['asn'] = section else: return False def capability (self, tokeniser): section = self.get_section(SectionCapability.name,tokeniser) if section: self.content['capability'] = section else: return False @classmethod def register (cls, registry, location): registry.register_class(cls) registry.register(SectionASN,location+['asn']) registry.register_hook(cls,'action',location+['asn'],'asn') registry.register(SectionCapability,location+['capability']) registry.register_hook(cls,'action',location+['capability'],'capability') registry.register_hook(cls,'enter',location,'enter') registry.register_hook(cls,'exit',location,'exit') registry.register_hook(cls,'action',location+['router-id'],'router_id') registry.register_hook(cls,'action',location+['hold-time'],'hold_time') # registry.register_hook(cls,'enter',location,'enter_nameless') # registry.register_hook(cls,'action',location+['local'],'local_asn') # registry.register_hook(cls,'action',location+['peer'],'peer_asn') # registry.register_hook(cls,'exit', location,'exit_nameless')
bsd-3-clause
dpek/unity-raconteur
Twine/State/TwineExecutionState.cs
1399
using DPek.Raconteur.Twine.Parser; using DPek.Raconteur.Twine.Script; using System.Collections.Generic; namespace DPek.Raconteur.Twine.State { public class TwineExecutionState { /// <summary> /// The story that this execution state uses. /// </summary> private TwineState m_state; /// <summary> /// The passage that this execution state is currently pointing to. /// </summary> private List<TwineLine> m_currentPassage; public List<TwineLine> CurrentPassage { get { return m_currentPassage; } } /// <summary> /// Whether or not the state is currently running. /// </summary> public bool Running { get { return m_currentPassage != null; } } /// <summary> /// Creates a new execution state. /// </summary> /// <param name="state"> /// The TwineState this execution state belongs to. /// <param> public TwineExecutionState(TwineState state) { m_state = state; m_currentPassage = null; } public void GoToPassage(string name) { Static.Log("<b>Starting compilation of \"" + name + "\"...</b>\n"); TwinePassage passage = m_state.Script.GetPassage(name); m_currentPassage = passage.Compile(m_state); Static.Log("<b>Finished compilation of \"" + name + "\"</b>\n"); } /// <summary> /// Resets the state of the TwineExecutionState. /// </summary> public void Reset() { m_currentPassage = null; } } }
bsd-3-clause
Illescas28/hva_08_05_2016
module/Propel/build/classes/hva/AdmisionPeer.php
394
<?php /** * Skeleton subclass for performing query and update operations on the 'admision' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package propel.generator.hva */ class AdmisionPeer extends BaseAdmisionPeer { }
bsd-3-clause
jneslen/pixeltenchi
wp-includes/js/jquery/ui/effect-bounce.min.js
951
/*! * jQuery UI Effects Bounce 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ !function(e){"function"==typeof define&&define.amd?define(["jquery","./effect"],e):e(jQuery)}(function(w){return w.effects.define("bounce",function(e,t){var i,n,f,o=w(this),a=e.mode,c="hide"===a,u="show"===a,s=e.direction||"up",d=e.distance,r=e.times||5,p=2*r+(u||c?1:0),h=e.duration/p,m=e.easing,y="up"===s||"down"===s?"top":"left",l="up"===s||"left"===s,g=0,q=o.queue().length;for(w.effects.createPlaceholder(o),f=o.css(y),d=d||o["top"==y?"outerHeight":"outerWidth"]()/3,u&&((n={opacity:1})[y]=f,o.css("opacity",0).css(y,l?2*-d:2*d).animate(n,h,m)),c&&(d/=Math.pow(2,r-1)),(n={})[y]=f;g<r;g++)(i={})[y]=(l?"-=":"+=")+d,o.animate(i,h,m).animate(n,h,m),d=c?2*d:d/2;c&&((i={opacity:0})[y]=(l?"-=":"+=")+d,o.animate(i,h,m)),o.queue(t),w.effects.unshift(o,q,1+p)})});
bsd-3-clause
santisiri/popego
popego/jq/jq/consumer_startup.py
957
from twisted.application import internet, service from jq.consumer.server import JobConsumerFactory import os def attachConsumerService(processPath, port, app): service = internet.TCPServer(port, JobConsumerFactory(processPath)) service.setServiceParent(app) def createConsumerApplication(name='JobConsumer Application', ports=[9000]): # path del proceso consumer a ejecutar from jq import consumer consumerExecutable = os.path.join(os.path.dirname(consumer.__file__), 'agent_dispatcher.py') # conexion a la base de la aplicacion if 'POPEGO_CONF' not in os.environ: raise Exception("Falta la variable POPEGO_CONF") # Creacion del application application = service.Application(name) for port in ports: attachConsumerService(consumerExecutable, port, application) return application
bsd-3-clause
ppy/angle
src/libANGLE/renderer/gl/eagl/ContextEAGL.cpp
701
// // Copyright 2020 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ContextEAGL: // iOS-specific subclass of ContextGL. // #include "libANGLE/renderer/gl/eagl/ContextEAGL.h" #include "libANGLE/Context.h" #include "libANGLE/Display.h" #include "libANGLE/renderer/gl/eagl/DisplayEAGL.h" namespace rx { ContextEAGL::ContextEAGL(const gl::State &state, gl::ErrorSet *errorSet, const std::shared_ptr<RendererGL> &renderer) : ContextGL(state, errorSet, renderer, RobustnessVideoMemoryPurgeStatus::NOT_REQUESTED) {} } // namespace rx
bsd-3-clause
google/mozc
src/engine/minimal_engine.cc
8542
// Copyright 2010-2021, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "engine/minimal_engine.h" #include <cstdint> #include "composer/composer.h" #include "converter/converter_interface.h" #include "converter/segments.h" #include "data_manager/data_manager.h" #include "dictionary/suppression_dictionary.h" #include "engine/user_data_manager_interface.h" #include "prediction/predictor_interface.h" #include "request/conversion_request.h" namespace mozc { namespace { class UserDataManagerStub : public UserDataManagerInterface { public: UserDataManagerStub() = default; ~UserDataManagerStub() override = default; bool Sync() override { return true; } bool Reload() override { return true; } bool ClearUserHistory() override { return true; } bool ClearUserPrediction() override { return true; } bool ClearUnusedUserPrediction() override { return true; } bool ClearUserPredictionEntry(const std::string &key, const std::string &value) override { return true; } bool Wait() override { return true; } }; bool AddAsIsCandidate(const std::string &key, Segments *segments) { if (segments == nullptr) { return false; } segments->Clear(); Segment *segment = segments->add_segment(); DCHECK(segment); Segment::Candidate *candidate = segment->push_back_candidate(); DCHECK(candidate); candidate->Init(); candidate->content_key = key; candidate->content_value = key; candidate->key = key; candidate->value = key; candidate->lid = 0; candidate->rid = 0; candidate->wcost = 0; candidate->cost = 0; candidate->attributes = Segment::Candidate::DEFAULT_ATTRIBUTE; return true; } bool AddAsIsCandidate(const ConversionRequest &request, Segments *segments) { if (!request.has_composer()) { return false; } std::string key; request.composer().GetQueryForConversion(&key); return AddAsIsCandidate(key, segments); } class MinimalConverter : public ConverterInterface { public: MinimalConverter() = default; ~MinimalConverter() override = default; bool StartConversionForRequest(const ConversionRequest &request, Segments *segments) const override { return AddAsIsCandidate(request, segments); } bool StartConversion(Segments *segments, const std::string &key) const override { return AddAsIsCandidate(key, segments); } bool StartReverseConversion(Segments *segments, const std::string &key) const override { return false; } bool StartPredictionForRequest(const ConversionRequest &request, Segments *segments) const override { return AddAsIsCandidate(request, segments); } bool StartPrediction(Segments *segments, const std::string &key) const override { return AddAsIsCandidate(key, segments); } bool StartSuggestionForRequest(const ConversionRequest &request, Segments *segments) const override { return AddAsIsCandidate(request, segments); } bool StartSuggestion(Segments *segments, const std::string &key) const override { return AddAsIsCandidate(key, segments); } bool StartPartialPredictionForRequest(const ConversionRequest &request, Segments *segments) const override { return false; } bool StartPartialPrediction(Segments *segments, const std::string &key) const override { return false; } bool StartPartialSuggestionForRequest(const ConversionRequest &request, Segments *segments) const override { return false; } bool StartPartialSuggestion(Segments *segments, const std::string &key) const override { return false; } bool FinishConversion(const ConversionRequest &request, Segments *segments) const override { return true; } bool CancelConversion(Segments *segments) const override { return true; } bool ResetConversion(Segments *segments) const override { return true; } bool RevertConversion(Segments *segments) const override { return true; } bool ReconstructHistory(Segments *segments, const std::string &preceding_text) const override { return true; } bool CommitSegmentValue(Segments *segments, size_t segment_index, int candidate_index) const override { return true; } bool CommitPartialSuggestionSegmentValue( Segments *segments, size_t segment_index, int candidate_index, absl::string_view current_segment_key, absl::string_view new_segment_key) const override { return true; } bool FocusSegmentValue(Segments *segments, size_t segment_index, int candidate_index) const override { return true; } bool FreeSegmentValue(Segments *segments, size_t segment_index) const override { return true; } bool CommitSegments( Segments *segments, const std::vector<size_t> &candidate_index) const override { return true; } bool ResizeSegment(Segments *segments, const ConversionRequest &request, size_t segment_index, int offset_length) const override { return true; } bool ResizeSegment(Segments *segments, const ConversionRequest &request, size_t start_segment_index, size_t segments_size, const uint8_t *new_size_array, size_t array_size) const override { return true; } }; class MinimalPredictor : public PredictorInterface { public: MinimalPredictor() : name_("MinimalPredictor") {} ~MinimalPredictor() override = default; bool PredictForRequest(const ConversionRequest &request, Segments *segments) const override { return AddAsIsCandidate(request, segments); } const std::string &GetPredictorName() const override { return name_; } private: const std::string name_; }; } // namespace MinimalEngine::MinimalEngine() : converter_(new MinimalConverter()), predictor_(new MinimalPredictor()), suppression_dictionary_(new dictionary::SuppressionDictionary()), user_data_manager_(new UserDataManagerStub()), data_manager_(new DataManager()) {} MinimalEngine::~MinimalEngine() = default; ConverterInterface *MinimalEngine::GetConverter() const { return converter_.get(); } PredictorInterface *MinimalEngine::GetPredictor() const { return predictor_.get(); } dictionary::SuppressionDictionary *MinimalEngine::GetSuppressionDictionary() { return suppression_dictionary_.get(); } UserDataManagerInterface *MinimalEngine::GetUserDataManager() { return user_data_manager_.get(); } const DataManagerInterface *MinimalEngine::GetDataManager() const { return data_manager_.get(); } std::vector<std::string> MinimalEngine::GetPosList() const { return {}; } } // namespace mozc
bsd-3-clause
crosswalk-project/chromium-efl
impl/browser/renderer_host/web_cache_manager_efl.cc
10789
// Copyright 2014 Samsung Electronics. All rights reseoved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "browser/renderer_host/web_cache_manager_efl.h" #include "common/render_messages_efl.h" #include "cache_params_efl.h" #include "base/logging.h" #include "base/sys_info.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" using namespace tizen_webview; WebCacheManagerEfl::WebCacheManagerEfl(content::BrowserContext* browser_context) : browser_context_(browser_context), cache_model_(TW_CACHE_MODEL_DOCUMENT_VIEWER) { registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, content::NotificationService::AllBrowserContextsAndSources()); } WebCacheManagerEfl::~WebCacheManagerEfl() { } void WebCacheManagerEfl::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { content::RenderProcessHost* process = content::Source<content::RenderProcessHost>(source).ptr(); DCHECK(process); if (process->GetBrowserContext() != browser_context_) return; int renderer_id = process->GetID(); switch (type) { case content::NOTIFICATION_RENDERER_PROCESS_CREATED: { renderers_.insert(renderer_id); SetRenderProcessCacheModel(cache_model_, renderer_id); break; } case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: { renderers_.erase(renderer_id); break; } default: NOTREACHED(); break; } } void WebCacheManagerEfl::ClearCache() { for (std::set<int>::const_iterator iter = renderers_.begin(); iter != renderers_.end(); ++iter) { content::RenderProcessHost* host = content::RenderProcessHost::FromID(*iter); if (host) host->Send(new EflViewMsg_ClearCache()); } } void WebCacheManagerEfl::SetRenderProcessCacheModel(Cache_Model model, int render_process_id) { DCHECK(render_process_id); DCHECK(renderers_.find(render_process_id) != renderers_.end()); content::RenderProcessHost* host = content::RenderProcessHost::FromID(render_process_id); if (host) host->Send(new EflViewMsg_SetCache(GetCacheParamsFromModel(model))); } void WebCacheManagerEfl::SetCacheModel(Cache_Model model) { cache_model_ = model; CacheParamsEfl cache_params = GetCacheParamsFromModel(model); for (std::set<int>::const_iterator iter = renderers_.begin(); iter != renderers_.end(); ++iter) { content::RenderProcessHost* host = content::RenderProcessHost::FromID(*iter); if (host) host->Send(new EflViewMsg_SetCache(cache_params)); } } CacheParamsEfl WebCacheManagerEfl::GetCacheParamsFromModel(Cache_Model cache_model) { int64 mem_size = base::SysInfo::AmountOfPhysicalMemory(); // in chromium the limiting parameter is max file size of network cache // which is set at the time of creation of backend. // backend could be completely in-memory as well. // in WK2/Tizen, it is free space on disk // So, we are using free space available on browser_context path // we dont set it on renderer side anyway. int64 disk_free_size = base::SysInfo::AmountOfFreeDiskSpace(browser_context_->GetPath()); int64 cache_min_dead_capacity = 0; int64 cache_max_dead_capacity = 0; int64 cache_total_capacity = 0; double dead_decoded_data_deletion_interval = 0; int64 page_cache_capacity = 0; int64 url_cache_memory_capacity = 0; int64 url_cache_disk_capacity = 0; // We have taken this calculation from WK2. // Except that, we are using pointers instead of reference for output. // We don't use page_cache_capacity. NavigationControllerImpl has // kMaxSessionHistoryEntries = 50 for back/forward list. // url_cache_memory_capacity, url_cache_disk_capacity seem to be parts of // network layer. disk_cache::CreateCacheBackend gets size while creation. // Could not find anything to modify it on-the-fly. // m_deadDecodedDataDeletionInterval is unused variable in MemoryCache.cpp in // WK2 CachedResource uses this to start timer. // So, We are using only cache_total_capacity, cache_min_dead_capacity, and // cache_max_dead_capacity. This is same as Chromium cache manager implementation // But we are using following calculation instead of dynamic strategy used in Chromium. CalculateCacheSizes(cache_model, mem_size, disk_free_size, &cache_total_capacity, &cache_min_dead_capacity, &cache_max_dead_capacity, &dead_decoded_data_deletion_interval, &page_cache_capacity, &url_cache_memory_capacity, &url_cache_disk_capacity); CacheParamsEfl cache_params; cache_params.cache_max_dead_capacity = cache_max_dead_capacity; cache_params.cache_min_dead_capacity = cache_min_dead_capacity; cache_params.cache_total_capacity = cache_total_capacity; return cache_params; } // taken from WK2/Tizen // static void WebCacheManagerEfl::CalculateCacheSizes(Cache_Model cache_model, int64 memory_size, int64 disk_free_size, int64* cache_total_capacity, int64* cache_min_dead_capacity, int64* cache_max_dead_capacity, double* dead_decoded_data_deletion_interval, int64* page_cache_capacity, int64* url_cache_memory_capacity, int64* url_cache_disk_capacity) { switch (cache_model) { case TW_CACHE_MODEL_DOCUMENT_VIEWER: { // Object cache capacities (in bytes) if (memory_size >= 2048) *cache_total_capacity = 96 * 1024 * 1024; else if (memory_size >= 1536) *cache_total_capacity = 64 * 1024 * 1024; else if (memory_size >= 1024) *cache_total_capacity = 32 * 1024 * 1024; else if (memory_size >= 512) *cache_total_capacity = 16 * 1024 * 1024; *cache_min_dead_capacity = 0; *cache_max_dead_capacity = 0; // Foundation memory cache capacity (in bytes) *url_cache_memory_capacity = 0; // Foundation disk cache capacity (in bytes) *url_cache_disk_capacity = 0; break; } case TW_CACHE_MODEL_DOCUMENT_BROWSER: { // Page cache capacity (in pages) if (memory_size >= 1024) *page_cache_capacity = 3; else if (memory_size >= 512) *page_cache_capacity = 2; else if (memory_size >= 256) *page_cache_capacity = 1; else *page_cache_capacity = 0; // Object cache capacities (in bytes) if (memory_size >= 2048) *cache_total_capacity = 96 * 1024 * 1024; else if (memory_size >= 1536) *cache_total_capacity = 64 * 1024 * 1024; else if (memory_size >= 1024) *cache_total_capacity = 32 * 1024 * 1024; else if (memory_size >= 512) *cache_total_capacity = 16 * 1024 * 1024; *cache_min_dead_capacity = *cache_total_capacity / 8; *cache_max_dead_capacity = *cache_total_capacity / 4; // Foundation memory cache capacity (in bytes) if (memory_size >= 2048) *url_cache_memory_capacity = 4 * 1024 * 1024; else if (memory_size >= 1024) *url_cache_memory_capacity = 2 * 1024 * 1024; else if (memory_size >= 512) *url_cache_memory_capacity = 1 * 1024 * 1024; else *url_cache_memory_capacity = 512 * 1024; // Foundation disk cache capacity (in bytes) if (disk_free_size >= 16384) *url_cache_disk_capacity = 50 * 1024 * 1024; else if (disk_free_size >= 8192) *url_cache_disk_capacity = 40 * 1024 * 1024; else if (disk_free_size >= 4096) *url_cache_disk_capacity = 30 * 1024 * 1024; else *url_cache_disk_capacity = 20 * 1024 * 1024; break; }// CacheModelDocumentBrowser case TW_CACHE_MODEL_PRIMARY_WEBBROWSER: { // Page cache capacity (in pages) // (Research indicates that value / page drops substantially after 3 pages.) if (memory_size >= 2048) *page_cache_capacity = 5; else if (memory_size >= 1024) *page_cache_capacity = 4; else if (memory_size >= 512) *page_cache_capacity = 3; else if (memory_size >= 256) *page_cache_capacity = 2; else *page_cache_capacity = 1; // Object cache capacities (in bytes) // (Testing indicates that value / MB depends heavily on content and // browsing pattern. Even growth above 128MB can have substantial // value / MB for some content / browsing patterns.) if (memory_size >= 2048) *cache_total_capacity = 128 * 1024 * 1024; else if (memory_size >= 1536) *cache_total_capacity = 96 * 1024 * 1024; else if (memory_size >= 1024) *cache_total_capacity = 64 * 1024 * 1024; else if (memory_size >= 512) *cache_total_capacity = 32 * 1024 * 1024; *cache_min_dead_capacity = *cache_total_capacity / 4; *cache_max_dead_capacity = *cache_total_capacity / 2; // This code is here to avoid a PLT regression. We can remove it if we // can prove that the overall system gain would justify the regression. *cache_max_dead_capacity = std::max(static_cast<int64>(24), *cache_max_dead_capacity); *dead_decoded_data_deletion_interval = 60; // Foundation memory cache capacity (in bytes) // (These values are small because WebCore does most caching itself.) if (memory_size >= 1024) *url_cache_memory_capacity = 4 * 1024 * 1024; else if (memory_size >= 512) *url_cache_memory_capacity = 2 * 1024 * 1024; else if (memory_size >= 256) *url_cache_memory_capacity = 1 * 1024 * 1024; else *url_cache_memory_capacity = 512 * 1024; // Foundation disk cache capacity (in bytes) if (disk_free_size >= 16384) *url_cache_disk_capacity = 175 * 1024 * 1024; else if (disk_free_size >= 8192) *url_cache_disk_capacity = 150 * 1024 * 1024; else if (disk_free_size >= 4096) *url_cache_disk_capacity = 125 * 1024 * 1024; else if (disk_free_size >= 2048) *url_cache_disk_capacity = 100 * 1024 * 1024; else if (disk_free_size >= 1024) *url_cache_disk_capacity = 75 * 1024 * 1024; else *url_cache_disk_capacity = 50 * 1024 * 1024; break; } default: NOTREACHED(); break; }; } void WebCacheManagerEfl::SetBrowserContext(content::BrowserContext* browser_context) { DCHECK(!browser_context_); browser_context_ = browser_context; }
bsd-3-clause
microscopium/microscopium
microscopium/config.py
321
#!/usr/bin/env python import os import yaml def load_config(yaml_filename): with open(yaml_filename, "r") as f: settings = yaml.safe_load(f) return settings def get_tooltips(settings): tooltip_columns = settings['tooltip-columns'] return [(column, '@' + column) for column in tooltip_columns]
bsd-3-clause
alexfrolov/grappa
system/tasks/TaskingScheduler.hpp
21684
//////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2015, University of Washington and Battelle // Memorial Institute. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials // provided with the distribution. // * Neither the name of the University of Washington, Battelle // Memorial Institute, or the names of their contributors may be // used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // UNIVERSITY OF WASHINGTON OR BATTELLE MEMORIAL INSTITUTE BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. //////////////////////////////////////////////////////////////////////// #ifndef TASKING_SCHEDULER_HPP #define TASKING_SCHEDULER_HPP #include "Worker.hpp" #include "ThreadQueue.hpp" #include "Scheduler.hpp" #include "Communicator.hpp" #include <Timestamp.hpp> #include <glog/logging.h> #include <sstream> #include "Metrics.hpp" #include "HistogramMetric.hpp" #include "Timestamp.hpp" #include "PerformanceTools.hpp" #include "MetricsTools.hpp" #include "Metrics.hpp" #ifdef VTRACE #include <vt_user.h> #endif #include "StateTimer.hpp" GRAPPA_DECLARE_METRIC( SimpleMetric<uint64_t>, scheduler_context_switches ); GRAPPA_DECLARE_METRIC( SimpleMetric<uint64_t>, scheduler_count); // forward declarations namespace Grappa { namespace impl { void idle_flush_rdma_aggregator(); } namespace Metrics { void sample_all(); } } // forward-declare old aggregator flush bool idle_flush_aggregator(); DECLARE_int64( periodic_poll_ticks ); DECLARE_bool(poll_on_idle); DECLARE_bool(flush_on_idle); DECLARE_bool(rdma_flush_on_idle); DECLARE_bool( stats_blob_enable ); DECLARE_string(stats_blob_filename); DECLARE_int64( stats_blob_ticks ); namespace Grappa { namespace impl { class TaskManager; struct task_worker_args; /// Worker scheduler that knows about Tasks. /// Intended to schedule from a pool of worker threads that execute Tasks. class TaskingScheduler : public Scheduler { private: /// Queue for Threads that are ready to run PrefetchingThreadQueue readyQ; /// Queue for Threads that are to run periodically ThreadQueue periodicQ; /// Pool of idle workers that are not assigned to Tasks ThreadQueue unassignedQ; /// Master Worker that represents the main program thread Worker * master; /// Always points the the Worker that is currently running Worker * current_thread; threadid_t nextId; /// number of idle workers uint64_t num_idle; /// number of workers assigned to Tasks uint64_t num_active_tasks; /// Max allowed active workers uint64_t max_allowed_active_workers; /// Reference to Task manager that is used by the scheduler /// for finding Tasks to assign to workers TaskManager * task_manager; /// total number of worker Threads uint64_t num_workers; /// Return an idle worker Worker Worker * getWorker (); task_worker_args * work_args; // STUB: replace with real periodic threads Grappa::Timestamp previous_periodic_ts; Grappa::Timestamp periodic_poll_ticks; inline bool should_run_periodic( Grappa::Timestamp current_ts ) { return current_ts - previous_periodic_ts > periodic_poll_ticks; } Worker * periodicDequeue(Grappa::Timestamp current_ts) { // // tick the timestap counter // Grappa::tick(); // Grappa::Timestamp current_ts = Grappa::timestamp(); if( should_run_periodic( current_ts ) ) { return periodicQ.dequeue(); } else { return NULL; } } ////// bool queuesFinished(); /// make sure we don't context switch when we don't want to bool in_no_switch_region_; Grappa::Timestamp prev_ts; Grappa::Timestamp prev_stats_blob_ts; static const int64_t tick_scale = 1L; //(1L << 30); Worker * nextCoroutine ( bool isBlocking=true ) { scheduler_context_switches++; Grappa::Timestamp current_ts = 0; #ifdef VTRACE_FULL VT_TRACER("nextCoroutine"); #endif CHECK_EQ( in_no_switch_region_, false ) << "Trying to context switch in no-switch region"; do { Worker * result; scheduler_count++; // tick the timestap counter Grappa::tick(); current_ts = Grappa::timestamp(); // maybe sample if( Grappa::impl::take_tracing_sample ) { Grappa::impl::take_tracing_sample = false; #ifdef HISTOGRAM_SAMPLED DVLOG(3) << "sampling histogram"; Grappa::Metrics::histogram_sample(); #else Grappa::Metrics::sample(); #endif } // if( ( global_communicator.mycore == 0 ) && // ( current_ts - prev_stats_blob_ts > FLAGS_stats_blob_ticks ) && // FLAGS_stats_blob_enable && // current_thread != master ) { // prev_stats_blob_ts = current_ts; // Grappa::Metrics::dump_stats_blob(); // } // check for periodic tasks result = periodicDequeue(current_ts); if (result != NULL) { // DVLOG(5) << current_thread->id << " scheduler: pick periodic"; *(stats.state_timers[ stats.prev_state ]) += (current_ts - prev_ts) / tick_scale; stats.prev_state = TaskingSchedulerMetrics::StatePoll; prev_ts = current_ts; return result; } // check ready tasks result = readyQ.dequeue(); if (result != NULL) { // DVLOG(5) << current_thread->id << " scheduler: pick ready"; *(stats.state_timers[ stats.prev_state ]) += (current_ts - prev_ts) / tick_scale; stats.prev_state = TaskingSchedulerMetrics::StateReady; prev_ts = current_ts; return result; } // check if scheduler is allowed to have more active workers if (num_active_tasks < max_allowed_active_workers) { // check for new workers result = getWorker(); if (result != NULL) { // DVLOG(5) << current_thread->id << " scheduler: pick task worker"; *(stats.state_timers[ stats.prev_state ]) += (current_ts - prev_ts) / tick_scale; stats.prev_state = TaskingSchedulerMetrics::StateReady; prev_ts = current_ts; return result; } } if (FLAGS_poll_on_idle) { *(stats.state_timers[ stats.prev_state ]) += (current_ts - prev_ts) / tick_scale; if( FLAGS_rdma_flush_on_idle ) { Grappa::impl::idle_flush_rdma_aggregator(); } if ( idle_flush_aggregator() ) { stats.prev_state = TaskingSchedulerMetrics::StateIdleUseful; } else { stats.prev_state = TaskingSchedulerMetrics::StateIdle; } StateTimer::enterState_scheduler(); } else { *(stats.state_timers[ stats.prev_state ]) += (current_ts - prev_ts) / tick_scale; stats.prev_state = TaskingSchedulerMetrics::StateIdle; usleep(1); } prev_ts = current_ts; // no coroutines can run, so handle /*DVLOG(5) << current_thread->id << " scheduler: no coroutines can run" << "[isBlocking=" << isBlocking << " periodQ=" << (periodicQ.empty() ? "empty" : "full") << " unassignedQ=" << (unassignedQ.empty() ? "empty" : "full") << "]";*/ // usleep(1); } while ( isBlocking || !queuesFinished() ); // exit if all threads exited, including idle workers // TODO just as use mightBeWork as shortcut, also kill all idle unassigned workers on cbarrier_exit return NULL; } /// Append a representation of the state of the scheduler to an output stream std::ostream& dump( std::ostream& o = std::cout, const char * terminator = "" ) const { return o << "\"TaskingScheduler\": {" << std::endl //<< " \"hostname\": \"" << global_communicator.hostname() << "\"" << std::endl << " \"pid\": " << getpid() << std::endl << " \"readyQ\": " << readyQ << std::endl << " \"periodicQ\": " << periodicQ << std::endl << " \"num_workers\": " << num_workers << std::endl << " \"num_idle\": " << num_idle << std::endl << " \"unassignedQ\": " << unassignedQ << std::endl << "}"; } public: /// Stats for the scheduler class TaskingSchedulerMetrics { private: int64_t task_log_index; short * active_task_log; TaskingScheduler * sched; public: enum State { StatePoll=0, StateReady=1, StateIdle=2, StateIdleUseful=3, StateLast=4 }; SimpleMetric<uint64_t> * state_timers[ StateLast ]; State prev_state; TaskingSchedulerMetrics(); // only for declarations that will be copy-assigned to /// Create new statistics tracking for scheduler TaskingSchedulerMetrics( TaskingScheduler * scheduler ); ~TaskingSchedulerMetrics(); void reset(); void print_active_task_log(); /// Take a sample of the scheduler state void sample(); }; TaskingSchedulerMetrics stats; void assign_time_to_networking() { stats.prev_state = TaskingSchedulerMetrics::StatePoll; } TaskingScheduler ( ); void init ( Worker * master, TaskManager * taskman ); void set_no_switch_region( bool val ) { in_no_switch_region_ = val; } bool in_no_switch_region() { return in_no_switch_region_; } /// Get the currently running Worker. Worker * get_current_thread() { return current_thread; } int64_t active_worker_count() { return this->num_active_tasks; } void shutdown_readyQ() { uint64_t count = 0; while ( readyQ.length() > 0 ) { Worker * w = readyQ.dequeue(); //DVLOG(3) << "Worker found on readyQ at termination: " << *w; count++; } if ( count > 0 ) { DVLOG(2) << "Workers were found on readyQ at termination: " << count; } else { DVLOG(3) << "No Workers were found on readyQ at termination"; } } /// Set allowed active workers to allow `n` more workers than are active now, or if '-1' /// is specified, allow all workers to be active. /// (this is mostly to make Core 0 with user_main not get forced to have fewer active) void allow_active_workers(int64_t n) { if (n == -1) { max_allowed_active_workers = num_workers; } else { //VLOG(1) << "mynode = " << global_communicator.mycore; max_allowed_active_workers = n + ((global_communicator.mycore == 0) ? 1 : 0); } } int64_t max_allowed_active() { return max_allowed_active_workers; } /// Assign the Worker a unique id for this scheduler void assignTid( Worker * thr ) { thr->id = nextId++; } void createWorkers( uint64_t num ); Worker* maybeSpawnCoroutines( ); void onWorkerStart( ); uint64_t active_task_count() { return num_active_tasks; } /// Mark the Worker as an idle worker void unassigned( Worker * thr ) { unassignedQ.enqueue( thr ); } /// Mark the Worker as ready to run void ready( Worker * thr ) { readyQ.enqueue( thr ); } /// Put the Worker into the periodic queue void periodic( Worker * thr ) { periodicQ.enqueue( thr ); Grappa::tick(); Grappa::Timestamp current_ts = Grappa::force_tick(); previous_periodic_ts = current_ts; } /// Reset scheduler statistics void reset_stats() { stats.reset(); } /// run threads until all exit void run ( ); bool thread_maybe_yield( ); bool thread_yield( ); bool thread_yield_periodic( ); void thread_suspend( ); void thread_wake( Worker * next ); void thread_yield_wake( Worker * next ); void thread_suspend_wake( Worker * next ); bool thread_idle( uint64_t total_idle ); bool thread_idle( ); Worker * thread_wait( void **result ); void thread_on_exit( ); friend std::ostream& operator<<( std::ostream& o, const TaskingScheduler& ts ); friend void workerLoop ( Worker *, void * ); }; /// Arguments to workerLoop() worker Worker routine struct task_worker_args { TaskManager *const tasks; TaskingScheduler *const scheduler; task_worker_args( TaskManager * task_manager, TaskingScheduler * sched ) : tasks( task_manager ) , scheduler( sched ) { } }; /// Check the timestamp counter to see if it's time to run the periodic queue inline bool TaskingScheduler::thread_maybe_yield( ) { bool yielded = false; // tick the timestap counter Grappa::Timestamp current_ts = Grappa::force_tick(); if( should_run_periodic( current_ts ) ) { yielded = true; thread_yield(); } return yielded; } /// Yield the CPU to the next Worker on this scheduler. /// Cannot be called during the master Worker. inline bool TaskingScheduler::thread_yield( ) { CHECK( current_thread != master ) << "can't yield on a system Worker"; StateTimer::enterState_scheduler(); ready( current_thread ); Worker * yieldedThr = current_thread; Worker * next = nextCoroutine( ); bool gotRescheduled = (next == yieldedThr); current_thread = next; //DVLOG(5) << "Worker " << yieldedThr->id << " yielding to " << next->id << (gotRescheduled ? " (same thread)." : " (diff thread)."); thread_context_switch( yieldedThr, next, NULL); return gotRescheduled; // 0=another ran; 1=me got rescheduled immediately } /// For periodic threads: yield the CPU to the next Worker on this scheduler. /// Cannot be called during the master Worker. inline bool TaskingScheduler::thread_yield_periodic( ) { CHECK( current_thread != master ) << "can't yield on a system Worker"; StateTimer::enterState_scheduler(); periodic( current_thread ); Worker * yieldedThr = current_thread; Worker * next = nextCoroutine( ); bool gotRescheduled = (next == yieldedThr); current_thread = next; //DVLOG(5) << "Worker " << yieldedThr->id << " yielding to " << next->id << (gotRescheduled ? " (same thread)." : " (diff thread)."); thread_context_switch( yieldedThr, next, NULL); return gotRescheduled; // 0=another ran; 1=me got rescheduled immediately } /// Suspend the current Worker. Worker is not placed on any queue. /// Cannot be called during the master Worker. inline void TaskingScheduler::thread_suspend( ) { CHECK( current_thread != master ) << "can't yield on a system Worker"; CHECK( current_thread->running ) << "may only suspend a running coroutine"; StateTimer::enterState_scheduler(); Worker * yieldedThr = current_thread; yieldedThr->running = 0; // XXX: hack; really want to know at a user Worker level that it isn't running yieldedThr->suspended = 1; Worker * next = nextCoroutine( ); current_thread = next; thread_context_switch( yieldedThr, next, NULL); } /// Wake a suspended Worker by putting it on the run queue. /// For now, waking a running Worker is a fatal error. /// For now, waking a queued Worker is also a fatal error. /// For now, can only wake a Worker on your scheduler inline void TaskingScheduler::thread_wake( Worker * next ) { CHECK( next->sched == static_cast<Scheduler*>(this) ) << "can only wake a Worker on your scheduler (next="<<(void*) next << " next->sched="<<(void*)next->sched <<" this="<<(void*)this; CHECK( next->next == NULL ) << "woken Worker should not be on any queue"; CHECK( !next->running ) << "woken Worker should not be running"; next->suspended = 0; DVLOG(5) << "Worker " << current_thread->id << " wakes thread " << next->id; ready( next ); } /// Yield the current Worker and wake a suspended thread. /// For now, waking a running Worker is a fatal error. /// For now, waking a queued Worker is also a fatal error. inline void TaskingScheduler::thread_yield_wake( Worker * next ) { CHECK( current_thread != master ) << "can't yield on a system Worker"; CHECK( next->sched == static_cast<Scheduler*>(this) ) << "can only wake a Worker on your scheduler"; CHECK( next->next == NULL ) << "woken Worker should not be on any queue"; CHECK( !next->running ) << "woken Worker should not be running"; StateTimer::enterState_scheduler(); next->suspended = 0; Worker * yieldedThr = current_thread; ready( yieldedThr ); current_thread = next; thread_context_switch( yieldedThr, next, NULL); } /// Suspend current Worker and wake a suspended thread. /// For now, waking a running Worker is a fatal error. /// For now, waking a queued Worker is also a fatal error. inline void TaskingScheduler::thread_suspend_wake( Worker *next ) { CHECK( current_thread != master ) << "can't yield on a system Worker"; CHECK( next->next == NULL ) << "woken Worker should not be on any queue"; CHECK( !next->running ) << "woken Worker should not be running"; StateTimer::enterState_scheduler(); next->suspended = 0; Worker * yieldedThr = current_thread; yieldedThr->suspended = 1; current_thread = next; thread_context_switch( yieldedThr, next, NULL); } /// Make the current Worker idle. /// Like suspend except the Worker is not blocking on a /// particular resource, just waiting to be woken. /// @param total_idle the total number of possible idle threads inline bool TaskingScheduler::thread_idle( uint64_t total_idle ) { CHECK( num_idle+1 <= total_idle ) << "number of idle threads should not be more than total" << " (" << num_idle+1 << " / " << total_idle << ")"; if (num_idle+1 == total_idle) { DVLOG(5) << "going idle and is last"; } else { DVLOG(5) << "going idle and is " << num_idle+1 << " of " << total_idle; } num_idle++; current_thread->idle = 1; unassigned( current_thread ); thread_suspend( ); // woke so decrement idle counter num_idle--; current_thread->idle = 0; return true; } /// See bool TaskingScheduler::thread_idle(uint64_t), defaults /// to total being the number of scheduler workers. inline bool TaskingScheduler::thread_idle( ) { return thread_idle( num_workers ); } /// Callback for the end of a Worker inline void TaskingScheduler::thread_on_exit( ) { Worker * exitedThr = current_thread; current_thread = master; thread_context_switch( exitedThr, master, (void *)exitedThr); } /// instance extern TaskingScheduler global_scheduler; } // namespace impl /////////////////////////// /// Helpers /// /// @addtogroup Delegates /// @{ inline Worker* current_worker() { return impl::global_scheduler.get_current_thread(); } /// Yield to scheduler, placing current Worker on run queue. static inline void yield() { impl::global_scheduler.thread_yield(); } /// Yield to scheduler, placing current Worker on periodic queue. static inline void yield_periodic() { impl::global_scheduler.thread_yield_periodic( ); } /// Yield to scheduler, suspending current Worker. static inline void suspend() { DVLOG(5) << "suspending Worker " << impl::global_scheduler.get_current_thread() << "(# " << impl::global_scheduler.get_current_thread()->id << ")"; impl::global_scheduler.thread_suspend( ); //CHECK_EQ(retval, 0) << "Worker " << th1 << " suspension failed. Have the server threads exited?"; } /// Wake a Worker by putting it on the run queue, leaving the current thread running. static inline void wake( Worker * t ) { DVLOG(5) << impl::global_scheduler.get_current_thread()->id << " waking Worker " << t; impl::global_scheduler.thread_wake( t ); } /// Wake a Worker t by placing current thread on run queue and running t next. static inline void yield_wake( Worker * t ) { DVLOG(5) << "yielding Worker " << impl::global_scheduler.get_current_thread() << " and waking thread " << t; impl::global_scheduler.thread_yield_wake( t ); } /// Wake a Worker t by suspending current thread and running t next. static inline void suspend_wake( Worker * t ) { DVLOG(5) << "suspending Worker " << impl::global_scheduler.get_current_thread() << " and waking thread " << t; impl::global_scheduler.thread_suspend_wake( t ); } /// Place current thread on queue to be reused by tasking layer as a worker. /// @deprecated should not be in the public API because it is a Worker-level not Task-level routine static inline bool thread_idle() { DVLOG(5) << "Worker " << impl::global_scheduler.get_current_thread()->id << " going idle"; return impl::global_scheduler.thread_idle(); } /// @} } // namespace Grappa #endif // TASKING_SCHEDULER_HPP
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s03/CWE590_Free_Memory_Not_on_Heap__delete_long_declare_54b.cpp
1236
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_long_declare_54b.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.nonpointer.label.xml Template File: sources-sink-54b.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: declare Data buffer is declared on the stack * GoodSource: Allocate memory on the heap * Sink: * BadSink : Print then free data * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_long_declare_54 { /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void badSink_c(long * data); void badSink_b(long * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(long * data); void goodG2BSink_b(long * data) { goodG2BSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
bsd-3-clause
gartung/fnal-cetlib
cetlib/split_path.cc
659
// ====================================================================== // // split_path: Split the string 'path' into components delimited by a // single colon. Adjacent colons result in an empty string. // // ====================================================================== #include "cetlib/split_path.h" #include "boost/algorithm/string.hpp" void cet::split_path(std::string const& path, std::vector<std::string>& components) { if(path.empty()) components.clear(); else boost::algorithm::split(components, path, boost::algorithm::is_any_of(":")); }
bsd-3-clause
andrewseidl/chrono
src/chrono/assets/ChRoundedBoxShape.cpp
543
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2012 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #include "chrono/assets/ChRoundedBoxShape.h" namespace chrono { // Register into the object factory, to enable run-time // dynamic creation and persistence CH_FACTORY_REGISTER(ChRoundedBoxShape) } // end namespace chrono
bsd-3-clause
304NotModified/NLog
src/NLog/Targets/NetworkTargetQueueOverflowAction.cs
2160
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { /// <summary> /// The action to be taken when the queue overflows. /// </summary> public enum NetworkTargetQueueOverflowAction { /// <summary> /// Grow the queue. /// </summary> Grow, /// <summary> /// Discard the overflowing item. /// </summary> Discard, /// <summary> /// Block until there's more room in the queue. /// </summary> Block, } }
bsd-3-clause
oci-pronghorn/FogLight
foglight/src/main/java/com/ociweb/iot/grove/three_axis_accelerometer_16g/ThreeAxisAccelerometer_16g_Constants.java
2670
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ociweb.iot.grove.three_axis_accelerometer_16g; /** * * @author huydo */ public class ThreeAxisAccelerometer_16g_Constants { public static final int ADXL345_DEVICE = 0x53; public static final int ADXL345_POWER_CTL = 0x2D; public static final int ADXL345_DATA_FORMAT = 0x31; public static final int ADXL345_DATAX0 = 0x32; public static final int ADXL345_DATAX1 = 0x33; public static final int ADXL345_DATAY0 = 0x34; public static final int ADXL345_DATAY1 = 0x35; public static final int ADXL345_DATAZ0 = 0x36; public static final int ADXL345_DATAZ1 = 0x37; public static final int ADXL345_WINDOW = 0x23; public static final int ADXL345_LATENT = 0x22; public static final int ADXL345_DUR = 0x21; public static final int ADXL345_THRESH_TAP = 0x1d; public static final int ADXL345_ACT_TAP_STATUS = 0x2b; public static final int ADXL345_OFSX = 0x1e; public static final int ADXL345_OFSY = 0x1f; public static final int ADXL345_OFSZ = 0x20; public static final int ADXL345_DEVID = 0x00; public static final int ADXL345_RESERVED1 = 0x01; public static final int ADXL345_THRESH_ACT = 0x24; public static final int ADXL345_THRESH_INACT = 0x25; public static final int ADXL345_TIME_INACT = 0x26; public static final int ADXL345_ACT_INACT_CTL = 0x27; public static final int ADXL345_THRESH_FF = 0x28; public static final int ADXL345_TIME_FF = 0x29; public static final int ADXL345_TAP_AXES = 0x2a; public static final int ADXL345_BW_RATE = 0x2c; public static final int ADXL345_INT_ENABLE = 0x2e; public static final int ADXL345_INT_MAP = 0x2f; public static final int ADXL345_INT_SOURCE = 0x30; public static final int ADXL345_FIFO_CTL = 0x38; public static final int ADXL345_FIFO_STATUS = 0x39; public static final int ADXL345_RATE_3200 = 0x0F; // 1111 public static final int ADXL345_RATE_1600 = 0x0E; // 1110 public static final int ADXL345_RATE_800 = 0x0D ;// 1101 public static final int ADXL345_RATE_400 = 0x0C; // 1100 public static final int ADXL345_RATE_200 = 0x0B; // 1011 public static final int ADXL345_RATE_100 = 0x0A ;// 1010 public static final int ADXL345_RATE_50 = 0x09 ;// 1001 public static final int ADXL345_RATE_25 = 0x08 ;// 1000 public static final int ADXL345_RATE_12 = 0x07; // 0111 public static final int ADXL345_RATE_6 = 0x06; // 0110 }
bsd-3-clause
ruslankus/invoice-crm
modules/leap/classes/Base/DB/MsSQL/Insert/Builder.php
2004
<?php defined('SYSPATH') OR die('No direct script access.'); /** * Copyright © 2011–2013 Spadefoot Team. * * Unless otherwise noted, LEAP is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License * at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This class builds a MS SQL insert statement. * * @package Leap * @category MS SQL * @version 2012-12-05 * * @see http://msdn.microsoft.com/en-us/library/aa933206%28v=sql.80%29.aspx */ abstract class Base_DB_MsSQL_Insert_Builder extends DB_SQL_Insert_Builder { /** * This function returns the SQL statement. * * @access public * @override * @param boolean $terminated whether to add a semi-colon to the end * of the statement * @return string the SQL statement */ public function statement($terminated = TRUE) { $sql = "INSERT INTO {$this->data['into']}"; if ( ! empty($this->data['columns'])) { $rows = array_values($this->data['rows']); $rowCt = 1; $columns = array_keys($this->data['columns']); $columnCt = count($columns); $sql .= ' (' . implode(', ', $columns) . ') VALUES'; for ($r = 0; $r < $rowCt; $r++) { if ($r > 0) { $sql .= ','; } $sql .= ' ('; for ($c = 0; $c < $columnCt; $c++) { if ($c > 0) { $sql .= ', '; } $column = $columns[$c]; $sql .= (isset($rows[$r][$column])) ? $rows[$r][$column] : 'NULL'; } $sql .= ')'; } } if ($terminated) { $sql .= ';'; } return $sql; } }
bsd-3-clause
espadrine/opera
chromium/src/third_party/WebKit/Source/core/animation/PlayerTest.cpp
8047
/* * Copyright (c) 2013, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/animation/Player.h" #include "core/animation/DocumentTimeline.h" #include "core/dom/Document.h" #include "core/dom/QualifiedName.h" #include "weborigin/KURL.h" #include <gtest/gtest.h> using namespace WebCore; namespace { class PlayerTest : public ::testing::Test { protected: virtual void SetUp() { document = Document::create(0, KURL()); timeline = DocumentTimeline::create(document.get()); player = Player::create(timeline.get(), 0); } bool updateTimeline(double time) { timeline->serviceAnimations(time); // The timeline does not know about our player, so we have to explicitly call update(). return player->update(); } RefPtr<Document> document; RefPtr<DocumentTimeline> timeline; RefPtr<Player> player; }; TEST_F(PlayerTest, InitialState) { EXPECT_TRUE(isNull(timeline->currentTime())); EXPECT_EQ(0, player->currentTime()); EXPECT_FALSE(player->paused()); EXPECT_EQ(1, player->playbackRate()); EXPECT_EQ(0, player->startTime()); EXPECT_EQ(0, player->timeDrift()); } TEST_F(PlayerTest, CreatePlayerAfterTimelineStarted) { updateTimeline(1234); EXPECT_EQ(1234, timeline->currentTime()); RefPtr<Player> player = Player::create(timeline.get(), 0); EXPECT_EQ(1234, player->startTime()); EXPECT_EQ(0, player->currentTime()); } TEST_F(PlayerTest, PauseUnpause) { updateTimeline(200); player->setPaused(true); EXPECT_TRUE(player->paused()); EXPECT_EQ(200, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); updateTimeline(400); player->setPaused(false); EXPECT_FALSE(player->paused()); EXPECT_EQ(200, player->currentTime()); EXPECT_EQ(200, player->timeDrift()); updateTimeline(600); EXPECT_EQ(400, player->currentTime()); EXPECT_EQ(200, player->timeDrift()); } TEST_F(PlayerTest, PauseBeforeTimelineStarted) { player->setPaused(true); EXPECT_TRUE(player->paused()); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); player->setPaused(false); EXPECT_FALSE(player->paused()); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); player->setPaused(true); updateTimeline(100); EXPECT_TRUE(player->paused()); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(100, player->timeDrift()); player->setPaused(false); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(100, player->timeDrift()); } TEST_F(PlayerTest, SetCurrentTime) { updateTimeline(0); player->setCurrentTime(250); EXPECT_EQ(250, player->currentTime()); EXPECT_EQ(-250, player->timeDrift()); } TEST_F(PlayerTest, SetCurrentTimeBeforeTimelineStarted) { player->setCurrentTime(250); EXPECT_EQ(250, player->currentTime()); EXPECT_EQ(-250, player->timeDrift()); updateTimeline(0); EXPECT_EQ(250, player->currentTime()); } TEST_F(PlayerTest, SetPlaybackRate) { updateTimeline(0); player->setPlaybackRate(2); EXPECT_EQ(2, player->playbackRate()); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); updateTimeline(100); EXPECT_EQ(200, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); } TEST_F(PlayerTest, SetPlaybackRateBeforeTimelineStarted) { player->setPlaybackRate(2); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); updateTimeline(100); EXPECT_EQ(200, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); } TEST_F(PlayerTest, SetPlaybackRateWhilePaused) { updateTimeline(100); player->setPaused(true); player->setPlaybackRate(2); EXPECT_EQ(100, player->currentTime()); EXPECT_EQ(100, player->timeDrift()); updateTimeline(200); player->setPaused(false); EXPECT_EQ(100, player->currentTime()); EXPECT_EQ(300, player->timeDrift()); updateTimeline(250); EXPECT_EQ(200, player->currentTime()); EXPECT_EQ(300, player->timeDrift()); } TEST_F(PlayerTest, SetPlaybackRateNaN) { updateTimeline(0); player->setPlaybackRate(nullValue()); EXPECT_TRUE(isNull(player->playbackRate())); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); updateTimeline(100); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); } TEST_F(PlayerTest, SetPlaybackRateInfinity) { updateTimeline(0); player->setPlaybackRate(std::numeric_limits<double>::infinity()); EXPECT_EQ(std::numeric_limits<double>::infinity(), player->playbackRate()); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); updateTimeline(100); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); } TEST_F(PlayerTest, SetPlaybackRateMax) { updateTimeline(0); player->setPlaybackRate(std::numeric_limits<double>::max()); EXPECT_EQ(std::numeric_limits<double>::max(), player->playbackRate()); EXPECT_EQ(0, player->currentTime()); EXPECT_EQ(0, player->timeDrift()); updateTimeline(100); EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime()); } TEST_F(PlayerTest, SetCurrentTimeNan) { updateTimeline(0); player->setCurrentTime(nullValue()); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); updateTimeline(100); EXPECT_TRUE(isNull(player->currentTime())); EXPECT_TRUE(isNull(player->timeDrift())); } TEST_F(PlayerTest, SetCurrentTimeInfinity) { updateTimeline(0); player->setCurrentTime(std::numeric_limits<double>::infinity()); EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime()); EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift()); updateTimeline(100); EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime()); EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift()); } TEST_F(PlayerTest, SetCurrentTimeMax) { updateTimeline(0); player->setCurrentTime(std::numeric_limits<double>::max()); EXPECT_EQ(std::numeric_limits<double>::max(), player->currentTime()); EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift()); updateTimeline(100); EXPECT_EQ(std::numeric_limits<double>::max(), player->currentTime()); EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift()); } }
bsd-3-clause
dushmis/Oracle-Cloud
PaaS_SaaS_Accelerator_RESTFulFacade/Fusion_UserDetailsService/src/com/oracle/xmlns/apps/hcm/people/roles/userdetailsservicev2/types/ObjectFactory.java
7459
package com.oracle.xmlns.apps.hcm.people.roles.userdetailsservicev2.types; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.oracle.xmlns.apps.hcm.people.roles.userdetailsservicev2.types package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.oracle.xmlns.apps.hcm.people.roles.userdetailsservicev2.types * */ public ObjectFactory() { } /** * Create an instance of {@link FindSelfUserDetailsAsyncResponse } * */ public FindSelfUserDetailsAsyncResponse createFindSelfUserDetailsAsyncResponse() { return new FindSelfUserDetailsAsyncResponse(); } /** * Create an instance of {@link FindUserDetailsByPersonIdAsyncResponse } * */ public FindUserDetailsByPersonIdAsyncResponse createFindUserDetailsByPersonIdAsyncResponse() { return new FindUserDetailsByPersonIdAsyncResponse(); } /** * Create an instance of {@link GetServiceLastUpdateTimeAsync } * */ public GetServiceLastUpdateTimeAsync createGetServiceLastUpdateTimeAsync() { return new GetServiceLastUpdateTimeAsync(); } /** * Create an instance of {@link FindSelfUserDetailsAsync } * */ public FindSelfUserDetailsAsync createFindSelfUserDetailsAsync() { return new FindSelfUserDetailsAsync(); } /** * Create an instance of {@link FindUserDetailsByPersonNumberResponse } * */ public FindUserDetailsByPersonNumberResponse createFindUserDetailsByPersonNumberResponse() { return new FindUserDetailsByPersonNumberResponse(); } /** * Create an instance of {@link GetEntityListAsyncResponse } * */ public GetEntityListAsyncResponse createGetEntityListAsyncResponse() { return new GetEntityListAsyncResponse(); } /** * Create an instance of {@link FindUserDetailsByUsername } * */ public FindUserDetailsByUsername createFindUserDetailsByUsername() { return new FindUserDetailsByUsername(); } /** * Create an instance of {@link GetDfltObjAttrHints } * */ public GetDfltObjAttrHints createGetDfltObjAttrHints() { return new GetDfltObjAttrHints(); } /** * Create an instance of {@link GetDfltObjAttrHintsAsyncResponse } * */ public GetDfltObjAttrHintsAsyncResponse createGetDfltObjAttrHintsAsyncResponse() { return new GetDfltObjAttrHintsAsyncResponse(); } /** * Create an instance of {@link FindUserDetailsByPersonId } * */ public FindUserDetailsByPersonId createFindUserDetailsByPersonId() { return new FindUserDetailsByPersonId(); } /** * Create an instance of {@link FindUserDetailsByPersonNumberAsyncResponse } * */ public FindUserDetailsByPersonNumberAsyncResponse createFindUserDetailsByPersonNumberAsyncResponse() { return new FindUserDetailsByPersonNumberAsyncResponse(); } /** * Create an instance of {@link FindSelfUserDetails } * */ public FindSelfUserDetails createFindSelfUserDetails() { return new FindSelfUserDetails(); } /** * Create an instance of {@link GetEntityListAsync } * */ public GetEntityListAsync createGetEntityListAsync() { return new GetEntityListAsync(); } /** * Create an instance of {@link FindUserDetailsByPersonNumber } * */ public FindUserDetailsByPersonNumber createFindUserDetailsByPersonNumber() { return new FindUserDetailsByPersonNumber(); } /** * Create an instance of {@link FindUserDetailsByPersonIdAsync } * */ public FindUserDetailsByPersonIdAsync createFindUserDetailsByPersonIdAsync() { return new FindUserDetailsByPersonIdAsync(); } /** * Create an instance of {@link GetEntityList } * */ public GetEntityList createGetEntityList() { return new GetEntityList(); } /** * Create an instance of {@link GetDfltObjAttrHintsAsync } * */ public GetDfltObjAttrHintsAsync createGetDfltObjAttrHintsAsync() { return new GetDfltObjAttrHintsAsync(); } /** * Create an instance of {@link FindUserDetailsByUsernameAsyncResponse } * */ public FindUserDetailsByUsernameAsyncResponse createFindUserDetailsByUsernameAsyncResponse() { return new FindUserDetailsByUsernameAsyncResponse(); } /** * Create an instance of {@link GetEntityListResponse } * */ public GetEntityListResponse createGetEntityListResponse() { return new GetEntityListResponse(); } /** * Create an instance of {@link GetServiceLastUpdateTimeAsyncResponse } * */ public GetServiceLastUpdateTimeAsyncResponse createGetServiceLastUpdateTimeAsyncResponse() { return new GetServiceLastUpdateTimeAsyncResponse(); } /** * Create an instance of {@link FindSelfUserDetailsResponse } * */ public FindSelfUserDetailsResponse createFindSelfUserDetailsResponse() { return new FindSelfUserDetailsResponse(); } /** * Create an instance of {@link FindUserDetailsByPersonNumberAsync } * */ public FindUserDetailsByPersonNumberAsync createFindUserDetailsByPersonNumberAsync() { return new FindUserDetailsByPersonNumberAsync(); } /** * Create an instance of {@link FindUserDetailsByPersonIdResponse } * */ public FindUserDetailsByPersonIdResponse createFindUserDetailsByPersonIdResponse() { return new FindUserDetailsByPersonIdResponse(); } /** * Create an instance of {@link GetDfltObjAttrHintsResponse } * */ public GetDfltObjAttrHintsResponse createGetDfltObjAttrHintsResponse() { return new GetDfltObjAttrHintsResponse(); } /** * Create an instance of {@link GetServiceLastUpdateTimeResponse } * */ public GetServiceLastUpdateTimeResponse createGetServiceLastUpdateTimeResponse() { return new GetServiceLastUpdateTimeResponse(); } /** * Create an instance of {@link FindUserDetailsByUsernameAsync } * */ public FindUserDetailsByUsernameAsync createFindUserDetailsByUsernameAsync() { return new FindUserDetailsByUsernameAsync(); } /** * Create an instance of {@link FindUserDetailsByUsernameResponse } * */ public FindUserDetailsByUsernameResponse createFindUserDetailsByUsernameResponse() { return new FindUserDetailsByUsernameResponse(); } /** * Create an instance of {@link GetServiceLastUpdateTime } * */ public GetServiceLastUpdateTime createGetServiceLastUpdateTime() { return new GetServiceLastUpdateTime(); } }
bsd-3-clause
MITK/MITK
Modules/Core/src/IO/mitkOperation.cpp
632
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkOperation.h" mitk::Operation::Operation(mitk::OperationType operationType) : m_OperationType(operationType) { } mitk::Operation::~Operation() { } mitk::OperationType mitk::Operation::GetOperationType() { return m_OperationType; }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE23_Relative_Path_Traversal/s04/CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_65a.cpp
3350
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_65a.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-65a.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: file Read input from a file * GoodSource: Use a fixed file name * Sinks: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH L"c:\\temp\\" #else #include <wchar.h> #define BASEPATH L"/tmp/" #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_65 { #ifndef OMITBAD /* bad function declaration */ void badSink(wchar_t * data); void bad() { wchar_t * data; /* define a function pointer */ void (*funcPtr) (wchar_t *) = badSink; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(wchar_t * data); static void goodG2B() { wchar_t * data; void (*funcPtr) (wchar_t *) = goodG2BSink; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ wcscat(data, L"file.txt"); funcPtr(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_65; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
DataBiosphere/terra-workspace-manager
service/src/main/java/bio/terra/workspace/service/workspace/exceptions/RetryableCrlException.java
571
package bio.terra.workspace.service.workspace.exceptions; import bio.terra.stairway.exception.RetryException; /** * Exception for retryable errors thrown by the Cloud Resource Library (CRL). * * <p>This extends Stairway's RetryException, which will signal Stairway to retry any step this is * thrown from (modulo a retry rule). */ public class RetryableCrlException extends RetryException { public RetryableCrlException(String message) { super(message); } public RetryableCrlException(String message, Throwable cause) { super(message, cause); } }
bsd-3-clause
ric2b/Vivaldi-browser
thirdparty/gn/src/gn/command_help.cc
13227
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "gn/args.h" #include "gn/commands.h" #include "gn/err.h" #include "gn/functions.h" #include "gn/input_conversion.h" #include "gn/label.h" #include "gn/label_pattern.h" #include "gn/metadata.h" #include "gn/ninja_build_writer.h" #include "gn/output_conversion.h" #include "gn/parser.h" #include "gn/pattern.h" #include "gn/runtime_deps.h" #include "gn/setup.h" #include "gn/standard_out.h" #include "gn/string_utils.h" #include "gn/substitution_writer.h" #include "gn/switches.h" #include "gn/target.h" #include "gn/variables.h" namespace commands { namespace { // Some names exist in multiple sections, these prefixes are used for the // internal links to disambiguate when writing markdown. const char kCommandLinkPrefix[] = "cmd_"; const char kFunctionLinkPrefix[] = "func_"; const char kVariableLinkPrefix[] = "var_"; void PrintToplevelHelp() { PrintSectionHelp("Commands", "<command>", "commands"); for (const auto& cmd : commands::GetCommands()) PrintShortHelp(cmd.second.help_short, kCommandLinkPrefix + cmd.first); // Target declarations. PrintSectionHelp("Target declarations", "<function>", "targets"); for (const auto& func : functions::GetFunctions()) { if (func.second.is_target) PrintShortHelp(func.second.help_short, kFunctionLinkPrefix + func.first); } // Functions. PrintSectionHelp("Buildfile functions", "<function>", "functions"); for (const auto& func : functions::GetFunctions()) { if (!func.second.is_target) PrintShortHelp(func.second.help_short, kFunctionLinkPrefix + func.first); } // Built-in variables. PrintSectionHelp("Built-in predefined variables", "<variable>", "predefined_variables"); for (const auto& builtin : variables::GetBuiltinVariables()) { PrintShortHelp(builtin.second.help_short, kVariableLinkPrefix + builtin.first); } // Target variables. PrintSectionHelp("Variables you set in targets", "<variable>", "target_variables"); for (const auto& target : variables::GetTargetVariables()) { PrintShortHelp(target.second.help_short, kVariableLinkPrefix + target.first); } PrintSectionHelp("Other help topics", "", "other"); PrintShortHelp("all: Print all the help at once"); PrintShortHelp("buildargs: How build arguments work.", "buildargs"); PrintShortHelp("dotfile: Info about the toplevel .gn file.", "dotfile"); PrintShortHelp("execution: Build graph and execution overview.", "execution"); PrintShortHelp("grammar: Language and grammar for GN build files.", "grammar"); PrintShortHelp( "input_conversion: Processing input from exec_script and read_file.", "io_conversion"); PrintShortHelp("file_pattern: Matching more than one file.", "file_pattern"); PrintShortHelp("label_pattern: Matching more than one label.", "label_pattern"); PrintShortHelp("labels: About labels.", "labels"); PrintShortHelp("metadata_collection: About metadata and its collection.", "metadata_collection"); PrintShortHelp("ninja_rules: How Ninja build rules are named.", "ninja_rules"); PrintShortHelp("nogncheck: Annotating includes for checking.", "nogncheck"); PrintShortHelp( "output_conversion: Specifies how to transform a value to output.", "io_conversion"); PrintShortHelp("runtime_deps: How runtime dependency computation works.", "runtime_deps"); PrintShortHelp("source_expansion: Map sources to outputs for scripts.", "source_expansion"); PrintShortHelp("switches: Show available command-line switches.", "switch_list"); } void PrintSwitchHelp() { const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); bool is_markdown = cmdline->HasSwitch(switches::kMarkdown); // This uses "switch_list" for the tag because Markdown seems to generate // implicit tags for headings that match the strings, and some headings are // labeled "switches". PrintLongHelp(R"(Available global switches Do "gn help --the_switch_you_want_help_on" for more. Individual commands may take command-specific switches not listed here. See the help on your specific command for more. )", "switch_list"); if (is_markdown) OutputString("```\n", DECORATION_NONE); for (const auto& s : switches::GetSwitches()) PrintShortHelp(s.second.short_help); if (is_markdown) OutputString("```\n", DECORATION_NONE); OutputString("\n"); } void PrintAllHelp() { const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); bool is_markdown = cmdline->HasSwitch(switches::kMarkdown); if (is_markdown) { OutputString("# GN Reference\n\n"); OutputString( "*This page is automatically generated from* " "`gn help --markdown all`.\n\n"); // Generate our own table of contents so that we have more control // over what's in and out. OutputString("## Contents\n\n"); } PrintToplevelHelp(); OutputString("\n"); if (is_markdown) { OutputString("## <a name=\"commands\"></a>Commands\n\n", DECORATION_NONE, NO_ESCAPING); } for (const auto& c : commands::GetCommands()) PrintLongHelp(c.second.help, kCommandLinkPrefix + c.first); if (is_markdown) { OutputString("## <a name=\"targets\"></a>Target declarations\n\n", DECORATION_NONE, NO_ESCAPING); } for (const auto& f : functions::GetFunctions()) { if (f.second.is_target) PrintLongHelp(f.second.help, kFunctionLinkPrefix + f.first); } if (is_markdown) { OutputString("## <a name=\"functions\"></a>Buildfile functions\n\n", DECORATION_NONE, NO_ESCAPING); } for (const auto& f : functions::GetFunctions()) { if (!f.second.is_target) PrintLongHelp(f.second.help, kFunctionLinkPrefix + f.first); } if (is_markdown) { OutputString( "## <a name=\"predefined_variables\"></a>" "Built-in predefined variables\n\n", DECORATION_NONE, NO_ESCAPING); } for (const auto& v : variables::GetBuiltinVariables()) PrintLongHelp(v.second.help, kVariableLinkPrefix + v.first); if (is_markdown) { OutputString( "## <a name=\"target_variables\"></a>" "Variables you set in targets\n\n", DECORATION_NONE, NO_ESCAPING); } for (const auto& v : variables::GetTargetVariables()) PrintLongHelp(v.second.help, kVariableLinkPrefix + v.first); if (is_markdown) { OutputString("## <a name=\"other\"></a>Other help topics\n\n", DECORATION_NONE, NO_ESCAPING); } PrintLongHelp(kBuildArgs_Help, "buildargs"); PrintLongHelp(kDotfile_Help, "dotfile"); PrintLongHelp(kExecution_Help, "execution"); PrintLongHelp(kGrammar_Help, "grammar"); PrintLongHelp(kInputOutputConversion_Help, "io_conversion"); PrintLongHelp(kFilePattern_Help, "file_pattern"); PrintLongHelp(kLabelPattern_Help, "label_pattern"); PrintLongHelp(kLabels_Help, "labels"); PrintLongHelp(kMetadata_Help, "metadata_collection"); PrintLongHelp(kNinjaRules_Help, "ninja_rules"); PrintLongHelp(kNoGnCheck_Help, "nogncheck"); PrintLongHelp(kRuntimeDeps_Help, "runtime_deps"); PrintLongHelp(kSourceExpansion_Help, "source_expansion"); PrintSwitchHelp(); } // Prints help on the given switch. There should be no leading hyphens. Returns // true if the switch was found and help was printed. False means the switch is // unknown. bool PrintHelpOnSwitch(const std::string& what) { const switches::SwitchInfoMap& all = switches::GetSwitches(); switches::SwitchInfoMap::const_iterator found = all.find(std::string_view(what)); if (found == all.end()) return false; PrintLongHelp(found->second.long_help); return true; } // Special-case help for ambiguous "args" case. void PrintArgsHelp() { PrintLongHelp( "The string \"args\" is both a command and a variable for action " "targets.\nShowing help for both...\n\n"); PrintLongHelp(commands::kArgs_Help); PrintLongHelp( "\n----------------------------------------------------------------------" "---------\n\n"); PrintLongHelp(variables::kArgs_Help); } } // namespace const char kHelp[] = "help"; const char kHelp_HelpShort[] = "help: Does what you think."; const char kHelp_Help[] = R"(gn help <anything> Yo dawg, I heard you like help on your help so I put help on the help in the help. You can also use "all" as the parameter to get all help at once. Switches --markdown Format output in markdown syntax. Example gn help --markdown all Dump all help to stdout in markdown format. )"; int RunHelp(const std::vector<std::string>& args) { std::string what; if (args.size() == 0) { // If no argument is specified, check for switches to allow things like // "gn help --args" for help on the args switch. const base::CommandLine::SwitchMap& switches = base::CommandLine::ForCurrentProcess()->GetSwitches(); if (switches.empty()) { // Still nothing, show help overview. PrintToplevelHelp(); return 0; } // Switch help needs to be done separately. The CommandLine will strip the // switch separators so --args will come out as "args" which is then // ambiguous with the variable named "args". if (!PrintHelpOnSwitch(switches.begin()->first)) PrintToplevelHelp(); return 0; } else { what = args[0]; } std::vector<std::string_view> all_help_topics; // Special-case ambiguous topics. if (what == "args") { PrintArgsHelp(); return 0; } // Check commands. const commands::CommandInfoMap& command_map = commands::GetCommands(); auto found_command = command_map.find(what); if (found_command != command_map.end()) { PrintLongHelp(found_command->second.help); return 0; } for (const auto& entry : command_map) all_help_topics.push_back(entry.first); // Check functions. const functions::FunctionInfoMap& function_map = functions::GetFunctions(); auto found_function = function_map.find(what); if (found_function != function_map.end()) PrintLongHelp(found_function->second.help); for (const auto& entry : function_map) all_help_topics.push_back(entry.first); // Builtin variables. const variables::VariableInfoMap& builtin_vars = variables::GetBuiltinVariables(); auto found_builtin_var = builtin_vars.find(what); if (found_builtin_var != builtin_vars.end()) PrintLongHelp(found_builtin_var->second.help); for (const auto& entry : builtin_vars) all_help_topics.push_back(entry.first); // Target variables. const variables::VariableInfoMap& target_vars = variables::GetTargetVariables(); auto found_target_var = target_vars.find(what); if (found_target_var != target_vars.end()) PrintLongHelp(found_target_var->second.help); for (const auto& entry : target_vars) all_help_topics.push_back(entry.first); if (found_function != function_map.end() || found_builtin_var != builtin_vars.end() || found_target_var != target_vars.end()) return 0; // Random other topics. std::map<std::string, void (*)()> random_topics; random_topics["all"] = PrintAllHelp; random_topics["execution"] = []() { PrintLongHelp(kExecution_Help); }; random_topics["buildargs"] = []() { PrintLongHelp(kBuildArgs_Help); }; random_topics["dotfile"] = []() { PrintLongHelp(kDotfile_Help); }; random_topics["grammar"] = []() { PrintLongHelp(kGrammar_Help); }; random_topics["io_conversion"] = []() { PrintLongHelp(kInputOutputConversion_Help); }; random_topics["file_pattern"] = []() { PrintLongHelp(kFilePattern_Help); }; random_topics["label_pattern"] = []() { PrintLongHelp(kLabelPattern_Help); }; random_topics["labels"] = []() { PrintLongHelp(kLabels_Help); }; random_topics["metadata_collection"] = []() { PrintLongHelp(kMetadata_Help); }; random_topics["ninja_rules"] = []() { PrintLongHelp(kNinjaRules_Help); }; random_topics["nogncheck"] = []() { PrintLongHelp(kNoGnCheck_Help); }; random_topics["runtime_deps"] = []() { PrintLongHelp(kRuntimeDeps_Help); }; random_topics["source_expansion"] = []() { PrintLongHelp(kSourceExpansion_Help); }; random_topics["switches"] = PrintSwitchHelp; auto found_random_topic = random_topics.find(what); if (found_random_topic != random_topics.end()) { found_random_topic->second(); return 0; } for (const auto& entry : random_topics) all_help_topics.push_back(entry.first); // No help on this. Err(Location(), "No help on \"" + what + "\".").PrintToStdout(); std::string_view suggestion = SpellcheckString(what, all_help_topics); if (suggestion.empty()) { OutputString("Run `gn help` for a list of available topics.\n", DECORATION_NONE); } else { OutputString("Did you mean `gn help " + std::string(suggestion) + "`?\n", DECORATION_NONE); } return 1; } } // namespace commands
bsd-3-clause
lognormal/boomerang
tests/page-templates/00-basic/00-onload.js
2949
/*eslint-env mocha*/ /*global BOOMR_test,assert*/ describe("e2e/00-basic/00-onload", function() { var tf = BOOMR.plugins.TestFramework; it("Should have sent a beacon", function() { // ensure we fired a beacon ('beacon') assert.isTrue(tf.fired_onbeacon); }); it("Should have fired 'beacon' with a beacon payload", function() { // ensure the data was sent to 'beacon' assert.isObject(tf.lastBeacon()); }); it("Should have set basic beacon properties", function() { assert.isString(tf.lastBeacon().v); }); it("Should have set dom.* properties", function() { assert.isNumber(tf.lastBeacon()["dom.img"], "dom.img"); assert.isNumber(tf.lastBeacon()["dom.ln"], "dom.ln"); assert.isNumber(tf.lastBeacon()["dom.script"], "dom.script"); assert.isNumber(tf.lastBeacon()["dom.sz"], "dom.sz"); if (BOOMR_test.isResourceTimingSupported()) { assert.isNumber(tf.lastBeacon()["dom.doms"], "dom.doms"); assert.isNumber(tf.lastBeacon()["dom.res"], "dom.res"); } }); it("Should have set mem.* properties", function() { if ((window.performance && window.performance.memory) || (window.console && window.console.memory)) { assert.isNumber(tf.lastBeacon()["mem.total"], "mem.total"); assert.isNumber(tf.lastBeacon()["mem.used"], "mem.used"); // Might not exist except recent builds if (tf.lastBeacon()["mem.limit"]) { assert.isNumber(tf.lastBeacon()["mem.limit"], "mem.limit"); } } }); it("Should have set RT properties", function() { assert.isString(tf.lastBeacon().u, "u"); assert.isNumber(tf.lastBeacon()["rt.bstart"], "rt.bstart"); assert.isNumber(tf.lastBeacon()["rt.end"], "rt.end"); assert.isString(tf.lastBeacon()["rt.si"], "rt.si"); assert.isNumber(tf.lastBeacon()["rt.sl"], "rt.sl"); assert.isNumber(tf.lastBeacon()["rt.ss"], "rt.ss"); assert.isString(tf.lastBeacon()["rt.start"], "rt.start"); // optional if (typeof tf.lastBeacon()["rt.tstart"] !== "undefined") { assert.isNumber(tf.lastBeacon()["rt.tstart"], "rt.tstart"); } }); it("Should have set scr.* properties", function() { var s = window.screen; assert.isString(tf.lastBeacon()["scr.bpp"], "scr.bpp"); assert.isString(tf.lastBeacon()["scr.xy"], "scr.xy"); // only if we have orientation if (s && s.orientation) { assert.isString(tf.lastBeacon()["scr.orn"], "scr.orn"); } // only if we have pixel ratio if (window.devicePixelRatio && window.devicePixelRatio > 1) { assert.isNumber(tf.lastBeacon()["scr.dpx"], "scr.dpx"); } }); it("Should have set LOGN / SOASTA properties", function() { assert.isString(tf.lastBeacon()["h.key"], "h.key"); }); it("Should have set vis.* properties", function() { assert.isString(tf.lastBeacon()["vis.st"], "vis.st"); }); it("Should have set Page ID (pid)", function() { assert.isString(tf.lastBeacon().pid, "pid"); }); it("Should have not set nocookie", function() { assert.isUndefined(tf.lastBeacon().nocookie); }); });
bsd-3-clause
Tietoarkisto/metka
metka/src/main/java/fi/uta/fsd/metkaAmqp/factories/AuditFactory.java
3218
/************************************************************************************** * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, * * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************/ package fi.uta.fsd.metkaAmqp.factories; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import fi.uta.fsd.metkaAmqp.payloads.AuditPayload; public class AuditFactory extends PayloadFactoryBase<AuditPayload> { @Override public String buildRoutingKey(String resource, String event, AuditPayload payload) { return super.buildRoutingKey(resource, event, payload)+payload.getResult(); } @Override public JsonNode build(String resource, String event, AuditPayload payload) { ObjectNode base = (ObjectNode)super.build(resource, event, payload); base.set("target", new TextNode(payload.getMessage())); base.set("result", new TextNode(payload.getResult())); return base; } }
bsd-3-clause
gasman/wagtail
wagtail/admin/tests/api/test_pages.py
34733
import collections import datetime import json from django.contrib.auth import get_user_model from django.urls import reverse from django.utils import timezone from wagtail.api.v2.tests.test_pages import TestPageDetail, TestPageListing from wagtail.core import hooks from wagtail.core.models import Locale, Page from wagtail.tests.demosite import models from wagtail.tests.testapp.models import SimplePage, StreamPage from wagtail.users.models import UserProfile from .utils import AdminAPITestCase def get_total_page_count(): # Need to take away 1 as the root page is invisible over the API by default return Page.objects.count() - 1 class TestAdminPageListing(AdminAPITestCase, TestPageListing): fixtures = ['demosite.json'] def get_response(self, **params): return self.client.get(reverse('wagtailadmin_api:pages:listing'), params) def get_page_id_list(self, content): return [page['id'] for page in content['items']] # BASIC TESTS def test_basic(self): response = self.get_response() self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-type'], 'application/json') # Will crash if the JSON is invalid content = json.loads(response.content.decode('UTF-8')) # Check that the meta section is there self.assertIn('meta', content) self.assertIsInstance(content['meta'], dict) # Check that the total count is there and correct self.assertIn('total_count', content['meta']) self.assertIsInstance(content['meta']['total_count'], int) self.assertEqual(content['meta']['total_count'], get_total_page_count()) # Check that the items section is there self.assertIn('items', content) self.assertIsInstance(content['items'], list) # Check that each page has a meta section with type, detail_url, html_url, status and children attributes for page in content['items']: self.assertIn('meta', page) self.assertIsInstance(page['meta'], dict) self.assertEqual(set(page['meta'].keys()), {'type', 'detail_url', 'html_url', 'status', 'children', 'slug', 'first_published_at', 'latest_revision_created_at'}) # Check the type info self.assertIsInstance(content['__types'], dict) self.assertEqual(set(content['__types'].keys()), { 'demosite.EventPage', 'demosite.StandardIndexPage', 'demosite.PersonPage', 'demosite.HomePage', 'demosite.StandardPage', 'demosite.EventIndexPage', 'demosite.ContactPage', 'demosite.BlogEntryPage', 'demosite.BlogIndexPage', }) self.assertEqual(set(content['__types']['demosite.EventPage'].keys()), {'verbose_name', 'verbose_name_plural'}) self.assertEqual(content['__types']['demosite.EventPage']['verbose_name'], 'event page') self.assertEqual(content['__types']['demosite.EventPage']['verbose_name_plural'], 'event pages') # Not applicable to the admin API test_unpublished_pages_dont_appear_in_list = None test_private_pages_dont_appear_in_list = None def test_unpublished_pages_appear_in_list(self): total_count = get_total_page_count() page = models.BlogEntryPage.objects.get(id=16) page.unpublish() response = self.get_response() content = json.loads(response.content.decode('UTF-8')) self.assertEqual(content['meta']['total_count'], total_count) def test_private_pages_appear_in_list(self): total_count = get_total_page_count() page = models.BlogIndexPage.objects.get(id=5) page.view_restrictions.create(password='test') new_total_count = get_total_page_count() self.assertEqual(total_count, total_count) response = self.get_response() content = json.loads(response.content.decode('UTF-8')) self.assertEqual(content['meta']['total_count'], new_total_count) def test_get_in_non_content_language(self): # set logged-in user's admin UI language to Swedish user = get_user_model().objects.get(email='test@email.com') UserProfile.objects.update_or_create(user=user, defaults={'preferred_language': 'se'}) response = self.get_response() self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-type'], 'application/json') # Will crash if the JSON is invalid content = json.loads(response.content.decode('UTF-8')) self.assertIn('meta', content) # FIELDS # Not applicable to the admin API test_parent_field_gives_error = None def test_fields(self): response = self.get_response(type='demosite.BlogEntryPage', fields='title,date,feed_image') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title', 'date', 'feed_image'}) def test_fields_default(self): response = self.get_response(type='demosite.BlogEntryPage') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title'}) self.assertEqual(set(page['meta'].keys()), {'type', 'detail_url', 'html_url', 'children', 'status', 'slug', 'first_published_at', 'latest_revision_created_at'}) def test_remove_meta_fields(self): response = self.get_response(fields='-html_url') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title'}) self.assertEqual(set(page['meta'].keys()), {'type', 'detail_url', 'slug', 'first_published_at', 'latest_revision_created_at', 'status', 'children'}) def test_remove_all_meta_fields(self): response = self.get_response(fields='-type,-detail_url,-slug,-first_published_at,-html_url,-latest_revision_created_at,-status,-children') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'title', 'admin_display_title'}) def test_remove_fields(self): response = self.get_response(fields='-title,-admin_display_title') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta'}) def test_remove_id_field(self): response = self.get_response(fields='-id') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'meta', 'title', 'admin_display_title'}) def test_all_fields(self): response = self.get_response(type='demosite.BlogEntryPage', fields='*') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title', 'date', 'related_links', 'tags', 'carousel_items', 'body', 'feed_image', 'feed_image_thumbnail'}) self.assertEqual(set(page['meta'].keys()), {'type', 'detail_url', 'show_in_menus', 'first_published_at', 'seo_title', 'slug', 'parent', 'html_url', 'search_description', 'locale', 'children', 'descendants', 'ancestors', 'translations', 'status', 'latest_revision_created_at'}) def test_all_fields_then_remove_something(self): response = self.get_response(type='demosite.BlogEntryPage', fields='*,-title,-admin_display_title,-date,-seo_title,-status') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'related_links', 'tags', 'carousel_items', 'body', 'feed_image', 'feed_image_thumbnail'}) self.assertEqual(set(page['meta'].keys()), {'type', 'detail_url', 'show_in_menus', 'first_published_at', 'slug', 'parent', 'html_url', 'search_description', 'locale', 'children', 'descendants', 'ancestors', 'translations', 'latest_revision_created_at'}) def test_all_nested_fields(self): response = self.get_response(type='demosite.BlogEntryPage', fields='feed_image(*)') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page['feed_image'].keys()), {'id', 'meta', 'title', 'width', 'height', 'thumbnail'}) def test_fields_foreign_key(self): # Only the base the detail_url is different here from the public API response = self.get_response(type='demosite.BlogEntryPage', fields='title,date,feed_image') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: feed_image = page['feed_image'] if feed_image is not None: self.assertIsInstance(feed_image, dict) self.assertEqual(set(feed_image.keys()), {'id', 'meta', 'title'}) self.assertIsInstance(feed_image['id'], int) self.assertIsInstance(feed_image['meta'], dict) self.assertEqual(set(feed_image['meta'].keys()), {'type', 'detail_url', 'download_url'}) self.assertEqual(feed_image['meta']['type'], 'wagtailimages.Image') self.assertEqual(feed_image['meta']['detail_url'], 'http://localhost/admin/api/main/images/%d/' % feed_image['id']) def test_fields_parent(self): response = self.get_response(type='demosite.BlogEntryPage', fields='parent') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: parent = page['meta']['parent'] # All blog entry pages have the same parent self.assertDictEqual(parent, { 'id': 5, 'meta': { 'type': 'demosite.BlogIndexPage', 'detail_url': 'http://localhost/admin/api/main/pages/5/', 'html_url': 'http://localhost/blog-index/', }, 'title': "Blog index" }) def test_fields_descendants(self): response = self.get_response(fields='descendants') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: descendants = page['meta']['descendants'] self.assertEqual(set(descendants.keys()), {'count', 'listing_url'}) self.assertIsInstance(descendants['count'], int) self.assertEqual(descendants['listing_url'], 'http://localhost/admin/api/main/pages/?descendant_of=%d' % page['id']) def test_fields_child_relation(self): response = self.get_response(type='demosite.BlogEntryPage', fields='title,related_links') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title', 'related_links'}) self.assertIsInstance(page['related_links'], list) def test_fields_ordering(self): response = self.get_response(type='demosite.BlogEntryPage', fields='date,title,feed_image,related_links') # Will crash if the JSON is invalid content = json.loads(response.content.decode('UTF-8')) # Test field order content = json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(response.content.decode('UTF-8')) field_order = [ 'id', 'meta', 'title', 'admin_display_title', 'date', 'feed_image', 'related_links', ] self.assertEqual(list(content['items'][0].keys()), field_order) def test_fields_tags(self): response = self.get_response(type='demosite.BlogEntryPage', fields='tags') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(set(page.keys()), {'id', 'meta', 'tags', 'title', 'admin_display_title'}) self.assertIsInstance(page['tags'], list) def test_fields_translations(self): # Add a translation of the homepage french = Locale.objects.create(language_code='fr') homepage = Page.objects.get(depth=2) french_homepage = homepage.copy_for_translation(french) response = self.get_response(fields='translations') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: translations = page['meta']['translations'] if page['id'] == homepage.id: self.assertEqual(len(translations), 1) self.assertEqual(translations[0]['id'], french_homepage.id) self.assertEqual(translations[0]['meta']['locale'], 'fr') elif page['id'] == french_homepage.id: self.assertEqual(len(translations), 1) self.assertEqual(translations[0]['id'], homepage.id) self.assertEqual(translations[0]['meta']['locale'], 'en') else: self.assertEqual(translations, []) # CHILD OF FILTER # Not applicable to the admin API test_child_of_page_thats_not_in_same_site_gives_error = None def test_child_of_root(self): # Only return the homepage as that's the only child of the "root" node # in the tree. This is different to the public API which pretends the # homepage of the current site is the root page. response = self.get_response(child_of='root') content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [2]) def test_child_of_page_1(self): # Public API doesn't allow this, as it's the root page response = self.get_response(child_of=1) json.loads(response.content.decode('UTF-8')) self.assertEqual(response.status_code, 200) # DESCENDANT OF FILTER # Not applicable to the admin API test_descendant_of_page_thats_not_in_same_site_gives_error = None def test_descendant_of_root(self): response = self.get_response(descendant_of='root') content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [2, 4, 8, 9, 5, 16, 18, 19, 6, 10, 15, 17, 21, 22, 23, 20, 13, 14, 12]) def test_descendant_of_root_doesnt_give_error(self): # Public API doesn't allow this response = self.get_response(descendant_of=1) json.loads(response.content.decode('UTF-8')) self.assertEqual(response.status_code, 200) # FOR EXPLORER FILTER def make_simple_page(self, parent, title): return parent.add_child(instance=SimplePage(title=title, content='Simple page')) def test_for_explorer_filter(self): movies = self.make_simple_page(Page.objects.get(pk=1), 'Movies') visible_movies = [ self.make_simple_page(movies, 'The Way of the Dragon'), self.make_simple_page(movies, 'Enter the Dragon'), self.make_simple_page(movies, 'Dragons Forever'), ] hidden_movies = [ self.make_simple_page(movies, 'The Hidden Fortress'), self.make_simple_page(movies, 'Crouching Tiger, Hidden Dragon'), self.make_simple_page(movies, 'Crouching Tiger, Hidden Dragon: Sword of Destiny'), ] response = self.get_response(child_of=movies.pk, for_explorer=1) content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [page.pk for page in visible_movies]) response = self.get_response(child_of=movies.pk) content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [page.pk for page in visible_movies + hidden_movies]) def test_for_explorer_no_child_of(self): response = self.get_response(for_explorer=1) self.assertEqual(response.status_code, 400) content = json.loads(response.content.decode('UTF-8')) self.assertEqual(content, { 'message': 'filtering by for_explorer without child_of is not supported', }) def test_for_explorer_construct_explorer_page_queryset_ordering(self): def set_custom_ordering(parent_page, pages, request): return pages.order_by('-title') with hooks.register_temporarily('construct_explorer_page_queryset', set_custom_ordering): response = self.get_response(for_explorer=True, child_of=2) content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [6, 20, 4, 12, 5]) # HAS CHILDREN FILTER def test_has_children_filter(self): response = self.get_response(has_children='true') content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [2, 4, 5, 6, 21, 20]) def test_has_children_filter_off(self): response = self.get_response(has_children='false') content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [8, 9, 16, 18, 19, 10, 15, 17, 22, 23, 13, 14, 12]) def test_has_children_filter_int(self): response = self.get_response(has_children=1) content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [2, 4, 5, 6, 21, 20]) def test_has_children_filter_int_off(self): response = self.get_response(has_children=0) content = json.loads(response.content.decode('UTF-8')) page_id_list = self.get_page_id_list(content) self.assertEqual(page_id_list, [8, 9, 16, 18, 19, 10, 15, 17, 22, 23, 13, 14, 12]) def test_has_children_filter_invalid_integer(self): response = self.get_response(has_children=3) content = json.loads(response.content.decode('UTF-8')) self.assertEqual(response.status_code, 400) self.assertEqual(content, {'message': "has_children must be 'true' or 'false'"}) def test_has_children_filter_invalid_value(self): response = self.get_response(has_children='yes') content = json.loads(response.content.decode('UTF-8')) self.assertEqual(response.status_code, 400) self.assertEqual(content, {'message': "has_children must be 'true' or 'false'"}) # TYPE FILTER def test_type_filter_items_are_all_blog_entries(self): response = self.get_response(type='demosite.BlogEntryPage') content = json.loads(response.content.decode('UTF-8')) for page in content['items']: self.assertEqual(page['meta']['type'], 'demosite.BlogEntryPage') # No specific fields available by default self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title'}) def test_type_filter_multiple(self): response = self.get_response(type='demosite.BlogEntryPage,demosite.EventPage') content = json.loads(response.content.decode('UTF-8')) blog_page_seen = False event_page_seen = False for page in content['items']: self.assertIn(page['meta']['type'], ['demosite.BlogEntryPage', 'demosite.EventPage']) if page['meta']['type'] == 'demosite.BlogEntryPage': blog_page_seen = True elif page['meta']['type'] == 'demosite.EventPage': event_page_seen = True # Only generic fields available self.assertEqual(set(page.keys()), {'id', 'meta', 'title', 'admin_display_title'}) self.assertTrue(blog_page_seen, "No blog pages were found in the items") self.assertTrue(event_page_seen, "No event pages were found in the items") class TestAdminPageDetail(AdminAPITestCase, TestPageDetail): fixtures = ['demosite.json'] def get_response(self, page_id, **params): return self.client.get(reverse('wagtailadmin_api:pages:detail', args=(page_id, )), params) def test_basic(self): response = self.get_response(16) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-type'], 'application/json') # Will crash if the JSON is invalid content = json.loads(response.content.decode('UTF-8')) # Check the id field self.assertIn('id', content) self.assertEqual(content['id'], 16) # Check that the meta section is there self.assertIn('meta', content) self.assertIsInstance(content['meta'], dict) # Check the meta type self.assertIn('type', content['meta']) self.assertEqual(content['meta']['type'], 'demosite.BlogEntryPage') # Check the meta detail_url self.assertIn('detail_url', content['meta']) self.assertEqual(content['meta']['detail_url'], 'http://localhost/admin/api/main/pages/16/') # Check the meta html_url self.assertIn('html_url', content['meta']) self.assertEqual(content['meta']['html_url'], 'http://localhost/blog-index/blog-post/') # Check the meta status self.assertIn('status', content['meta']) self.assertEqual(content['meta']['status'], { 'status': 'live', 'live': True, 'has_unpublished_changes': False }) # Check the meta children self.assertIn('children', content['meta']) self.assertEqual(content['meta']['children'], { 'count': 0, 'listing_url': 'http://localhost/admin/api/main/pages/?child_of=16' }) # Check the parent field self.assertIn('parent', content['meta']) self.assertIsInstance(content['meta']['parent'], dict) self.assertEqual(set(content['meta']['parent'].keys()), {'id', 'meta', 'title'}) self.assertEqual(content['meta']['parent']['id'], 5) self.assertIsInstance(content['meta']['parent']['meta'], dict) self.assertEqual(set(content['meta']['parent']['meta'].keys()), {'type', 'detail_url', 'html_url'}) self.assertEqual(content['meta']['parent']['meta']['type'], 'demosite.BlogIndexPage') self.assertEqual(content['meta']['parent']['meta']['detail_url'], 'http://localhost/admin/api/main/pages/5/') self.assertEqual(content['meta']['parent']['meta']['html_url'], 'http://localhost/blog-index/') # Check that the custom fields are included self.assertIn('date', content) self.assertIn('body', content) self.assertIn('tags', content) self.assertIn('feed_image', content) self.assertIn('related_links', content) self.assertIn('carousel_items', content) # Check that the date was serialised properly self.assertEqual(content['date'], '2013-12-02') # Check that the tags were serialised properly self.assertEqual(content['tags'], ['bird', 'wagtail']) # Check that the feed image was serialised properly self.assertIsInstance(content['feed_image'], dict) self.assertEqual(set(content['feed_image'].keys()), {'id', 'meta', 'title'}) self.assertEqual(content['feed_image']['id'], 7) self.assertIsInstance(content['feed_image']['meta'], dict) self.assertEqual(set(content['feed_image']['meta'].keys()), {'type', 'detail_url', 'download_url'}) self.assertEqual(content['feed_image']['meta']['type'], 'wagtailimages.Image') self.assertEqual(content['feed_image']['meta']['detail_url'], 'http://localhost/admin/api/main/images/7/') # Check that the child relations were serialised properly self.assertEqual(content['related_links'], []) for carousel_item in content['carousel_items']: self.assertEqual(set(carousel_item.keys()), {'id', 'meta', 'embed_url', 'link', 'caption', 'image'}) self.assertEqual(set(carousel_item['meta'].keys()), {'type'}) # Check the type info self.assertIsInstance(content['__types'], dict) self.assertEqual(set(content['__types'].keys()), { 'wagtailcore.Page', 'demosite.HomePage', 'demosite.BlogIndexPage', 'demosite.BlogEntryPageCarouselItem', 'demosite.BlogEntryPage', 'wagtailimages.Image' }) self.assertEqual(set(content['__types']['demosite.BlogIndexPage'].keys()), {'verbose_name', 'verbose_name_plural'}) self.assertEqual(content['__types']['demosite.BlogIndexPage']['verbose_name'], 'blog index page') self.assertEqual(content['__types']['demosite.BlogIndexPage']['verbose_name_plural'], 'blog index pages') # overridden from public API tests def test_meta_parent_id_doesnt_show_root_page(self): # Root page is visible in the admin API response = self.get_response(2) content = json.loads(response.content.decode('UTF-8')) self.assertIsNotNone(content['meta']['parent']) def test_field_ordering(self): # Need to override this as the admin API has a __types field response = self.get_response(16) # Will crash if the JSON is invalid content = json.loads(response.content.decode('UTF-8')) # Test field order content = json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(response.content.decode('UTF-8')) field_order = [ 'id', 'meta', 'title', 'admin_display_title', 'body', 'tags', 'date', 'feed_image', 'feed_image_thumbnail', 'carousel_items', 'related_links', '__types', ] self.assertEqual(list(content.keys()), field_order) def test_meta_status_draft(self): # Unpublish the page Page.objects.get(id=16).unpublish() response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) self.assertIn('status', content['meta']) self.assertEqual(content['meta']['status'], { 'status': 'draft', 'live': False, 'has_unpublished_changes': True }) def test_meta_status_live_draft(self): # Save revision without republish Page.objects.get(id=16).save_revision() response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) self.assertIn('status', content['meta']) self.assertEqual(content['meta']['status'], { 'status': 'live + draft', 'live': True, 'has_unpublished_changes': True }) def test_meta_status_scheduled(self): # Unpublish and save revision with go live date in the future Page.objects.get(id=16).unpublish() tomorrow = timezone.now() + datetime.timedelta(days=1) Page.objects.get(id=16).save_revision(approved_go_live_at=tomorrow) response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) self.assertIn('status', content['meta']) self.assertEqual(content['meta']['status'], { 'status': 'scheduled', 'live': False, 'has_unpublished_changes': True }) def test_meta_status_expired(self): # Unpublish and set expired flag Page.objects.get(id=16).unpublish() Page.objects.filter(id=16).update(expired=True) response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) self.assertIn('status', content['meta']) self.assertEqual(content['meta']['status'], { 'status': 'expired', 'live': False, 'has_unpublished_changes': True }) def test_meta_children_for_parent(self): # Homepage should have children response = self.get_response(2) content = json.loads(response.content.decode('UTF-8')) self.assertIn('children', content['meta']) self.assertEqual(content['meta']['children'], { 'count': 5, 'listing_url': 'http://localhost/admin/api/main/pages/?child_of=2' }) def test_meta_descendants(self): # Homepage should have children response = self.get_response(2) content = json.loads(response.content.decode('UTF-8')) self.assertIn('descendants', content['meta']) self.assertEqual(content['meta']['descendants'], { 'count': 18, 'listing_url': 'http://localhost/admin/api/main/pages/?descendant_of=2' }) def test_meta_ancestors(self): # Homepage should have children response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) self.assertIn('ancestors', content['meta']) self.assertIsInstance(content['meta']['ancestors'], list) self.assertEqual(len(content['meta']['ancestors']), 3) self.assertEqual(content['meta']['ancestors'][0].keys(), {'id', 'meta', 'title', 'admin_display_title'}) self.assertEqual(content['meta']['ancestors'][0]['title'], 'Root') self.assertEqual(content['meta']['ancestors'][1]['title'], 'Home page') self.assertEqual(content['meta']['ancestors'][2]['title'], 'Blog index') # FIELDS def test_remove_all_meta_fields(self): response = self.get_response(16, fields='-type,-detail_url,-slug,-first_published_at,-html_url,-descendants,-latest_revision_created_at,-children,-ancestors,-show_in_menus,-seo_title,-parent,-status,-search_description') content = json.loads(response.content.decode('UTF-8')) self.assertNotIn('meta', set(content.keys())) self.assertIn('id', set(content.keys())) def test_remove_all_fields(self): response = self.get_response(16, fields='_,id,type') content = json.loads(response.content.decode('UTF-8')) self.assertEqual(set(content.keys()), {'id', 'meta', '__types'}) self.assertEqual(set(content['meta'].keys()), {'type'}) def test_all_nested_fields(self): response = self.get_response(16, fields='feed_image(*)') content = json.loads(response.content.decode('UTF-8')) self.assertEqual(set(content['feed_image'].keys()), {'id', 'meta', 'title', 'width', 'height', 'thumbnail'}) def test_fields_foreign_key(self): response = self.get_response(16) content = json.loads(response.content.decode('UTF-8')) feed_image = content['feed_image'] self.assertIsInstance(feed_image, dict) self.assertEqual(set(feed_image.keys()), {'id', 'meta', 'title'}) self.assertIsInstance(feed_image['id'], int) self.assertIsInstance(feed_image['meta'], dict) self.assertEqual(set(feed_image['meta'].keys()), {'type', 'detail_url', 'download_url'}) self.assertEqual(feed_image['meta']['type'], 'wagtailimages.Image') self.assertEqual(feed_image['meta']['detail_url'], 'http://localhost/admin/api/main/images/%d/' % feed_image['id']) class TestAdminPageDetailWithStreamField(AdminAPITestCase): fixtures = ['test.json'] def setUp(self): super().setUp() self.homepage = Page.objects.get(url_path='/home/') def make_stream_page(self, body): stream_page = StreamPage( title='stream page', slug='stream-page', body=body ) return self.homepage.add_child(instance=stream_page) def test_can_fetch_streamfield_content(self): stream_page = self.make_stream_page('[{"type": "text", "value": "foo"}]') response_url = reverse('wagtailadmin_api:pages:detail', args=(stream_page.id, )) response = self.client.get(response_url) self.assertEqual(response.status_code, 200) self.assertEqual(response['content-type'], 'application/json') content = json.loads(response.content.decode('utf-8')) self.assertIn('id', content) self.assertEqual(content['id'], stream_page.id) self.assertIn('body', content) self.assertEqual(len(content['body']), 1) self.assertEqual(content['body'][0]['type'], 'text') self.assertEqual(content['body'][0]['value'], 'foo') self.assertTrue(content['body'][0]['id']) def test_image_block(self): stream_page = self.make_stream_page('[{"type": "image", "value": 1}]') response_url = reverse('wagtailadmin_api:pages:detail', args=(stream_page.id, )) response = self.client.get(response_url) content = json.loads(response.content.decode('utf-8')) # ForeignKeys in a StreamField shouldn't be translated into dictionary representation self.assertEqual(content['body'][0]['type'], 'image') self.assertEqual(content['body'][0]['value'], 1) class TestCustomAdminDisplayTitle(AdminAPITestCase): fixtures = ['test.json'] def setUp(self): super().setUp() self.event_page = Page.objects.get(url_path='/home/events/saint-patrick/') def test_custom_admin_display_title_shown_on_detail_page(self): api_url = reverse('wagtailadmin_api:pages:detail', args=(self.event_page.id, )) response = self.client.get(api_url) content = json.loads(response.content.decode('utf-8')) self.assertEqual(content['title'], "Saint Patrick") self.assertEqual(content['admin_display_title'], "Saint Patrick (single event)") def test_custom_admin_display_title_shown_on_listing(self): api_url = reverse('wagtailadmin_api:pages:listing') response = self.client.get(api_url) content = json.loads(response.content.decode('utf-8')) matching_items = [item for item in content['items'] if item['id'] == self.event_page.id] self.assertEqual(1, len(matching_items)) self.assertEqual(matching_items[0]['title'], "Saint Patrick") self.assertEqual(matching_items[0]['admin_display_title'], "Saint Patrick (single event)") # Overwrite imported test cases do Django doesn't run them TestPageDetail = None TestPageListing = None
bsd-3-clause
czechcamus/albert5-cms
private/frontend/components/views/boxGallery.php
781
<?php /* @var $gallery \common\models\Gallery */ /* @var $image string */ /* @var $align string */ use yii\helpers\Html; if ($gallery) { echo '<div class="col s12 m6 gallery-link ' . $align . '">'; echo '<div class="card">'; echo '<div class="card-content">'; echo '<span class="card-title"><i class="material-icons">photo_library</i> ' . Html::a($gallery->title, ['site/gallery', 'id' => $gallery->id, 'c' => 'article']) . '</span>'; echo Html::a($image, ['site/gallery', 'id' => $gallery->id, 'c' => 'article']); echo '</div>'; echo '<div class="card-action">'; echo Html::a(Yii::t('front', 'Skip to gallery'), ['site/gallery', 'id' => $gallery->id, 'c' => 'article'], [ 'class' => 'waves-effect waves-light btn' ]); echo '</div>'; echo '</div>'; echo '</div>'; }
bsd-3-clause
rimbalinux/LMD3
docutils/parsers/rst/languages/en.py
3283
# $Id: en.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ English-language mappings for language-dependent features of reStructuredText. """ __docformat__ = 'reStructuredText' directives = { # language-dependent: fixed 'attention': 'attention', 'caution': 'caution', 'danger': 'danger', 'error': 'error', 'hint': 'hint', 'important': 'important', 'note': 'note', 'tip': 'tip', 'warning': 'warning', 'admonition': 'admonition', 'sidebar': 'sidebar', 'topic': 'topic', 'line-block': 'line-block', 'parsed-literal': 'parsed-literal', 'rubric': 'rubric', 'epigraph': 'epigraph', 'highlights': 'highlights', 'pull-quote': 'pull-quote', 'compound': 'compound', 'container': 'container', #'questions': 'questions', 'table': 'table', 'csv-table': 'csv-table', 'list-table': 'list-table', #'qa': 'questions', #'faq': 'questions', 'meta': 'meta', #'imagemap': 'imagemap', 'image': 'image', 'figure': 'figure', 'include': 'include', 'raw': 'raw', 'replace': 'replace', 'unicode': 'unicode', 'date': 'date', 'class': 'class', 'role': 'role', 'default-role': 'default-role', 'title': 'title', 'contents': 'contents', 'sectnum': 'sectnum', 'section-numbering': 'sectnum', 'header': 'header', 'footer': 'footer', #'footnotes': 'footnotes', #'citations': 'citations', 'target-notes': 'target-notes', 'restructuredtext-test-directive': 'restructuredtext-test-directive'} """English name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'abbreviation': 'abbreviation', 'ab': 'abbreviation', 'acronym': 'acronym', 'ac': 'acronym', 'index': 'index', 'i': 'index', 'subscript': 'subscript', 'sub': 'subscript', 'superscript': 'superscript', 'sup': 'superscript', 'title-reference': 'title-reference', 'title': 'title-reference', 't': 'title-reference', 'pep-reference': 'pep-reference', 'pep': 'pep-reference', 'rfc-reference': 'rfc-reference', 'rfc': 'rfc-reference', 'emphasis': 'emphasis', 'strong': 'strong', 'literal': 'literal', 'named-reference': 'named-reference', 'anonymous-reference': 'anonymous-reference', 'footnote-reference': 'footnote-reference', 'citation-reference': 'citation-reference', 'substitution-reference': 'substitution-reference', 'target': 'target', 'uri-reference': 'uri-reference', 'uri': 'uri-reference', 'url': 'uri-reference', 'raw': 'raw',} """Mapping of English role names to canonical role names for interpreted text. """
bsd-3-clause
hefen1/chromium
chrome/browser/chrome_browser_main_win.cc
18646
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_browser_main_win.h" #include <windows.h> #include <shellapi.h> #include <algorithm> #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/i18n/rtl.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/scoped_native_library.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/win/metro.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "base/win/wrapped_window_proc.h" #include "chrome/browser/browser_util_win.h" #include "chrome/browser/chrome_elf_init_win.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/install_verification/win/install_verification.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_shortcut_manager.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/simple_message_box.h" #include "chrome/browser/ui/uninstall_browser_prompt.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_utility_messages.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/env_vars.h" #include "chrome/common/terminate_on_heap_corruption_experiment_win.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/shell_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/utility_process_host.h" #include "content/public/browser/utility_process_host_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/dwrite_font_platform_win.h" #include "content/public/common/main_function_params.h" #include "installer_util_strings/installer_util_strings.h" #include "ui/base/cursor/cursor_loader_win.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/base/ui_base_switches.h" #include "ui/base/win/message_box_win.h" #include "ui/gfx/platform_font_win.h" #include "ui/gfx/switches.h" #include "ui/gfx/win/direct_write.h" #include "ui/strings/grit/app_locale_settings.h" #if defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/google/did_run_updater_win.h" #endif namespace { typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)( const wchar_t* command_line, DWORD flags); void InitializeWindowProcExceptions() { // Get the breakpad pointer from chrome.exe base::win::WinProcExceptionFilter exception_filter = reinterpret_cast<base::win::WinProcExceptionFilter>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "CrashForException")); exception_filter = base::win::SetWinProcExceptionFilter(exception_filter); DCHECK(!exception_filter); } // gfx::Font callbacks void AdjustUIFont(LOGFONT* logfont) { l10n_util::AdjustUIFont(logfont); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } class TranslationDelegate : public installer::TranslationDelegate { public: virtual base::string16 GetLocalizedString(int installer_string_id) override; }; void ExecuteFontCacheBuildTask(const base::FilePath& path) { base::WeakPtr<content::UtilityProcessHost> utility_process_host( content::UtilityProcessHost::Create(NULL, NULL)->AsWeakPtr()); utility_process_host->DisableSandbox(); utility_process_host->Send( new ChromeUtilityHostMsg_BuildDirectWriteFontCache(path)); } } // namespace void ShowCloseBrowserFirstMessageBox() { int message_id = IDS_UNINSTALL_CLOSE_APP; if (base::win::GetVersion() >= base::win::VERSION_WIN8 && (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT)) { message_id = IDS_UNINSTALL_CLOSE_APP_IMMERSIVE; } chrome::ShowMessageBox(NULL, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), l10n_util::GetStringUTF16(message_id), chrome::MESSAGE_BOX_TYPE_WARNING); } int DoUninstallTasks(bool chrome_still_running) { // We want to show a warning to user (and exit) if Chrome is already running // *before* we show the uninstall confirmation dialog box. But while the // uninstall confirmation dialog is up, user might start Chrome, so we // check once again after user acknowledges Uninstall dialog. if (chrome_still_running) { ShowCloseBrowserFirstMessageBox(); return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE; } int result = chrome::ShowUninstallBrowserPrompt(); if (browser_util::IsBrowserAlreadyRunning()) { ShowCloseBrowserFirstMessageBox(); return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE; } if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) { // The following actions are just best effort. // TODO(gab): Look into removing this code which is now redundant with the // work done by setup.exe on uninstall. VLOG(1) << "Executing uninstall actions"; base::FilePath chrome_exe; if (PathService::Get(base::FILE_EXE, &chrome_exe)) { ShellUtil::ShortcutLocation user_shortcut_locations[] = { ShellUtil::SHORTCUT_LOCATION_DESKTOP, ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH, ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR, ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR, }; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); for (size_t i = 0; i < arraysize(user_shortcut_locations); ++i) { if (!ShellUtil::RemoveShortcuts(user_shortcut_locations[i], dist, ShellUtil::CURRENT_USER, chrome_exe)) { VLOG(1) << "Failed to delete shortcut at location " << user_shortcut_locations[i]; } } } else { NOTREACHED(); } } return result; } // ChromeBrowserMainPartsWin --------------------------------------------------- ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin( const content::MainFunctionParams& parameters) : ChromeBrowserMainParts(parameters) { if (base::win::IsMetroProcess()) { typedef const wchar_t* (*GetMetroSwitches)(void); GetMetroSwitches metro_switches_proc = reinterpret_cast<GetMetroSwitches>( GetProcAddress(base::win::GetMetroModule(), "GetMetroCommandLineSwitches")); if (metro_switches_proc) { base::string16 metro_switches = (*metro_switches_proc)(); if (!metro_switches.empty()) { base::CommandLine extra_switches(base::CommandLine::NO_PROGRAM); extra_switches.ParseFromString(metro_switches); base::CommandLine::ForCurrentProcess()->AppendArguments(extra_switches, false); } } } } ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() { } void ChromeBrowserMainPartsWin::ToolkitInitialized() { ChromeBrowserMainParts::ToolkitInitialized(); gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont; gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize; ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll); } void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() { // installer_util references strings that are normally compiled into // setup.exe. In Chrome, these strings are in the locale files. SetupInstallerUtilStrings(); ChromeBrowserMainParts::PreMainMessageLoopStart(); if (!parameters().ui_task) { // Make sure that we know how to handle exceptions from the message loop. InitializeWindowProcExceptions(); } IncognitoModePrefs::InitializePlatformParentalControls(); } int ChromeBrowserMainPartsWin::PreCreateThreads() { int rv = ChromeBrowserMainParts::PreCreateThreads(); // TODO(viettrungluu): why don't we run this earlier? if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) && base::win::GetVersion() < base::win::VERSION_XP) { chrome::ShowMessageBox(NULL, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP), chrome::MESSAGE_BOX_TYPE_WARNING); } return rv; } void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() { ui::MessageBox(NULL, base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage), base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle), MB_OK | MB_ICONERROR | MB_TOPMOST); } void ChromeBrowserMainPartsWin::PostProfileInit() { ChromeBrowserMainParts::PostProfileInit(); // DirectWrite support is mainly available Windows 7 and up. if (gfx::win::ShouldUseDirectWrite()) { base::FilePath path( profile()->GetPath().AppendASCII(content::kFontCacheSharedSectionName)); // This function will create a read only section if cache file exists // otherwise it will spawn utility process to build cache file, which will // be used during next browser start/postprofileinit. if (!content::LoadFontCache(path)) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(ExecuteFontCacheBuildTask, path)); } } } void ChromeBrowserMainPartsWin::PostBrowserStart() { ChromeBrowserMainParts::PostBrowserStart(); UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice()); // Set up a task to verify installed modules in the current process. Use a // delay to reduce the impact on startup time. content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI)->PostDelayedTask( FROM_HERE, base::Bind(&VerifyInstallation), base::TimeDelta::FromSeconds(45)); InitializeChromeElf(); // TODO(erikwright): Remove this and the implementation of the experiment by // September 2014. InitializeDisableTerminateOnHeapCorruptionExperiment(); #if defined(GOOGLE_CHROME_BUILD) did_run_updater_.reset(new DidRunUpdater); #endif } // static void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment( const base::CommandLine& parsed_command_line) { // Clear this var so child processes don't show the dialog by default. scoped_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(env_vars::kShowRestart); // For non-interactive tests we don't restart on crash. if (env->HasVar(env_vars::kHeadless)) return; // If the known command-line test options are used we don't create the // environment block which means we don't get the restart dialog. if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) || parsed_command_line.HasSwitch(switches::kNoErrorDialogs)) return; // The encoding we use for the info is "title|context|direction" where // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending // on the current locale. base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE)); dlg_strings.push_back('|'); base::string16 adjusted_string( l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT)); base::i18n::AdjustStringForLocaleDirection(&adjusted_string); dlg_strings.append(adjusted_string); dlg_strings.push_back('|'); dlg_strings.append(base::ASCIIToUTF16( base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale)); env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings)); } // static void ChromeBrowserMainPartsWin::RegisterApplicationRestart( const base::CommandLine& parsed_command_line) { DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA); base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll")); // Get the function pointer for RegisterApplicationRestart. RegisterApplicationRestartProc register_application_restart = reinterpret_cast<RegisterApplicationRestartProc>( library.GetFunctionPointer("RegisterApplicationRestart")); if (!register_application_restart) { LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll"; return; } // The Windows Restart Manager expects a string of command line flags only, // without the program. base::CommandLine command_line(base::CommandLine::NO_PROGRAM); command_line.AppendArguments(parsed_command_line, false); if (!command_line.HasSwitch(switches::kRestoreLastSession)) command_line.AppendSwitch(switches::kRestoreLastSession); // Restart Chrome if the computer is restarted as the result of an update. // This could be extended to handle crashes, hangs, and patches. HRESULT hr = register_application_restart( command_line.GetCommandLineString().c_str(), RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH); if (FAILED(hr)) { if (hr == E_INVALIDARG) { LOG(WARNING) << "Command line too long for RegisterApplicationRestart"; } else { NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr << ", command_line: " << command_line.GetCommandLineString(); } } } // static int ChromeBrowserMainPartsWin::HandleIconsCommands( const base::CommandLine& parsed_command_line) { if (parsed_command_line.HasSwitch(switches::kHideIcons)) { base::string16 cp_applet; base::win::Version version = base::win::GetVersion(); if (version >= base::win::VERSION_VISTA) { cp_applet.assign(L"Programs and Features"); // Windows Vista and later. } else if (version >= base::win::VERSION_XP) { cp_applet.assign(L"Add/Remove Programs"); // Windows XP. } else { return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported } const base::string16 msg = l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet); const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST; if (IDOK == ui::MessageBox(NULL, msg, caption, flags)) ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL); // Exit as we are not launching the browser. return content::RESULT_CODE_NORMAL_EXIT; } // We don't hide icons so we shouldn't do anything special to show them return chrome::RESULT_CODE_UNSUPPORTED_PARAM; } // static bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() { // TODO(tommi): Check if using the default distribution is always the right // thing to do. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); Version version; InstallUtil::GetChromeVersion(dist, true, &version); if (version.IsValid()) { base::FilePath exe_path; PathService::Get(base::DIR_EXE, &exe_path); std::wstring exe = exe_path.value(); base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist)); if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) { bool is_metro = base::win::IsMetroProcess(); if (!is_metro) { // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on // an invisible dialog. // TODO (gab): Get rid of this dialog altogether and auto-launch // system-level Chrome instead. const base::string16 text = l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT); const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST; ui::MessageBox(NULL, text, caption, flags); } base::CommandLine uninstall_cmd( InstallUtil::GetChromeUninstallCmd(false, dist->GetType())); if (!uninstall_cmd.GetProgram().empty()) { uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct); uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall); uninstall_cmd.AppendSwitch( installer::switches::kDoNotRemoveSharedItems); // Trigger Active Setup for the system-level Chrome to make sure // per-user shortcuts to the system-level Chrome are created. Skip this // if the system-level Chrome will undergo first run anyway, as Active // Setup is triggered on system-level Chrome's first run. // TODO(gab): Instead of having callers of Active Setup think about // other callers, have Active Setup itself register when it ran and // no-op otherwise (http://crbug.com/346843). if (!first_run::IsChromeFirstRun()) uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup); const base::FilePath setup_exe(uninstall_cmd.GetProgram()); const base::string16 params(uninstall_cmd.GetArgumentsString()); SHELLEXECUTEINFO sei = { sizeof(sei) }; sei.fMask = SEE_MASK_NOASYNC; sei.nShow = SW_SHOWNORMAL; sei.lpFile = setup_exe.value().c_str(); sei.lpParameters = params.c_str(); // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we // flip to the Desktop when launching. if (is_metro) sei.fMask |= SEE_MASK_FLAG_LOG_USAGE; if (!::ShellExecuteEx(&sei)) DPCHECK(false); } return true; } } return false; } base::string16 TranslationDelegate::GetLocalizedString( int installer_string_id) { int resource_id = 0; switch (installer_string_id) { // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in // the generated header installer_util_strings.h. #define HANDLE_STRING(base_id, chrome_id) \ case base_id: \ resource_id = chrome_id; \ break; DO_INSTALLER_STRING_MAPPING #undef HANDLE_STRING default: NOTREACHED(); } if (resource_id) return l10n_util::GetStringUTF16(resource_id); return base::string16(); } // static void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() { CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ()); installer::SetTranslationDelegate(&delegate); }
bsd-3-clause
dacoex/pvlib-python
pvlib/test/test_pvsystem.py
7258
import logging pvl_logger = logging.getLogger('pvlib') import inspect import os import datetime import numpy as np import pandas as pd from nose.tools import assert_equals, assert_almost_equals from pandas.util.testing import assert_series_equal, assert_frame_equal from . import incompatible_conda_linux_py3 from pvlib import tmy from pvlib import pvsystem from pvlib import clearsky from pvlib import irradiance from pvlib import atmosphere from pvlib import solarposition from pvlib.location import Location tus = Location(32.2, -111, 'US/Arizona', 700, 'Tucson') times = pd.date_range(start=datetime.datetime(2014,1,1), end=datetime.datetime(2014,1,2), freq='1Min') ephem_data = solarposition.get_solarposition(times, tus, method='pyephem') irrad_data = clearsky.ineichen(times, tus, linke_turbidity=3, solarposition_method='pyephem') aoi = irradiance.aoi(0, 0, ephem_data['apparent_zenith'], ephem_data['apparent_azimuth']) am = atmosphere.relativeairmass(ephem_data.apparent_zenith) meta = {'latitude': 37.8, 'longitude': -122.3, 'altitude': 10, 'Name': 'Oakland', 'State': 'CA', 'TZ': -8} pvlib_abspath = os.path.dirname(os.path.abspath(inspect.getfile(tmy))) tmy3_testfile = os.path.join(pvlib_abspath, 'data', '703165TY.csv') tmy2_testfile = os.path.join(pvlib_abspath, 'data', '12839.tm2') tmy3_data, tmy3_metadata = tmy.readtmy3(tmy3_testfile) tmy2_data, tmy2_metadata = tmy.readtmy2(tmy2_testfile) def test_systemdef_tmy3(): expected = {'tz': -9.0, 'albedo': 0.1, 'altitude': 7.0, 'latitude': 55.317, 'longitude': -160.517, 'name': '"SAND POINT"', 'parallel_modules': 5, 'series_modules': 5, 'surface_azimuth': 0, 'surface_tilt': 0} assert_equals(expected, pvsystem.systemdef(tmy3_metadata, 0, 0, .1, 5, 5)) def test_systemdef_tmy2(): expected = {'tz': -5, 'albedo': 0.1, 'altitude': 2.0, 'latitude': 25.8, 'longitude': -80.26666666666667, 'name': 'MIAMI', 'parallel_modules': 5, 'series_modules': 5, 'surface_azimuth': 0, 'surface_tilt': 0} assert_equals(expected, pvsystem.systemdef(tmy2_metadata, 0, 0, .1, 5, 5)) def test_systemdef_dict(): expected = {'tz': -8, ## Note that TZ is float, but Location sets tz as string 'albedo': 0.1, 'altitude': 10, 'latitude': 37.8, 'longitude': -122.3, 'name': 'Oakland', 'parallel_modules': 5, 'series_modules': 5, 'surface_azimuth': 0, 'surface_tilt': 5} assert_equals(expected, pvsystem.systemdef(meta, 5, 0, .1, 5, 5)) def test_ashraeiam(): thetas = pd.Series(np.linspace(-180,180,361)) iam = pvsystem.ashraeiam(.05, thetas) def test_physicaliam(): thetas = pd.Series(np.linspace(-180,180,361)) iam = pvsystem.physicaliam(4, 0.002, 1.526, thetas) # if this completes successfully we'll be able to do more tests below. sam_data = {} def test_retrieve_sam_network(): sam_data['cecmod'] = pvsystem.retrieve_sam('cecmod') sam_data['sandiamod'] = pvsystem.retrieve_sam('sandiamod') sam_data['cecinverter'] = pvsystem.retrieve_sam('cecinverter') def test_sapm(): modules = sam_data['sandiamod'] module = modules.Canadian_Solar_CS5P_220M___2009_ sapm = pvsystem.sapm(module, irrad_data['dni'], irrad_data['dhi'], 25, am, aoi) sapm = pvsystem.sapm(module.to_dict(), irrad_data['dni'], irrad_data['dhi'], 25, am, aoi) def test_calcparams_desoto(): cecmodule = sam_data['cecmod'].Example_Module pvsystem.calcparams_desoto(irrad_data['ghi'], temp_cell=25, alpha_isc=cecmodule['alpha_sc'], module_parameters=cecmodule, EgRef=1.121, dEgdT=-0.0002677) @incompatible_conda_linux_py3 def test_i_from_v(): output = pvsystem.i_from_v(20, .1, .5, 40, 6e-7, 7) assert_almost_equals(-299.746389916, output, 5) def test_singlediode_series(): cecmodule = sam_data['cecmod'].Example_Module IL, I0, Rs, Rsh, nNsVth = pvsystem.calcparams_desoto( irrad_data['ghi'], temp_cell=25, alpha_isc=cecmodule['alpha_sc'], module_parameters=cecmodule, EgRef=1.121, dEgdT=-0.0002677) out = pvsystem.singlediode(cecmodule, IL, I0, Rs, Rsh, nNsVth) assert isinstance(out, pd.DataFrame) @incompatible_conda_linux_py3 def test_singlediode_series(): cecmodule = sam_data['cecmod'].Example_Module out = pvsystem.singlediode(cecmodule, 7, 6e-7, .1, 20, .5) expected = {'i_xx': 4.2549732697234193, 'i_mp': 6.1390251797935704, 'v_oc': 8.1147298764528042, 'p_mp': 38.194165464983037, 'i_x': 6.7556075876880621, 'i_sc': 6.9646747613963198, 'v_mp': 6.221535886625464} assert isinstance(out, dict) for k, v in out.items(): assert_almost_equals(expected[k], v, 5) def test_sapm_celltemp(): default = pvsystem.sapm_celltemp(900, 5, 20) assert_almost_equals(43.509, default.ix[0, 'temp_cell'], 3) assert_almost_equals(40.809, default.ix[0, 'temp_module'], 3) assert_frame_equal(default, pvsystem.sapm_celltemp(900, 5, 20, [-3.47, -.0594, 3])) def test_sapm_celltemp_with_index(): times = pd.DatetimeIndex(start='2015-01-01', end='2015-01-02', freq='12H') temps = pd.Series([0, 10, 5], index=times) irrads = pd.Series([0, 500, 0], index=times) winds = pd.Series([10, 5, 0], index=times) pvtemps = pvsystem.sapm_celltemp(irrads, winds, temps) expected = pd.DataFrame({'temp_cell':[0., 23.06066166, 5.], 'temp_module':[0., 21.56066166, 5.]}, index=times) assert_frame_equal(expected, pvtemps) def test_snlinverter(): inverters = sam_data['cecinverter'] testinv = 'ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_' vdcs = pd.Series(np.linspace(0,50,3)) idcs = pd.Series(np.linspace(0,11,3)) pdcs = idcs * vdcs pacs = pvsystem.snlinverter(inverters[testinv], vdcs, pdcs) assert_series_equal(pacs, pd.Series([-0.020000, 132.004308, 250.000000])) def test_snlinverter_float(): inverters = sam_data['cecinverter'] testinv = 'ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_' vdcs = 25. idcs = 5.5 pdcs = idcs * vdcs pacs = pvsystem.snlinverter(inverters[testinv], vdcs, pdcs) assert_almost_equals(pacs, 132.004278, 5)
bsd-3-clause
hgl888/chromium-efl
ewk/unittest/utc_blink_ewk_context_web_indexed_database_delete_all_func.cpp
2565
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_context_web_indexed_database_delete_all : public utc_blink_ewk_base { protected: utc_blink_ewk_context_web_indexed_database_delete_all() : utc_blink_ewk_base() { } static void title_changed(void* data, Evas_Object* webview, void* event) { static_cast<utc_blink_ewk_context_web_indexed_database_delete_all*>(data)->title = ewk_view_title_get(webview); static_cast<utc_blink_ewk_context_web_indexed_database_delete_all*>(data)->EventLoopStop(Success); } virtual void LoadFinished(Evas_Object* webview) { evas_object_smart_callback_add(GetEwkWebView(), "title,changed", title_changed, this); } virtual void PostSetUp() { ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl("/ewk_context_web_indexed_database/CreateDB.html").c_str())); } virtual void PreTearDown() { evas_object_smart_callback_del(GetEwkWebView(), "title,changed", title_changed); } protected: std::string title; }; /** * @brief Tests if indexed database is deleted when initiated properly. */ TEST_F(utc_blink_ewk_context_web_indexed_database_delete_all, POS_TEST) { ASSERT_EQ(utc_blink_ewk_base::Success, EventLoopStart()); ASSERT_STREQ("success", utc_blink_ewk_context_web_indexed_database_delete_all::title.c_str()); ASSERT_EQ(EINA_TRUE, ewk_context_web_indexed_database_delete_all(ewk_view_context_get(GetEwkWebView()))); ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl("/ewk_context_web_indexed_database/DBExists.html").c_str())); ASSERT_EQ(utc_blink_ewk_base::Success, EventLoopStart()); EXPECT_STREQ("error", utc_blink_ewk_context_web_indexed_database_delete_all::title.c_str()); } /** * @brief Tests if indexed db is not deleted when initiated with NULL context. */ TEST_F(utc_blink_ewk_context_web_indexed_database_delete_all, NEG_TEST) { ASSERT_EQ(utc_blink_ewk_base::Success, EventLoopStart()); ASSERT_STREQ("success", utc_blink_ewk_context_web_indexed_database_delete_all::title.c_str()); ASSERT_NE(EINA_TRUE, ewk_context_web_indexed_database_delete_all(0)); ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), GetResourceUrl("/ewk_context_web_indexed_database/DBExists.html").c_str())); ASSERT_EQ(utc_blink_ewk_base::Success, EventLoopStart()); EXPECT_STRNE("error", utc_blink_ewk_context_web_indexed_database_delete_all::title.c_str()); }
bsd-3-clause
carnby/datagramas
datagramas/visualizations/circlepack/template.js
1933
var diameter = Math.min(_vis_width, _vis_height); var pack = d3.layout.pack() .size([diameter - 4, diameter - 4]) .value(function(d) { return datagramas.get(d, _node_value); }) .children(function (d) { return datagramas.get(d, _node_children); }); var root = pack.nodes(_data_tree); console.log('root', root); _node_color_update_scale_func(root.filter(function(d) { return datagramas.get(d, _node_value) > 0; })); var node = container.selectAll('.node') .data(root); var node_background = function (d) { if (_color_level >= 0 && _color_level !== d.depth) { return 'none'; } if (datagramas.get(d, _node_children) !== null) { return 'none'; } return _node_color(d); }; var node_text = function (d) { if (_label_leaves_only && datagramas.get(d, _node_children) != null) { return null; } return _node_label != null ? datagramas.get(d, _node_label) : null; }; node.enter().append('g').each(function(d, i) { var self = d3.select(this); self.append('circle'); self.append('text').attr('text-anchor', 'middle'); dispatch.node_selection_enter.apply(this, arguments); }); node.attr('class', function(d) { return d.children ? 'node node-depth-' + d.depth : 'node-leaf node node-depth-' + d.depth; }) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; }); node.selectAll('circle') .attr({ 'r': function(d) { return d.r - _node_padding; }, 'fill-opacity': _node_opacity, 'fill': node_background, 'stroke-width': _node_border, 'stroke': _node_border_color }).on('click', function(d, i) { console.log('click!', d, i, this); dispatch.node_click.apply(this, arguments); }); node.selectAll('text') .text(node_text); node.exit().each(function(d, i) { dispatch.node_selection_exit.apply(this, arguments); }) .remove();
bsd-3-clause
pizzathief/scipy
setup.py
21070
#!/usr/bin/env python """SciPy: Scientific Library for Python SciPy (pronounced "Sigh Pie") is open-source software for mathematics, science, and engineering. The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array manipulation. The SciPy library is built to work with NumPy arrays, and provides many user-friendly and efficient numerical routines such as routines for numerical integration and optimization. Together, they run on all popular operating systems, are quick to install, and are free of charge. NumPy and SciPy are easy to use, but powerful enough to be depended upon by some of the world's leading scientists and engineers. If you need to manipulate numbers on a computer and display or publish the results, give SciPy a try! """ DOCLINES = (__doc__ or '').split("\n") import os import sys import subprocess import textwrap import warnings import sysconfig from distutils.version import LooseVersion if sys.version_info[:2] < (3, 6): raise RuntimeError("Python version >= 3.6 required.") import builtins CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Science/Research Intended Audience :: Developers License :: OSI Approved :: BSD License Programming Language :: C Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Topic :: Software Development Topic :: Scientific/Engineering Operating System :: Microsoft :: Windows Operating System :: POSIX Operating System :: Unix Operating System :: MacOS """ MAJOR = 1 MINOR = 6 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the git revision as a string def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "Unknown" return GIT_REVISION # BEFORE importing setuptools, remove MANIFEST. Otherwise it may not be # properly updated when the contents of directories change (true for distutils, # not sure about setuptools). if os.path.exists('MANIFEST'): os.remove('MANIFEST') # This is a bit hackish: we are setting a global variable so that the main # scipy __init__ can detect if it is being loaded by the setup routine, to # avoid attempting to load components that aren't built yet. While ugly, it's # a lot more robust than what was previously being used. builtins.__SCIPY_SETUP__ = True def get_version_info(): # Adding the git rev number needs to be done inside # write_version_py(), otherwise the import of scipy.version messes # up the build under Python 3. FULLVERSION = VERSION if os.path.exists('.git'): GIT_REVISION = git_version() elif os.path.exists('scipy/version.py'): # must be a source distribution, use existing version file # load it as a separate module to not load scipy/__init__.py import runpy ns = runpy.run_path('scipy/version.py') GIT_REVISION = ns['git_revision'] else: GIT_REVISION = "Unknown" if not ISRELEASED: FULLVERSION += '.dev0+' + GIT_REVISION[:7] return FULLVERSION, GIT_REVISION def write_version_py(filename='scipy/version.py'): cnt = """ # THIS FILE IS GENERATED FROM SCIPY SETUP.PY short_version = '%(version)s' version = '%(version)s' full_version = '%(full_version)s' git_revision = '%(git_revision)s' release = %(isrelease)s if not release: version = full_version """ FULLVERSION, GIT_REVISION = get_version_info() a = open(filename, 'w') try: a.write(cnt % {'version': VERSION, 'full_version': FULLVERSION, 'git_revision': GIT_REVISION, 'isrelease': str(ISRELEASED)}) finally: a.close() try: from sphinx.setup_command import BuildDoc HAVE_SPHINX = True except Exception: HAVE_SPHINX = False if HAVE_SPHINX: class ScipyBuildDoc(BuildDoc): """Run in-place build before Sphinx doc build""" def run(self): ret = subprocess.call([sys.executable, sys.argv[0], 'build_ext', '-i']) if ret != 0: raise RuntimeError("Building Scipy failed!") BuildDoc.run(self) def check_submodules(): """ verify that the submodules are checked out and clean use `git submodule update --init`; on failure """ if not os.path.exists('.git'): return with open('.gitmodules') as f: for l in f: if 'path' in l: p = l.split('=')[-1].strip() if not os.path.exists(p): raise ValueError('Submodule %s missing' % p) proc = subprocess.Popen(['git', 'submodule', 'status'], stdout=subprocess.PIPE) status, _ = proc.communicate() status = status.decode("ascii", "replace") for line in status.splitlines(): if line.startswith('-') or line.startswith('+'): raise ValueError('Submodule not clean: %s' % line) class concat_license_files(): """Merge LICENSE.txt and LICENSES_bundled.txt for sdist creation Done this way to keep LICENSE.txt in repo as exact BSD 3-clause (see NumPy gh-13447). This makes GitHub state correctly how SciPy is licensed. """ def __init__(self): self.f1 = 'LICENSE.txt' self.f2 = 'LICENSES_bundled.txt' def __enter__(self): """Concatenate files and remove LICENSES_bundled.txt""" with open(self.f1, 'r') as f1: self.bsd_text = f1.read() with open(self.f1, 'a') as f1: with open(self.f2, 'r') as f2: self.bundled_text = f2.read() f1.write('\n\n') f1.write(self.bundled_text) def __exit__(self, exception_type, exception_value, traceback): """Restore content of both files""" with open(self.f1, 'w') as f: f.write(self.bsd_text) from distutils.command.sdist import sdist class sdist_checked(sdist): """ check submodules on sdist to prevent incomplete tarballs """ def run(self): check_submodules() with concat_license_files(): sdist.run(self) def get_build_ext_override(): """ Custom build_ext command to tweak extension building. """ from numpy.distutils.command.build_ext import build_ext as old_build_ext class build_ext(old_build_ext): def finalize_options(self): super().finalize_options() # Disable distutils parallel build, due to race conditions # in numpy.distutils (Numpy issue gh-15957) if self.parallel: print("NOTE: -j build option not supportd. Set NPY_NUM_BUILD_JOBS=4 " "for parallel build.") self.parallel = None def build_extension(self, ext): # When compiling with GNU compilers, use a version script to # hide symbols during linking. if self.__is_using_gnu_linker(ext): export_symbols = self.get_export_symbols(ext) text = '{global: %s; local: *; };' % (';'.join(export_symbols),) script_fn = os.path.join(self.build_temp, 'link-version-{}.map'.format(ext.name)) with open(script_fn, 'w') as f: f.write(text) # line below fixes gh-8680 ext.extra_link_args = [arg for arg in ext.extra_link_args if not "version-script" in arg] ext.extra_link_args.append('-Wl,--version-script=' + script_fn) # Allow late configuration hooks = getattr(ext, '_pre_build_hook', ()) _run_pre_build_hooks(hooks, (self, ext)) old_build_ext.build_extension(self, ext) def __is_using_gnu_linker(self, ext): if not sys.platform.startswith('linux'): return False # Fortran compilation with gfortran uses it also for # linking. For the C compiler, we detect gcc in a similar # way as distutils does it in # UnixCCompiler.runtime_library_dir_option if ext.language == 'f90': is_gcc = (self._f90_compiler.compiler_type in ('gnu', 'gnu95')) elif ext.language == 'f77': is_gcc = (self._f77_compiler.compiler_type in ('gnu', 'gnu95')) else: is_gcc = False if self.compiler.compiler_type == 'unix': cc = sysconfig.get_config_var("CC") if not cc: cc = "" compiler_name = os.path.basename(cc.split(" ")[0]) is_gcc = "gcc" in compiler_name or "g++" in compiler_name return is_gcc and sysconfig.get_config_var('GNULD') == 'yes' return build_ext def get_build_clib_override(): """ Custom build_clib command to tweak library building. """ from numpy.distutils.command.build_clib import build_clib as old_build_clib class build_clib(old_build_clib): def finalize_options(self): super().finalize_options() # Disable parallelization (see build_ext above) self.parallel = None def build_a_library(self, build_info, lib_name, libraries): # Allow late configuration hooks = build_info.get('_pre_build_hook', ()) _run_pre_build_hooks(hooks, (self, build_info)) old_build_clib.build_a_library(self, build_info, lib_name, libraries) return build_clib def _run_pre_build_hooks(hooks, args): """Call a sequence of pre-build hooks, if any""" if hooks is None: hooks = () elif not hasattr(hooks, '__iter__'): hooks = (hooks,) for hook in hooks: hook(*args) def generate_cython(): cwd = os.path.abspath(os.path.dirname(__file__)) print("Cythonizing sources") p = subprocess.call([sys.executable, os.path.join(cwd, 'tools', 'cythonize.py'), 'scipy'], cwd=cwd) if p != 0: # Could be due to a too old pip version and build isolation, check that try: # Note, pip may not be installed or not have been used import pip if LooseVersion(pip.__version__) < LooseVersion('18.0.0'): raise RuntimeError("Cython not found or too old. Possibly due " "to `pip` being too old, found version {}, " "needed is >= 18.0.0.".format( pip.__version__)) else: raise RuntimeError("Running cythonize failed!") except ImportError: raise RuntimeError("Running cythonize failed!") def parse_setuppy_commands(): """Check the commands and respond appropriately. Disable broken commands. Return a boolean value for whether or not to run the build or not (avoid parsing Cython and template files if False). """ args = sys.argv[1:] if not args: # User forgot to give an argument probably, let setuptools handle that. return True info_commands = ['--help-commands', '--name', '--version', '-V', '--fullname', '--author', '--author-email', '--maintainer', '--maintainer-email', '--contact', '--contact-email', '--url', '--license', '--description', '--long-description', '--platforms', '--classifiers', '--keywords', '--provides', '--requires', '--obsoletes'] for command in info_commands: if command in args: return False # Note that 'alias', 'saveopts' and 'setopt' commands also seem to work # fine as they are, but are usually used together with one of the commands # below and not standalone. Hence they're not added to good_commands. good_commands = ('develop', 'sdist', 'build', 'build_ext', 'build_py', 'build_clib', 'build_scripts', 'bdist_wheel', 'bdist_rpm', 'bdist_wininst', 'bdist_msi', 'bdist_mpkg', 'build_sphinx') for command in good_commands: if command in args: return True # The following commands are supported, but we need to show more # useful messages to the user if 'install' in args: print(textwrap.dedent(""" Note: if you need reliable uninstall behavior, then install with pip instead of using `setup.py install`: - `pip install .` (from a git repo or downloaded source release) - `pip install scipy` (last SciPy release on PyPI) """)) return True if '--help' in args or '-h' in sys.argv[1]: print(textwrap.dedent(""" SciPy-specific help ------------------- To install SciPy from here with reliable uninstall, we recommend that you use `pip install .`. To install the latest SciPy release from PyPI, use `pip install scipy`. For help with build/installation issues, please ask on the scipy-user mailing list. If you are sure that you have run into a bug, please report it at https://github.com/scipy/scipy/issues. Setuptools commands help ------------------------ """)) return False # The following commands aren't supported. They can only be executed when # the user explicitly adds a --force command-line argument. bad_commands = dict( test=""" `setup.py test` is not supported. Use one of the following instead: - `python runtests.py` (to build and test) - `python runtests.py --no-build` (to test installed scipy) - `>>> scipy.test()` (run tests for installed scipy from within an interpreter) """, upload=""" `setup.py upload` is not supported, because it's insecure. Instead, build what you want to upload and upload those files with `twine upload -s <filenames>` instead. """, upload_docs="`setup.py upload_docs` is not supported", easy_install="`setup.py easy_install` is not supported", clean=""" `setup.py clean` is not supported, use one of the following instead: - `git clean -xdf` (cleans all files) - `git clean -Xdf` (cleans all versioned files, doesn't touch files that aren't checked into the git repo) """, check="`setup.py check` is not supported", register="`setup.py register` is not supported", bdist_dumb="`setup.py bdist_dumb` is not supported", bdist="`setup.py bdist` is not supported", flake8="`setup.py flake8` is not supported, use flake8 standalone", ) bad_commands['nosetests'] = bad_commands['test'] for command in ('upload_docs', 'easy_install', 'bdist', 'bdist_dumb', 'register', 'check', 'install_data', 'install_headers', 'install_lib', 'install_scripts', ): bad_commands[command] = "`setup.py %s` is not supported" % command for command in bad_commands.keys(): if command in args: print(textwrap.dedent(bad_commands[command]) + "\nAdd `--force` to your command to use it anyway if you " "must (unsupported).\n") sys.exit(1) # Commands that do more than print info, but also don't need Cython and # template parsing. other_commands = ['egg_info', 'install_egg_info', 'rotate'] for command in other_commands: if command in args: return False # If we got here, we didn't detect what setup.py command was given warnings.warn("Unrecognized setuptools command ('{}'), proceeding with " "generating Cython sources and expanding templates".format( ' '.join(sys.argv[1:]))) return True def configuration(parent_package='', top_path=None): from scipy._build_utils.system_info import get_info, NotFoundError from numpy.distutils.misc_util import Configuration lapack_opt = get_info('lapack_opt') if not lapack_opt: msg = 'No lapack/blas resources found.' if sys.platform == "darwin": msg = ('No lapack/blas resources found. ' 'Note: Accelerate is no longer supported.') raise NotFoundError(msg) config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('scipy') config.add_data_files(('scipy', '*.txt')) config.get_version('scipy/version.py') return config def setup_package(): # Rewrite the version file every time write_version_py() cmdclass = {'sdist': sdist_checked} if HAVE_SPHINX: cmdclass['build_sphinx'] = ScipyBuildDoc # Figure out whether to add ``*_requires = ['numpy']``. # We don't want to do that unconditionally, because we risk updating # an installed numpy which fails too often. Just if it's not installed, we # may give it a try. See gh-3379. try: import numpy except ImportError: # We do not have numpy installed build_requires = ['numpy>=1.14.5'] else: # If we're building a wheel, assume there already exist numpy wheels # for this platform, so it is safe to add numpy to build requirements. # See gh-5184. build_requires = (['numpy>=1.14.5'] if 'bdist_wheel' in sys.argv[1:] else []) install_requires = build_requires setup_requires = build_requires + ['pybind11>=2.4.3'] metadata = dict( name='scipy', maintainer="SciPy Developers", maintainer_email="scipy-dev@python.org", description=DOCLINES[0], long_description="\n".join(DOCLINES[2:]), url="https://www.scipy.org", download_url="https://github.com/scipy/scipy/releases", project_urls={ "Bug Tracker": "https://github.com/scipy/scipy/issues", "Documentation": "https://docs.scipy.org/doc/scipy/reference/", "Source Code": "https://github.com/scipy/scipy", }, license='BSD', cmdclass=cmdclass, classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], test_suite='nose.collector', setup_requires=setup_requires, install_requires=install_requires, python_requires='>=3.6', ) if "--force" in sys.argv: run_build = True sys.argv.remove('--force') else: # Raise errors for unsupported commands, improve help output, etc. run_build = parse_setuppy_commands() # Disable OSX Accelerate, it has too old LAPACK os.environ['ACCELERATE'] = 'None' # This import is here because it needs to be done before importing setup() # from numpy.distutils, but after the MANIFEST removing and sdist import # higher up in this file. from setuptools import setup if run_build: from numpy.distutils.core import setup # Customize extension building cmdclass['build_ext'] = get_build_ext_override() cmdclass['build_clib'] = get_build_clib_override() cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(cwd, 'PKG-INFO')): # Generate Cython sources, unless building from source release generate_cython() metadata['configuration'] = configuration else: # Don't import numpy here - non-build actions are required to succeed # without NumPy for example when pip is used to install Scipy when # NumPy is not yet present in the system. # Version number is added to metadata inside configuration() if build # is run. metadata['version'] = get_version_info()[0] setup(**metadata) if __name__ == '__main__': setup_package()
bsd-3-clause
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/words/protocols/jabber/client.py
12885
# -*- test-case-name: twisted.words.test.test_jabberclient -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.words.xish import domish, xpath, utility from twisted.words.protocols.jabber import xmlstream, sasl, error from twisted.words.protocols.jabber.jid import JID NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams' NS_XMPP_BIND = 'urn:ietf:params:xml:ns:xmpp-bind' NS_XMPP_SESSION = 'urn:ietf:params:xml:ns:xmpp-session' NS_IQ_AUTH_FEATURE = 'http://jabber.org/features/iq-auth' DigestAuthQry = xpath.internQuery("/iq/query/digest") PlaintextAuthQry = xpath.internQuery("/iq/query/password") def basicClientFactory(jid, secret): a = BasicAuthenticator(jid, secret) return xmlstream.XmlStreamFactory(a) class IQ(domish.Element): """ Wrapper for a Info/Query packet. This provides the necessary functionality to send IQs and get notified when a result comes back. It's a subclass from L{domish.Element}, so you can use the standard DOM manipulation calls to add data to the outbound request. @type callbacks: L{utility.CallbackList} @cvar callbacks: Callback list to be notified when response comes back """ def __init__(self, xmlstream, type = "set"): """ @type xmlstream: L{xmlstream.XmlStream} @param xmlstream: XmlStream to use for transmission of this IQ @type type: C{str} @param type: IQ type identifier ('get' or 'set') """ domish.Element.__init__(self, ("jabber:client", "iq")) self.addUniqueId() self["type"] = type self._xmlstream = xmlstream self.callbacks = utility.CallbackList() def addCallback(self, fn, *args, **kwargs): """ Register a callback for notification when the IQ result is available. """ self.callbacks.addCallback(True, fn, *args, **kwargs) def send(self, to = None): """ Call this method to send this IQ request via the associated XmlStream. @param to: Jabber ID of the entity to send the request to @type to: C{str} @returns: Callback list for this IQ. Any callbacks added to this list will be fired when the result comes back. """ if to != None: self["to"] = to self._xmlstream.addOnetimeObserver("/iq[@id='%s']" % self["id"], \ self._resultEvent) self._xmlstream.send(self) def _resultEvent(self, iq): self.callbacks.callback(iq) self.callbacks = None class IQAuthInitializer(object): """ Non-SASL Authentication initializer for the initiating entity. This protocol is defined in U{JEP-0078<http://www.jabber.org/jeps/jep-0078.html>} and mainly serves for compatibility with pre-XMPP-1.0 server implementations. """ INVALID_USER_EVENT = "//event/client/basicauth/invaliduser" AUTH_FAILED_EVENT = "//event/client/basicauth/authfailed" def __init__(self, xs): self.xmlstream = xs def initialize(self): # Send request for auth fields iq = xmlstream.IQ(self.xmlstream, "get") iq.addElement(("jabber:iq:auth", "query")) jid = self.xmlstream.authenticator.jid iq.query.addElement("username", content = jid.user) d = iq.send() d.addCallbacks(self._cbAuthQuery, self._ebAuthQuery) return d def _cbAuthQuery(self, iq): jid = self.xmlstream.authenticator.jid password = self.xmlstream.authenticator.password # Construct auth request reply = xmlstream.IQ(self.xmlstream, "set") reply.addElement(("jabber:iq:auth", "query")) reply.query.addElement("username", content = jid.user) reply.query.addElement("resource", content = jid.resource) # Prefer digest over plaintext if DigestAuthQry.matches(iq): digest = xmlstream.hashPassword(self.xmlstream.sid, unicode(password)) reply.query.addElement("digest", content = digest) else: reply.query.addElement("password", content = password) d = reply.send() d.addCallbacks(self._cbAuth, self._ebAuth) return d def _ebAuthQuery(self, failure): failure.trap(error.StanzaError) e = failure.value if e.condition == 'not-authorized': self.xmlstream.dispatch(e.stanza, self.INVALID_USER_EVENT) else: self.xmlstream.dispatch(e.stanza, self.AUTH_FAILED_EVENT) return failure def _cbAuth(self, iq): pass def _ebAuth(self, failure): failure.trap(error.StanzaError) self.xmlstream.dispatch(failure.value.stanza, self.AUTH_FAILED_EVENT) return failure class BasicAuthenticator(xmlstream.ConnectAuthenticator): """ Authenticates an XmlStream against a Jabber server as a Client. This only implements non-SASL authentication, per U{JEP-0078<http://www.jabber.org/jeps/jep-0078.html>}. Additionally, this authenticator provides the ability to perform inline registration, per U{JEP-0077<http://www.jabber.org/jeps/jep-0077.html>}. Under normal circumstances, the BasicAuthenticator generates the L{xmlstream.STREAM_AUTHD_EVENT} once the stream has authenticated. However, it can also generate other events, such as: - L{INVALID_USER_EVENT} : Authentication failed, due to invalid username - L{AUTH_FAILED_EVENT} : Authentication failed, due to invalid password - L{REGISTER_FAILED_EVENT} : Registration failed If authentication fails for any reason, you can attempt to register by calling the L{registerAccount} method. If the registration succeeds, a L{xmlstream.STREAM_AUTHD_EVENT} will be fired. Otherwise, one of the above errors will be generated (again). """ namespace = "jabber:client" INVALID_USER_EVENT = IQAuthInitializer.INVALID_USER_EVENT AUTH_FAILED_EVENT = IQAuthInitializer.AUTH_FAILED_EVENT REGISTER_FAILED_EVENT = "//event/client/basicauth/registerfailed" def __init__(self, jid, password): xmlstream.ConnectAuthenticator.__init__(self, jid.host) self.jid = jid self.password = password def associateWithStream(self, xs): xs.version = (0, 0) xmlstream.ConnectAuthenticator.associateWithStream(self, xs) inits = [ (xmlstream.TLSInitiatingInitializer, False), (IQAuthInitializer, True), ] for initClass, required in inits: init = initClass(xs) init.required = required xs.initializers.append(init) # TODO: move registration into an Initializer? def registerAccount(self, username = None, password = None): if username: self.jid.user = username if password: self.password = password iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:register", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("password", content = self.password) iq.addCallback(self._registerResultEvent) iq.send() def _registerResultEvent(self, iq): if iq["type"] == "result": # Registration succeeded -- go ahead and auth self.streamStarted() else: # Registration failed self.xmlstream.dispatch(iq, self.REGISTER_FAILED_EVENT) class CheckVersionInitializer(object): """ Initializer that checks if the minimum common stream version number is 1.0. """ def __init__(self, xs): self.xmlstream = xs def initialize(self): if self.xmlstream.version < (1, 0): raise error.StreamError('unsupported-version') class BindInitializer(xmlstream.BaseFeatureInitiatingInitializer): """ Initializer that implements Resource Binding for the initiating entity. This protocol is documented in U{RFC 3920, section 7<http://www.xmpp.org/specs/rfc3920.html#bind>}. """ feature = (NS_XMPP_BIND, 'bind') def start(self): iq = xmlstream.IQ(self.xmlstream, 'set') bind = iq.addElement((NS_XMPP_BIND, 'bind')) resource = self.xmlstream.authenticator.jid.resource if resource: bind.addElement('resource', content=resource) d = iq.send() d.addCallback(self.onBind) return d def onBind(self, iq): if iq.bind: self.xmlstream.authenticator.jid = JID(unicode(iq.bind.jid)) class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer): """ Initializer that implements session establishment for the initiating entity. This protocol is defined in U{RFC 3921, section 3<http://www.xmpp.org/specs/rfc3921.html#session>}. """ feature = (NS_XMPP_SESSION, 'session') def start(self): iq = xmlstream.IQ(self.xmlstream, 'set') session = iq.addElement((NS_XMPP_SESSION, 'session')) return iq.send() def XMPPClientFactory(jid, password): """ Client factory for XMPP 1.0 (only). This returns a L{xmlstream.XmlStreamFactory} with an L{XMPPAuthenticator} object to perform the stream initialization steps (such as authentication). @see: The notes at L{XMPPAuthenticator} describe how the L{jid} and L{password} parameters are to be used. @param jid: Jabber ID to connect with. @type jid: L{jid.JID} @param password: password to authenticate with. @type password: C{unicode} @return: XML stream factory. @rtype: L{xmlstream.XmlStreamFactory} """ a = XMPPAuthenticator(jid, password) return xmlstream.XmlStreamFactory(a) class XMPPAuthenticator(xmlstream.ConnectAuthenticator): """ Initializes an XmlStream connecting to an XMPP server as a Client. This authenticator performs the initialization steps needed to start exchanging XML stanzas with an XMPP server as an XMPP client. It checks if the server advertises XML stream version 1.0, negotiates TLS (when available), performs SASL authentication, binds a resource and establishes a session. Upon successful stream initialization, the L{xmlstream.STREAM_AUTHD_EVENT} event will be dispatched through the XML stream object. Otherwise, the L{xmlstream.INIT_FAILED_EVENT} event will be dispatched with a failure object. After inspection of the failure, initialization can then be restarted by calling L{initializeStream}. For example, in case of authentication failure, a user may be given the opportunity to input the correct password. By setting the L{password} instance variable and restarting initialization, the stream authentication step is then retried, and subsequent steps are performed if succesful. @ivar jid: Jabber ID to authenticate with. This may contain a resource part, as a suggestion to the server for resource binding. A server may override this, though. If the resource part is left off, the server will generate a unique resource identifier. The server will always return the full Jabber ID in the resource binding step, and this is stored in this instance variable. @type jid: L{jid.JID} @ivar password: password to be used during SASL authentication. @type password: C{unicode} """ namespace = 'jabber:client' def __init__(self, jid, password): xmlstream.ConnectAuthenticator.__init__(self, jid.host) self.jid = jid self.password = password def associateWithStream(self, xs): """ Register with the XML stream. Populates stream's list of initializers, along with their requiredness. This list is used by L{ConnectAuthenticator.initializeStream} to perform the initalization steps. """ xmlstream.ConnectAuthenticator.associateWithStream(self, xs) xs.initializers = [CheckVersionInitializer(xs)] inits = [ (xmlstream.TLSInitiatingInitializer, False), (sasl.SASLInitiatingInitializer, True), (BindInitializer, False), (SessionInitializer, False), ] for initClass, required in inits: init = initClass(xs) init.required = required xs.initializers.append(init)
bsd-3-clause
derekisbusy/yii2-user
widgets/AdminMenu.php
3005
<?php /** * @copyright Copyright &copy; Kartik Visweswaran, communityii, 2014 - 2015 * @package communityii/yii2-user * @version 1.0.0 * @see https://github.com/communityii/yii2-user */ namespace comyii\user\widgets; use Yii; use yii\bootstrap\Nav; use comyii\user\Module; use comyii\user\models\User; /** * User profile actions menu * * @author Kartik Visweswaran <kartikv2@gmail.com> * @since 1.0 */ class AdminMenu extends Nav { /** * @var User the user model */ public $user; /** * @var bool whether the nav items labels should be HTML-encoded. */ public $encodeLabels = false; /** * @var string the user interface currently being rendered */ public $ui; /** * @inheritdoc */ public $options = ['class' => 'nav-pills']; /** * @inheritdoc */ public function init() { /** * @var Module $m */ $m = Yii::$app->getModule('user'); $settings = $this->user === null ? [] : $m->getEditSettingsAdmin($this->user); $this->items[] = [ 'label' => $m->icon('list') . Yii::t('user', 'Users'), 'url' => [$m->actionSettings[Module::ACTION_ADMIN_INDEX]], 'active' => ($this->ui === 'list'), 'linkOptions' => ['title' => Yii::t('user', 'View user listing')] ]; if ($m->checkSettings($settings, 'createUser')) { $this->items[] = [ 'label' => $m->icon('plus') . Yii::t('user', 'Create'), 'url' => [$m->actionSettings[Module::ACTION_ADMIN_CREATE]], 'active' => ($this->ui === 'create'), 'linkOptions' => ['title' => Yii::t('user', 'Create new user')] ]; } if (empty($settings) || $this->user->isNewRecord) { parent::init(); return; } if ($m->checkSettings($settings, 'changeUsername') || $m->checkSettings($settings, 'changeEmail')) { $this->items[] = [ 'label' => $m->icon('pencil') . Yii::t('user', 'Edit'), 'url' => [$m->actionSettings[Module::ACTION_ADMIN_UPDATE], 'id' => $this->user->id], 'active' => ($this->ui === 'edit'), 'linkOptions' => ['title' => Yii::t('user', 'Edit user profile')] ]; } $this->items[] = [ 'label' => $m->icon('wrench') . Yii::t('user', 'Manage'), 'url' => [$m->actionSettings[Module::ACTION_ADMIN_VIEW], 'id' => $this->user->id], 'active' => ($this->ui === 'manage'), 'linkOptions' => ['title' => Yii::t('user', 'Administer user profile')] ]; $this->items[] = [ 'label' => $m->icon('eye-open') . Yii::t('user', 'Profile'), 'url' => [$m->actionSettings[Module::ACTION_PROFILE_VIEW], 'id' => $this->user->id], 'linkOptions' => ['title' => Yii::t('user', 'View user profile')] ]; parent::init(); } }
bsd-3-clause
nwjs/chromium.src
extensions/browser/policy_check_unittest.cc
3457
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/policy_check.h" #include <string> #include <vector> #include "base/memory/ref_counted.h" #include "base/strings/utf_string_conversions.h" #include "content/public/test/test_browser_context.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_test.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/mock_extension_system.h" #include "extensions/browser/preload_check.h" #include "extensions/browser/preload_check_test_util.h" #include "extensions/browser/test_extensions_browser_client.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { namespace { const char16_t kDummyPolicyError[] = u"Cannot install extension"; class ManagementPolicyMock : public ManagementPolicy::Provider { public: ManagementPolicyMock(const Extension* extension, bool may_load) : extension_(extension), may_load_(may_load) {} std::string GetDebugPolicyProviderName() const override { return "ManagementPolicyMock"; } bool UserMayLoad(const Extension* extension, std::u16string* error) const override { EXPECT_EQ(extension_, extension); if (!may_load_) *error = kDummyPolicyError; return may_load_; } private: const Extension* extension_; bool may_load_; }; class TestExtensionSystem : public MockExtensionSystem { public: explicit TestExtensionSystem(content::BrowserContext* context) : MockExtensionSystem(context) {} ~TestExtensionSystem() override {} ManagementPolicy* management_policy() override { return &management_policy_; } private: ManagementPolicy management_policy_; }; } // namespace class PolicyCheckTest : public ExtensionsTest { public: PolicyCheckTest() {} ~PolicyCheckTest() override {} void SetUp() override { ExtensionsTest::SetUp(); // Replace the MockExtensionSystemFactory set by ExtensionsTest. extensions_browser_client()->set_extension_system_factory(&factory_); extension_ = ExtensionBuilder("dummy name").Build(); } protected: scoped_refptr<const Extension> extension_; PreloadCheckRunner runner_; private: MockExtensionSystemFactory<TestExtensionSystem> factory_; }; // Tests an allowed extension. TEST_F(PolicyCheckTest, PolicySuccess) { PolicyCheck policy_check(browser_context(), extension_); runner_.Run(&policy_check); EXPECT_TRUE(runner_.called()); EXPECT_EQ(0u, runner_.errors().size()); EXPECT_TRUE(policy_check.GetErrorMessage().empty()); } // Tests a disallowed extension. TEST_F(PolicyCheckTest, PolicyFailure) { ManagementPolicyMock policy(extension_.get(), false); ExtensionSystem::Get(browser_context()) ->management_policy() ->RegisterProvider(&policy); PolicyCheck policy_check(browser_context(), extension_); runner_.Run(&policy_check); EXPECT_TRUE(runner_.called()); EXPECT_THAT(runner_.errors(), testing::UnorderedElementsAre( PreloadCheck::Error::kDisallowedByPolicy)); EXPECT_EQ(kDummyPolicyError, policy_check.GetErrorMessage()); } } // namespace extensions
bsd-3-clause
leighpauls/k2cro4
chrome/browser/ui/bookmarks/bookmark_tab_helper.cc
4453
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/bookmarks/bookmark_node_data.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/bookmarks/bookmark_tab_helper_delegate.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(BookmarkTabHelper) namespace { bool CanShowBookmarkBar(content::WebUI* ui) { if (!ui) return false; NewTabUI* new_tab = NewTabUI::FromWebUIController(ui->GetController()); return new_tab && new_tab->CanShowBookmarkBar(); } } // namespace BookmarkTabHelper::BookmarkTabHelper(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), is_starred_(false), delegate_(NULL), bookmark_drag_(NULL) { // Register for notifications about URL starredness changing on any profile. registrar_.Add(this, chrome::NOTIFICATION_URLS_STARRED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED, content::NotificationService::AllBrowserContextsAndSources()); } BookmarkTabHelper::~BookmarkTabHelper() { // We don't want any notifications while we're running our destructor. registrar_.RemoveAll(); } bool BookmarkTabHelper::ShouldShowBookmarkBar() { if (web_contents()->ShowingInterstitialPage()) return false; // See WebContents::GetWebUIForCurrentState() comment for more info. This case // is very similar, but for non-first loads, we want to use the committed // entry. This is so the bookmarks bar disappears at the same time the page // does. if (web_contents()->GetController().GetLastCommittedEntry()) { // Not the first load, always use the committed Web UI. return CanShowBookmarkBar(web_contents()->GetCommittedWebUI()); } // When it's the first load, we know either the pending one or the committed // one will have the Web UI in it (see GetWebUIForCurrentState), and only one // of them will be valid, so we can just check both. return CanShowBookmarkBar(web_contents()->GetWebUI()); } void BookmarkTabHelper::DidNavigateMainFrame( const content::LoadCommittedDetails& /*details*/, const content::FrameNavigateParams& /*params*/) { UpdateStarredStateForCurrentURL(); } void BookmarkTabHelper::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED: // BookmarkModel finished loading, fall through to update starred state. case chrome::NOTIFICATION_URLS_STARRED: { // Somewhere, a URL has been starred. // Ignore notifications for profiles other than our current one. Profile* source_profile = content::Source<Profile>(source).ptr(); Profile* this_profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); if (!source_profile || !source_profile->IsSameProfile(this_profile)) return; UpdateStarredStateForCurrentURL(); break; } default: NOTREACHED(); } } void BookmarkTabHelper::SetBookmarkDragDelegate( BookmarkTabHelper::BookmarkDrag* bookmark_drag) { bookmark_drag_ = bookmark_drag; } BookmarkTabHelper::BookmarkDrag* BookmarkTabHelper::GetBookmarkDragDelegate() { return bookmark_drag_; } void BookmarkTabHelper::UpdateStarredStateForCurrentURL() { Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile); const bool old_state = is_starred_; is_starred_ = (model && model->IsBookmarked(web_contents()->GetURL())); if (is_starred_ != old_state && delegate()) delegate()->URLStarredChanged(web_contents(), is_starred_); }
bsd-3-clause
duythien/phanbook
core/modules/cli/tasks/ExportsTask.php
1364
<?php /** * Phanbook : Delightfully simple forum software * * Licensed under The BSD License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @link http://phanbook.com Phanbook Project * @since 1.0.0 * @license https://github.com/phanbook/phanbook/blob/master/LICENSE.txt */ namespace Phanbook\Cli\Tasks; use Phalcon\CLI\Task; use Phanbook\Cli\Library\Output; class ExportsTask extends Task { /** * The task exports database Phanbook * * {cmd} * php cli Exports * {/cmd} * * @return mixed */ public function mainAction() { Output::stdout('======================================================'); Output::stdout('Starting exports your database'); $mysql = $this->config->database->mysql; $host = $mysql->host; $database = $mysql->dbname; $username = $mysql->username; $password = $mysql->password; $name = $database . date('Y-m-d-H:i:s'); $cmd = "mysqldump -u $username --password=$password --host=$host $database > $name.sql"; shell_exec($cmd); Output::stdout('Phanbook exports your database successfully'); Output::stdout('======================================================'); } }
bsd-3-clause
cesarandreu/relay
src/store/__tests__/RelayStoreData-test.js
14070
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+relay */ 'use strict'; require('configureForRelayOSS'); jest .dontMock('GraphQLRange') .dontMock('GraphQLSegment'); const RelayConnectionInterface = require('RelayConnectionInterface'); const RelayStoreData = require('RelayStoreData'); const RelayGarbageCollector = require('RelayGarbageCollector'); const RelayTestUtils = require('RelayTestUtils'); describe('RelayStoreData', () => { let Relay; const {getNode, getVerbatimNode} = RelayTestUtils; beforeEach(() => { jest.resetModuleRegistry(); // @side-effect related to garbage collection Relay = require('Relay'); jasmine.addMatchers(RelayTestUtils.matchers); }); describe('handleQueryPayload', () => { it('writes responses to `records`', () => { const storeData = new RelayStoreData(); const query = getNode(Relay.QL` query { node(id:"123") { id, doesViewerLike, topLevelComments { count, }, } } `); const response = { node: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, __typename: 'Story', }, }; storeData.handleQueryPayload(query, response); // results are written to `records` const recordStore = storeData.getRecordStore(); expect(recordStore.getRecordState('123')).toBe('EXISTENT'); expect(recordStore.getField('123', 'doesViewerLike')).toBe(false); const commentsID = recordStore.getLinkedRecordID('123', 'topLevelComments'); expect(recordStore.getField(commentsID, 'count')).toBe(1); // `queuedRecords` is unchanged expect(storeData.getQueuedData()).toEqual({}); }); it('broadcasts changes for created and updated records', () => { const storeData = new RelayStoreData(); const query = getNode(Relay.QL` query { node(id:"123") { id, doesViewerLike, topLevelComments { count, }, } } `); const response = { node: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, __typename: 'Story', }, }; storeData.handleQueryPayload(query, response); const commentsID = storeData.getRecordStore().getLinkedRecordID('123', 'topLevelComments'); const changeEmitter = storeData.getChangeEmitter(); // broadcasts for created ids expect(changeEmitter.broadcastChangeForID).toBeCalledWith('123'); expect(changeEmitter.broadcastChangeForID).toBeCalledWith(commentsID); const updatedResponse = { node: { id: '123', doesViewerLike: true, // false -> true topLevelComments: { count: 2, // 1 -> 2 }, __typename: 'Story', }, }; changeEmitter.broadcastChangeForID.mockClear(); storeData.handleQueryPayload(query, updatedResponse); // broadcasts for updated ids expect(changeEmitter.broadcastChangeForID).toBeCalledWith('123'); expect(changeEmitter.broadcastChangeForID).toBeCalledWith(commentsID); }); it('uses cached IDs for root fields without IDs', () => { const storeData = new RelayStoreData(); const query = getNode(Relay.QL` query { node(id:"123") { id, doesViewerLike, topLevelComments { count, }, } } `); const response = { node: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, __typename: 'Story', }, }; storeData.handleQueryPayload(query, response); // results are written to `records` const recordStore = storeData.getRecordStore(); expect(recordStore.getRecordState('123')).toBe('EXISTENT'); expect(recordStore.getField('123', 'doesViewerLike')).toBe(false); const commentsID = recordStore.getLinkedRecordID('123', 'topLevelComments'); expect(recordStore.getField(commentsID, 'count')).toBe(1); // `queuedRecords` is unchanged expect(storeData.getQueuedData()).toEqual({}); }); }); describe('handleUpdatePayload', () => { it('writes server payloads to `records`', () => { const storeData = new RelayStoreData(); // create the root node storeData.getRecordWriter().putRecord('123'); const mutationQuery = getNode(Relay.QL` mutation { feedbackLike(input:$input) { clientMutationId, feedback { id, doesViewerLike, topLevelComments { count, } }, } } `); const payload = { [RelayConnectionInterface.CLIENT_MUTATION_ID]: 'abc', feedback: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, }, }; storeData.handleUpdatePayload(mutationQuery, payload, { configs: [], isOptimisticUpdate: false, }); // results are written to `records` const recordStore = storeData.getRecordStore(); expect(recordStore.getRecordState('123')).toBe('EXISTENT'); expect(recordStore.getField('123', 'doesViewerLike')).toBe(false); const commentsID = recordStore.getLinkedRecordID('123', 'topLevelComments'); expect(recordStore.getField(commentsID, 'count')).toBe(1); // `queuedRecords` is unchanged expect(storeData.getQueuedData()).toEqual({}); }); it('writes optimistic payloads to `queuedRecords`', () => { const storeData = new RelayStoreData(); // create the root node storeData.getRecordWriter().putRecord('123'); const mutationQuery = getNode(Relay.QL` mutation { feedbackLike(input:$input) { clientMutationId, feedback { id, doesViewerLike, topLevelComments { count, } }, } } `); const payload = { [RelayConnectionInterface.CLIENT_MUTATION_ID]: 'abc', feedback: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, }, }; storeData.handleUpdatePayload(mutationQuery, payload, { configs: [], isOptimisticUpdate: true, clientMutationID: 'mutationID', }); // results are written to `queuedRecords` const queuedStore = storeData.getQueuedStore(); expect(queuedStore.getRecordState('123')).toBe('EXISTENT'); expect(queuedStore.getField('123', 'doesViewerLike')).toBe(false); const commentsID = queuedStore.getLinkedRecordID('123', 'topLevelComments'); expect(queuedStore.getField(commentsID, 'count')).toBe(1); // `records` is unchanged expect(storeData.getNodeData()).toEqual({ '123': { __dataID__: '123', __typename: undefined, }, }); }); it( 'writes optimistic payloads to `queuedRecords` even if values are ' + 'identical to those in `records`', () => { // Example case: With a story unliked, quickly like and unlike it. The // second unlike will have the same value as the store // (`doesViewerLike === false`), but this must be recorded as an // optimistic value so that the first server payload (with the story // liked) is ignored. const storeData = new RelayStoreData(); // write starting values for a query const query = getNode(Relay.QL` query { node(id:"123") { id, doesViewerLike, topLevelComments { count, }, } } `); let response = { node: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, __typename: 'Story', }, }; storeData.handleQueryPayload(query, response); // write an optimistic update with the same values as the store const mutationQuery = getNode(Relay.QL` mutation { feedbackLike(input:$input) { clientMutationId, feedback { id, doesViewerLike, topLevelComments { count, } }, } } `); const payload = { [RelayConnectionInterface.CLIENT_MUTATION_ID]: 'abc', feedback: { id: '123', doesViewerLike: false, topLevelComments: { count: 1, }, }, }; storeData.handleUpdatePayload(mutationQuery, payload, { configs: [], isOptimisticUpdate: true, clientMutationID: 'mutationID', }); // simulate a server response with different data response = { node: { __typename: 'Feedback', id: '123', doesViewerLike: true, // inverted topLevelComments: null, // delete }, }; storeData.handleQueryPayload(query, response); // verify that the optimistic update takes precedence over the // server update const recordStore = storeData.getQueuedStore(); expect(recordStore.getField('123', 'doesViewerLike')).toBe(false); const commentsID = recordStore.getLinkedRecordID('123', 'topLevelComments'); expect(commentsID).toBeTruthy(); expect(recordStore.getField(commentsID, 'count')).toBe(1); } ); }); describe('buildFragmentQueryForDataID', () => { it('builds root queries for refetchable IDs', () => { const data = new RelayStoreData(); const fragment = getNode(Relay.QL` fragment on User { id name } `); const query = data.buildFragmentQueryForDataID( fragment, '123' ); expect(query).toEqualQueryRoot(getNode(Relay.QL` query { node(id:"123") { id __typename ... on User { id name } } } `)); expect(query.getName()).toBe(fragment.getDebugName()); expect(query.isAbstract()).toBe(true); }); it('builds root queries using the path for non-refetchable IDs', () => { const storeData = new RelayStoreData(); const addressFragment = Relay.QL`fragment on User{id,address{city}}`; const node = getNode(Relay.QL` query { node(id: "123") { id, ${addressFragment} } } `); const payload = { node: { id: '123', __typename: 'User', address: { city: 'Menlo Park', }, }, }; storeData.handleQueryPayload(node, payload); const fragment = getNode(Relay.QL` fragment on StreetAddress { city, } `); const query = storeData.buildFragmentQueryForDataID(fragment, 'client:1'); expect(query).toEqualQueryRoot(getVerbatimNode(Relay.QL` query RelayStoreData($id_0: ID!) { node(id: $id_0) { ... on User { id, __typename, address { ... on StreetAddress { city, }, }, } }, } `, {id_0: '123'})); expect(query.getName()).toBe(node.getName()); expect(query.isAbstract()).toBe(true); }); }); describe('garbage collection', () => { it('initializes the garbage collector if no data has been added', () => { const data = new RelayStoreData(); expect(data.getGarbageCollector()).toBe(undefined); expect(() => data.initializeGarbageCollector()).not.toThrow(); expect( data.getGarbageCollector() instanceof RelayGarbageCollector ).toBe(true); }); it('warns if initialized after data has been added', () => { jest.mock('warning'); const response = {node: {id: 0, __typename: 'User'}}; const data = new RelayStoreData(); const query = getNode(Relay.QL`query{node(id:"a") {id}}`); data.handleQueryPayload(query, response); const warningMsg = 'RelayStoreData: Garbage collection can only be initialized when ' + 'no data is present.'; expect([warningMsg]).toBeWarnedNTimes(0); data.initializeGarbageCollector(); expect([warningMsg]).toBeWarnedNTimes(1); }); it( 'registers created dataIDs in the garbage collector if it has been ' + 'initialized', () => { RelayGarbageCollector.prototype.register = jest.genMockFunction(); const response = {node: {id: 0}}; const data = new RelayStoreData(); data.initializeGarbageCollector(); const query = getNode(Relay.QL`query{node(id:"a") {id}}`); const garbageCollector = data.getGarbageCollector(); expect(garbageCollector.register).not.toBeCalled(); data.handleQueryPayload(query, response); expect(garbageCollector.register).toBeCalled(); expect(garbageCollector.register.mock.calls[0][0]).toBe('a'); } ); }); });
bsd-3-clause
drobilla/nunaliit
nunaliit2-couch-application/src/main/atlas_couchapp/views/schema-from-docid/map.js
88
function(doc) { if( doc.nunaliit_schema ) { emit(doc._id,doc.nunaliit_schema); }; }
bsd-3-clause
mudunuriRaju/tlr-live
tollbackend/web/js/angular-1.5.5/i18n/angular-locale_es-cr.js
3608
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a. m.", "p. m." ], "DAY": [ "domingo", "lunes", "martes", "mi\u00e9rcoles", "jueves", "viernes", "s\u00e1bado" ], "ERANAMES": [ "antes de Cristo", "despu\u00e9s de Cristo" ], "ERAS": [ "a. C.", "d. C." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ], "SHORTDAY": [ "dom.", "lun.", "mar.", "mi\u00e9.", "jue.", "vie.", "s\u00e1b." ], "SHORTMONTH": [ "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sept.", "oct.", "nov.", "dic." ], "STANDALONEMONTH": [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d 'de' MMMM 'de' y", "longDate": "d 'de' MMMM 'de' y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/M/yy h:mm a", "shortDate": "d/M/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20a1", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "es-cr", "localeID": "es_CR", "pluralCat": function (n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/browser/chromeos/extensions/file_manager/file_stream_md5_digester.cc
2049
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/extensions/file_manager/file_stream_md5_digester.h" #include <utility> #include "base/bind.h" #include "base/callback.h" #include "net/base/net_errors.h" #include "storage/browser/file_system/file_stream_reader.h" namespace drive { namespace util { namespace { const int kMd5DigestBufferSize = 512 * 1024; // 512 kB. } // namespace FileStreamMd5Digester::FileStreamMd5Digester() : buffer_(base::MakeRefCounted<net::IOBuffer>(kMd5DigestBufferSize)) {} FileStreamMd5Digester::~FileStreamMd5Digester() = default; void FileStreamMd5Digester::GetMd5Digest( std::unique_ptr<storage::FileStreamReader> stream_reader, ResultCallback callback) { // Only one digest can be running at a time. DCHECK(callback_.is_null()); callback_ = std::move(callback); reader_ = std::move(stream_reader); base::MD5Init(&md5_context_); // Start the read/hash. ReadNextChunk(); } void FileStreamMd5Digester::ReadNextChunk() { const int result = reader_->Read(buffer_.get(), kMd5DigestBufferSize, base::BindOnce(&FileStreamMd5Digester::OnChunkRead, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnChunkRead(result); } void FileStreamMd5Digester::OnChunkRead(int bytes_read) { if (bytes_read < 0) { // Error - just return empty string. std::move(callback_).Run(""); return; } else if (bytes_read == 0) { // EOF. base::MD5Digest digest; base::MD5Final(&digest, &md5_context_); std::string result = base::MD5DigestToBase16(digest); std::move(callback_).Run(std::move(result)); return; } // Read data and digest it. base::MD5Update(&md5_context_, base::StringPiece(buffer_->data(), bytes_read)); // Kick off the next read. ReadNextChunk(); } } // namespace util } // namespace drive
bsd-3-clause
leighpauls/k2cro4
chrome_frame/test/chrome_frame_test_utils.cc
23291
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/test/chrome_frame_test_utils.h" #include <atlapp.h> #include <atlmisc.h> #include <iepmapi.h> #include <sddl.h> #include <shlobj.h> #include <winsock2.h> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/file_version_info.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/process.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "base/win/registry.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #include "chrome_frame/utils.h" #include "net/base/net_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" namespace chrome_frame_test { const wchar_t kCrashServicePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices"; const DWORD kCrashServicePipeDesiredAccess = FILE_READ_DATA | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES; const DWORD kCrashServicePipeFlagsAndAttributes = SECURITY_IDENTIFICATION | SECURITY_SQOS_PRESENT; const int kCrashServiceStartupTimeoutMs = 500; const wchar_t kIEImageName[] = L"iexplore.exe"; const wchar_t kIEBrokerImageName[] = L"ieuser.exe"; const char kChromeImageName[] = "chrome.exe"; const wchar_t kIEProfileName[] = L"iexplore"; const wchar_t kChromeLauncher[] = L"chrome_launcher.exe"; #ifndef NDEBUG const base::TimeDelta kChromeFrameLongNavigationTimeout = base::TimeDelta::FromSeconds(30); const base::TimeDelta kChromeFrameVeryLongNavigationTimeout = base::TimeDelta::FromSeconds(90); #else const base::TimeDelta kChromeFrameLongNavigationTimeout = base::TimeDelta::FromSeconds(15); const base::TimeDelta kChromeFrameVeryLongNavigationTimeout = base::TimeDelta::FromSeconds(45); #endif // Callback function for EnumThreadWindows. BOOL CALLBACK CloseWindowsThreadCallback(HWND hwnd, LPARAM param) { int& count = *reinterpret_cast<int*>(param); if (IsWindowVisible(hwnd)) { if (IsWindowEnabled(hwnd)) { DWORD results = 0; if (!::SendMessageTimeout(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0, SMTO_BLOCK, 10000, &results)) { LOG(WARNING) << "Window hung: " << base::StringPrintf(L"%08X", hwnd); } count++; } else { LOG(WARNING) << "Skipping disabled window: " << base::StringPrintf(L"%08X", hwnd); } } return TRUE; // continue enumeration } // Attempts to close all non-child, visible windows on the given thread. // The return value is the number of visible windows a close request was // sent to. int CloseVisibleTopLevelWindowsOnThread(DWORD thread_id) { int window_close_attempts = 0; EnumThreadWindows(thread_id, CloseWindowsThreadCallback, reinterpret_cast<LPARAM>(&window_close_attempts)); return window_close_attempts; } // Enumerates the threads of a process and attempts to close visible non-child // windows on all threads of the process. // The return value is the number of visible windows a close request was // sent to. int CloseVisibleWindowsOnAllThreads(HANDLE process) { DWORD process_id = ::GetProcessId(process); if (process_id == 0) { NOTREACHED(); return 0; } base::win::ScopedHandle snapshot( CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)); if (!snapshot.IsValid()) { NOTREACHED(); return 0; } int window_close_attempts = 0; THREADENTRY32 te = { sizeof(THREADENTRY32) }; if (Thread32First(snapshot, &te)) { do { if (RTL_CONTAINS_FIELD(&te, te.dwSize, th32OwnerProcessID) && te.th32OwnerProcessID == process_id) { window_close_attempts += CloseVisibleTopLevelWindowsOnThread(te.th32ThreadID); } te.dwSize = sizeof(te); } while (Thread32Next(snapshot, &te)); } return window_close_attempts; } std::wstring GetExecutableAppPath(const std::wstring& file) { std::wstring kAppPathsKey = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\"; std::wstring app_path; base::win::RegKey key(HKEY_LOCAL_MACHINE, (kAppPathsKey + file).c_str(), KEY_READ); if (key.Handle()) { key.ReadValue(NULL, &app_path); } return app_path; } std::wstring FormatCommandForApp(const std::wstring& exe_name, const std::wstring& argument) { std::wstring reg_path( base::StringPrintf(L"Applications\\%ls\\shell\\open\\command", exe_name.c_str())); base::win::RegKey key(HKEY_CLASSES_ROOT, reg_path.c_str(), KEY_READ); std::wstring command; if (key.Handle()) { key.ReadValue(NULL, &command); int found = command.find(L"%1"); if (found >= 0) { command.replace(found, 2, argument); } } return command; } base::ProcessHandle LaunchExecutable(const std::wstring& executable, const std::wstring& argument) { base::ProcessHandle process = NULL; std::wstring path = GetExecutableAppPath(executable); if (path.empty()) { path = FormatCommandForApp(executable, argument); if (path.empty()) { LOG(ERROR) << "Failed to find executable: " << executable; } else { CommandLine cmdline = CommandLine::FromString(path); if (!base::LaunchProcess(cmdline, base::LaunchOptions(), &process)) { LOG(ERROR) << "LaunchProcess failed: " << ::GetLastError(); } } } else { CommandLine cmdline((FilePath(path))); cmdline.AppendArgNative(argument); if (!base::LaunchProcess(cmdline, base::LaunchOptions(), &process)) { LOG(ERROR) << "LaunchProcess failed: " << ::GetLastError(); } } return process; } base::ProcessHandle LaunchChrome(const std::wstring& url, const FilePath& user_data_dir) { FilePath path; PathService::Get(base::DIR_MODULE, &path); path = path.AppendASCII(kChromeImageName); CommandLine cmd(path); cmd.AppendSwitch(switches::kNoFirstRun); if (!user_data_dir.empty()) cmd.AppendSwitchPath(switches::kUserDataDir, user_data_dir); cmd.AppendArgNative(url); base::ProcessHandle process = NULL; base::LaunchProcess(cmd, base::LaunchOptions(), &process); return process; } base::ProcessHandle LaunchIEOnVista(const std::wstring& url) { typedef HRESULT (WINAPI* IELaunchURLPtr)(const wchar_t* url, PROCESS_INFORMATION* pi, VOID* info); IELaunchURLPtr launch; PROCESS_INFORMATION pi = {0}; IELAUNCHURLINFO info = {sizeof info, 0}; HMODULE h = LoadLibrary(L"ieframe.dll"); if (!h) { LOG(ERROR) << "Failed to load ieframe.dll: " << ::GetLastError(); return NULL; } launch = reinterpret_cast<IELaunchURLPtr>(GetProcAddress(h, "IELaunchURL")); CHECK(launch); HRESULT hr = launch(url.c_str(), &pi, &info); FreeLibrary(h); if (SUCCEEDED(hr)) { CloseHandle(pi.hThread); } else { LOG(ERROR) << base::StringPrintf("IELaunchURL failed: 0x%08X", hr); } return pi.hProcess; } base::ProcessHandle LaunchIE(const std::wstring& url) { if (GetInstalledIEVersion() >= IE_8) { chrome_frame_test::ClearIESessionHistory(); } if (base::win::GetVersion() >= base::win::VERSION_VISTA) { return LaunchIEOnVista(url); } return LaunchExecutable(kIEImageName, url); } int CloseAllIEWindows() { int ret = 0; base::win::ScopedComPtr<IShellWindows> windows; HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL, IID_IShellWindows, reinterpret_cast<void**>(windows.Receive())); DCHECK(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { long count = 0; // NOLINT windows->get_Count(&count); VARIANT i = { VT_I4 }; for (i.lVal = 0; i.lVal < count; ++i.lVal) { base::win::ScopedComPtr<IDispatch> folder; windows->Item(i, folder.Receive()); if (folder != NULL) { base::win::ScopedComPtr<IWebBrowser2> browser; if (SUCCEEDED(browser.QueryFrom(folder))) { bool is_ie = true; HWND window = NULL; // Check the class of the browser window to make sure we only close // IE windows. if (browser->get_HWND(reinterpret_cast<SHANDLE_PTR*>(window))) { wchar_t class_name[MAX_PATH]; if (::GetClassName(window, class_name, arraysize(class_name))) { is_ie = _wcsicmp(class_name, L"IEFrame") == 0; } } if (is_ie) { browser->Quit(); ++ret; } } } } } return ret; } LowIntegrityToken::LowIntegrityToken() : impersonated_(false) { } LowIntegrityToken::~LowIntegrityToken() { RevertToSelf(); } BOOL LowIntegrityToken::RevertToSelf() { BOOL ok = TRUE; if (impersonated_) { DCHECK(IsImpersonated()); ok = ::RevertToSelf(); if (ok) impersonated_ = false; } return ok; } BOOL LowIntegrityToken::Impersonate() { DCHECK(!impersonated_); DCHECK(!IsImpersonated()); HANDLE process_token_handle = NULL; BOOL ok = ::OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &process_token_handle); if (!ok) { LOG(ERROR) << "::OpenProcessToken failed: " << GetLastError(); return ok; } base::win::ScopedHandle process_token(process_token_handle); // Create impersonation low integrity token. HANDLE impersonation_token_handle = NULL; ok = ::DuplicateTokenEx(process_token, TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, NULL, SecurityImpersonation, TokenImpersonation, &impersonation_token_handle); if (!ok) { LOG(ERROR) << "::DuplicateTokenEx failed: " << GetLastError(); return ok; } // TODO(stoyan): sandbox/win/src/restricted_token_utils.cc has // SetTokenIntegrityLevel function already. base::win::ScopedHandle impersonation_token(impersonation_token_handle); PSID integrity_sid = NULL; TOKEN_MANDATORY_LABEL tml = {0}; ok = ::ConvertStringSidToSid(SDDL_ML_LOW, &integrity_sid); if (!ok) { LOG(ERROR) << "::ConvertStringSidToSid failed: " << GetLastError(); return ok; } tml.Label.Attributes = SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED; tml.Label.Sid = integrity_sid; ok = ::SetTokenInformation(impersonation_token, TokenIntegrityLevel, &tml, sizeof(tml) + ::GetLengthSid(integrity_sid)); ::LocalFree(integrity_sid); if (!ok) { LOG(ERROR) << "::SetTokenInformation failed: " << GetLastError(); return ok; } // Switch current thread to low integrity. ok = ::ImpersonateLoggedOnUser(impersonation_token); if (ok) { impersonated_ = true; } else { LOG(ERROR) << "::ImpersonateLoggedOnUser failed: " << GetLastError(); } return ok; } bool LowIntegrityToken::IsImpersonated() { HANDLE token = NULL; if (!::OpenThreadToken(::GetCurrentThread(), 0, false, &token) && ::GetLastError() != ERROR_NO_TOKEN) { return true; } if (token) ::CloseHandle(token); return false; } HRESULT LaunchIEAsComServer(IWebBrowser2** web_browser) { if (!web_browser) return E_INVALIDARG; if (GetInstalledIEVersion() >= IE_8) { chrome_frame_test::ClearIESessionHistory(); } AllowSetForegroundWindow(ASFW_ANY); HRESULT hr = S_OK; DWORD cocreate_flags = CLSCTX_LOCAL_SERVER; chrome_frame_test::LowIntegrityToken token; base::IntegrityLevel integrity_level = base::INTEGRITY_UNKNOWN; // Vista has a bug which manifests itself when a medium integrity process // launches a COM server like IE which runs in protected mode due to UAC. // This causes the IWebBrowser2 interface which is returned to be useless, // i.e it does not receive any events, etc. Our workaround for this is // to impersonate a low integrity token and then launch IE. Skip this if the // tests are running at high integrity, since the workaround results in the // medium-integrity broker exiting, and the low-integrity IE is therefore // unable to get chrome_launcher running at medium integrity. if (base::win::GetVersion() == base::win::VERSION_VISTA && GetInstalledIEVersion() == IE_7 && base::GetProcessIntegrityLevel(base::Process::Current().handle(), &integrity_level) && integrity_level != base::HIGH_INTEGRITY) { // Create medium integrity browser that will launch IE broker. base::win::ScopedComPtr<IWebBrowser2> medium_integrity_browser; hr = medium_integrity_browser.CreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER); if (FAILED(hr)) return hr; medium_integrity_browser->Quit(); // Broker remains alive. if (!token.Impersonate()) { hr = HRESULT_FROM_WIN32(GetLastError()); return hr; } cocreate_flags |= CLSCTX_ENABLE_CLOAKING; } hr = ::CoCreateInstance(CLSID_InternetExplorer, NULL, cocreate_flags, IID_IWebBrowser2, reinterpret_cast<void**>(web_browser)); // ~LowIntegrityToken() will switch integrity back to medium. return hr; } std::wstring GetExeVersion(const std::wstring& exe_path) { scoped_ptr<FileVersionInfo> ie_version_info( FileVersionInfo::CreateFileVersionInfo(FilePath(exe_path))); return ie_version_info->product_version(); } IEVersion GetInstalledIEVersion() { std::wstring path(chrome_frame_test::GetExecutableAppPath(kIEImageName)); std::wstring version(GetExeVersion(path)); size_t first_dot = version.find(L'.'); int major_version = 0; if (!base::StringToInt(base::StringPiece16( version.data(), first_dot == std::wstring::npos ? version.size() : first_dot), &major_version)) { return IE_UNSUPPORTED; } switch (major_version) { case 6: return IE_6; case 7: return IE_7; case 8: return IE_8; case 9: return IE_9; case 10: return IE_10; default: break; } return IE_UNSUPPORTED; } FilePath GetProfilePathForIE() { FilePath profile_path; // Browsers without IDeleteBrowsingHistory in non-priv mode // have their profiles moved into "Temporary Internet Files". // The code below basically retrieves the version of IE and computes // the profile directory accordingly. if (GetInstalledIEVersion() <= IE_7) { profile_path = GetIETemporaryFilesFolder(); profile_path = profile_path.Append(L"Google Chrome Frame"); } else { GetChromeFrameProfilePath(kIEProfileName, &profile_path); } return profile_path; } FilePath GetTestDataFolder() { FilePath test_dir; PathService::Get(base::DIR_SOURCE_ROOT, &test_dir); test_dir = test_dir.Append(FILE_PATH_LITERAL("chrome_frame")) .Append(FILE_PATH_LITERAL("test")) .Append(FILE_PATH_LITERAL("data")); return test_dir; } FilePath GetSeleniumTestFolder() { FilePath test_dir; PathService::Get(base::DIR_SOURCE_ROOT, &test_dir); test_dir = test_dir.Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("selenium_core")); return test_dir; } std::wstring GetPathFromUrl(const std::wstring& url) { string16 url16 = WideToUTF16(url); GURL gurl = GURL(url16); if (gurl.has_query()) { GURL::Replacements replacements; replacements.ClearQuery(); gurl = gurl.ReplaceComponents(replacements); } return UTF8ToWide(gurl.PathForRequest()); } std::wstring GetPathAndQueryFromUrl(const std::wstring& url) { string16 url16 = WideToUTF16(url); GURL gurl = GURL(url16); return UTF8ToWide(gurl.PathForRequest()); } std::wstring GetClipboardText() { string16 text16; ui::Clipboard::GetForCurrentThread()->ReadText( ui::Clipboard::BUFFER_STANDARD, &text16); return UTF16ToWide(text16); } void SetClipboardText(const std::wstring& text) { ui::ScopedClipboardWriter clipboard_writer( ui::Clipboard::GetForCurrentThread(), ui::Clipboard::BUFFER_STANDARD); clipboard_writer.WriteText(WideToUTF16(text)); } bool AddCFMetaTag(std::string* html_data) { if (!html_data) { NOTREACHED(); return false; } std::string lower = StringToLowerASCII(*html_data); size_t head = lower.find("<head>"); if (head == std::string::npos) { // Add missing head section. size_t html = lower.find("<html>"); if (html != std::string::npos) { head = html + strlen("<html>"); html_data->insert(head, "<head></head>"); } else { LOG(ERROR) << "Meta tag will not be injected " << "because the html tag could not be found"; } } if (head != std::string::npos) { html_data->insert( head + strlen("<head>"), "<meta http-equiv=\"x-ua-compatible\" content=\"chrome=1\" />"); } return head != std::string::npos; } CloseIeAtEndOfScope::~CloseIeAtEndOfScope() { int closed = CloseAllIEWindows(); LOG_IF(ERROR, closed != 0) << "Closed " << closed << " windows forcefully"; } // Attempt to connect to a running crash_service instance. Success occurs if we // can actually connect to the service's pipe or we receive ERROR_PIPE_BUSY. // Waits up to |timeout_ms| for success. |timeout_ms| may be 0, meaning only try // once, or negative, meaning wait forever. bool DetectRunningCrashService(int timeout_ms) { // Wait for the crash_service.exe to be ready for clients. base::Time start = base::Time::Now(); base::win::ScopedHandle new_pipe; while (true) { new_pipe.Set(::CreateFile(kCrashServicePipeName, kCrashServicePipeDesiredAccess, 0, // dwShareMode NULL, // lpSecurityAttributes OPEN_EXISTING, kCrashServicePipeFlagsAndAttributes, NULL)); // hTemplateFile if (new_pipe.IsValid()) { return true; } switch (::GetLastError()) { case ERROR_PIPE_BUSY: // OK, it exists, let's assume that clients will eventually be able to // connect to it. return true; case ERROR_FILE_NOT_FOUND: // Wait a bit longer break; default: DPLOG(WARNING) << "Unexpected error while checking crash_service.exe's " << "pipe."; // Go ahead and wait in case it clears up. break; } if (timeout_ms == 0) { return false; } else if (timeout_ms > 0) { base::TimeDelta duration = base::Time::Now() - start; if (duration.InMilliseconds() > timeout_ms) { return false; } } Sleep(10); } } base::ProcessHandle StartCrashService() { if (DetectRunningCrashService(kCrashServiceStartupTimeoutMs)) { VLOG(1) << "crash_service.exe is already running. We will use the " "existing process and leave it running after tests complete."; return NULL; } FilePath exe_dir; if (!PathService::Get(base::DIR_EXE, &exe_dir)) { DCHECK(false); return NULL; } base::ProcessHandle crash_service = NULL; VLOG(1) << "Starting crash_service.exe so you know if a test crashes!"; FilePath crash_service_path = exe_dir.AppendASCII("crash_service.exe"); if (!base::LaunchProcess(crash_service_path.value(), base::LaunchOptions(), &crash_service)) { LOG(ERROR) << "Couldn't start crash_service.exe"; return NULL; } base::Time start = base::Time::Now(); if (DetectRunningCrashService(kCrashServiceStartupTimeoutMs)) { VLOG(1) << "crash_service.exe is ready for clients in " << (base::Time::Now() - start).InMilliseconds() << " ms."; return crash_service; } else { LOG(ERROR) << "crash_service.exe failed to accept client connections " "within " << kCrashServiceStartupTimeoutMs << " ms. " "Terminating it now."; // First check to see if it's even still running just to minimize the // likelihood of spurious error messages from KillProcess. if (WAIT_OBJECT_0 != ::WaitForSingleObject(crash_service, 0)) { base::KillProcess(crash_service, 0, false); } return NULL; } } ScopedVirtualizeHklmAndHkcu::ScopedVirtualizeHklmAndHkcu() { override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE, L"hklm_fake"); override_manager_.OverrideRegistry(HKEY_CURRENT_USER, L"hkcu_fake"); } ScopedVirtualizeHklmAndHkcu::~ScopedVirtualizeHklmAndHkcu() { } void ScopedVirtualizeHklmAndHkcu::RemoveAllOverrides() { override_manager_.RemoveAllOverrides(); } bool KillProcesses(const std::wstring& executable_name, int exit_code, bool wait) { bool result = true; base::NamedProcessIterator iter(executable_name, NULL); while (const base::ProcessEntry* entry = iter.NextProcessEntry()) { result &= base::KillProcessById(entry->pid(), exit_code, wait); } return result; } ScopedChromeFrameRegistrar::RegistrationType GetTestBedType() { if (GetConfigBool(false, L"PerUserTestBed")) { return ScopedChromeFrameRegistrar::PER_USER; } else { return ScopedChromeFrameRegistrar::SYSTEM_LEVEL; } } void ClearIESessionHistory() { FilePath session_history_path; if (!PathService::Get(base::DIR_LOCAL_APP_DATA, &session_history_path)) return; session_history_path = session_history_path.AppendASCII("Microsoft"); session_history_path = session_history_path.AppendASCII("Internet Explorer"); session_history_path = session_history_path.AppendASCII("Recovery"); file_util::Delete(session_history_path, true); } std::string GetLocalIPv4Address() { std::string address; net::NetworkInterfaceList nic_list; if (!net::GetNetworkList(&nic_list)) { LOG(ERROR) << "GetNetworkList failed to look up non-loopback adapters. " << "Tests will be run over the loopback adapter, which may " << "result in hangs."; } else { // GetNetworkList only returns 'Up' non-loopback adapters. Select the first // IPv4 address found - we should be able to bind/connect over it. for (size_t i = 0; i < nic_list.size(); ++i) { if (nic_list[i].address.size() != net::kIPv4AddressSize) continue; char* address_string = inet_ntoa(*reinterpret_cast<in_addr*>(&nic_list[i].address[0])); DCHECK(address_string != NULL); if (address_string != NULL) { LOG(INFO) << "HTTP tests will run over " << address_string << "."; address.assign(address_string); break; } } } if (address.empty()) { LOG(ERROR) << "Failed to find a non-loopback IP_V4 address. Tests will be " << "run over the loopback adapter, which may result in hangs."; address.assign("127.0.0.1"); } return address; } } // namespace chrome_frame_test
bsd-3-clause
pbrunet/pythran
third_party/nt2/include/functions/simd/perms.hpp
179
#ifndef NT2_INCLUDE_FUNCTIONS_SIMD_PERMS_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_SIMD_PERMS_HPP_INCLUDED #include <nt2/combinatorial/include/functions/simd/perms.hpp> #endif
bsd-3-clause
cisco/PDTool
CISAdminApi8.0.0/src/com/compositesw/services/system/util/security/RbsSetEnabledRequest.java
1380
package com.compositesw.services.system.util.security; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.compositesw.services.system.util.common.BaseRequest; /** * <p>Java class for rbsSetEnabledRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="rbsSetEnabledRequest"> * &lt;complexContent> * &lt;extension base="{http://www.compositesw.com/services/system/util/common}baseRequest"> * &lt;sequence> * &lt;element name="enabled" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "rbsSetEnabledRequest", propOrder = { "enabled" }) public class RbsSetEnabledRequest extends BaseRequest { protected boolean enabled; /** * Gets the value of the enabled property. * */ public boolean isEnabled() { return enabled; } /** * Sets the value of the enabled property. * */ public void setEnabled(boolean value) { this.enabled = value; } }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s02/CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_72a.cpp
2982
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_72a.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml Template File: sources-sink-72a.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: alloca Data buffer is allocated on the stack with alloca() * GoodSource: Allocate memory on the heap * Sinks: * BadSink : Print then free data * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> #include <wchar.h> using namespace std; namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_72 { #ifndef OMITBAD /* bad function declaration */ void badSink(vector<char *> dataVector); void bad() { char * data; vector<char *> dataVector; data = NULL; /* Initialize data */ { /* FLAW: data is allocated on the stack and deallocated in the BadSink */ char * dataBuffer = (char *)ALLOCA(sizeof(char)); *dataBuffer = 'A'; data = dataBuffer; } /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); badSink(dataVector); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<char *> dataVector); static void goodG2B() { char * data; vector<char *> dataVector; data = NULL; /* Initialize data */ { /* FIX: data is allocated on the heap and deallocated in the BadSink */ char * dataBuffer = new char; *dataBuffer = 'A'; data = dataBuffer; } /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); goodG2BSink(dataVector); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE590_Free_Memory_Not_on_Heap__delete_char_alloca_72; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
vietnguyen/dhis2-core
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/query/Direction.java
1699
package org.hisp.dhis.query; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public enum Direction { ASCENDING, DESCENDING }
bsd-3-clause
mfurr/Diamondback-Ruby
tests/parser/large_examples/kroc.rb
8811
# # kroc.rb # # based on: # >> kroc.tcl - Copyright (C) 2004 David Zolli <kroc@kroc.tk> # imgdir = File.join(File.dirname(__FILE__), 'kroc', 'kroc') $images = Tk::Tile.load_images(imgdir, '*.gif') if TkPackage.vcompare(Tk::Tile.package_version, '0.5') >= 0 $TNotebook_Tab = Tk::Tile::TNotebook.style('Tab') else $TNotebook_Tab = 'Tab.TNotebook' end def kroc_rb_settings # Tk::Tile::Style.default(TkRoot, :background=>'#FCB64F', # :troughcolor=>'#F8C278', :borderwidth=>1) # or # Tk::Tile::Style.default(Tk.root, :background=>'#FCB64F', # :troughcolor=>'#F8C278', :borderwidth=>1) # or # Tk::Tile::Style.default('.', :background=>'#FCB64F', # :troughcolor=>'#F8C278', :borderwidth=>1) # or # Tk::Tile::Style.default(nil, :background=>'#FCB64F', # :troughcolor=>'#F8C278', :borderwidth=>1) # or Tk::Tile::Style.default(:background=>'#FCB64F', :troughcolor=>'#F8C278', :borderwidth=>1) # Tk::Tile::Style.default(TkRoot, :font=>Tk::Tile::Font::Default, # :borderwidth=>1) # or # Tk::Tile::Style.default(Tk.root, :font=>Tk::Tile::Font::Default, # :borderwidth=>1) # or # Tk::Tile::Style.default('.', :font=>Tk::Tile::Font::Default, # :borderwidth=>1) # or # Tk::Tile::Style.default(nil, :font=>Tk::Tile::Font::Default, # :borderwidth=>1) # or Tk::Tile::Style.default(:font=>Tk::Tile::Font::Default, :borderwidth=>1) # Tk::Tile::Style.map(TkRoot, :background=>[:active, '#694418']) # or # Tk::Tile::Style.map(Tk.root, :background=>[:active, '#694418']) # or # Tk::Tile::Style.map('.', :background=>[:active, '#694418']) # or # Tk::Tile::Style.map(nil, :background=>[:active, '#694418']) # or Tk::Tile::Style.map(:background=>[:active, '#694418']) Tk::Tile::Style.map(:foreground=>[:disabled, '#B2B2B2', :active, '#FFE7CB']) # Tk::Tile::Style.default('TButton', :padding=>[10,4]) Tk::Tile::Style.default(Tk::Tile::TButton, :padding=>[10,4]) # Tk::Tile::Style.default('TNotebook.Tab', Tk::Tile::Style.default($TNotebook_Tab, :padding=>[10, 3], :font=>Tk::Tile::Font::Default) # Tk::Tile::Style.map('TNotebook.Tab', Tk::Tile::Style.map($TNotebook_Tab, :background=>[:selected, '#FCB64F', '', '#FFE6BA'], :foreground=>['', 'black'], :padding=>[:selected, [10, 6, 10, 3]]) # Tk::Tile::Style.map('TScrollbar', Tk::Tile::Style.map(Tk::Tile::TScrollbar, :background=>[:pressed, '#694418'], :arrowcolor=>[:pressed, '#FEF7CB'], :relief=>[:pressed, :sunken]) # Tk::Tile::Style.layout('Vertical.TScrollbar', Tk::Tile::Style.layout(Tk::Tile.style('Vertical', Tk::Tile::TScrollbar), ['Scrollbar.trough', {:children=>[ 'Scrollbar.uparrow', {:side=>:top}, 'Scrollbar.downarrow', {:side=>:bottom}, 'Scrollbar.uparrow', {:side=>:bottom}, 'Scrollbar.thumb', {:side=>:top, :expand=>true} ]} ]) # Tk::Tile::Style.layout('Horizontal.TScrollbar', Tk::Tile::Style.layout(Tk::Tile.style('Horizontal', Tk::Tile::TScrollbar), ['Scrollbar.trough', {:children=>[ 'Scrollbar.leftarrow', {:side=>:left}, 'Scrollbar.rightarrow', {:side=>:right}, 'Scrollbar.leftarrow', {:side=>:right}, 'Scrollbar.thumb', {:side=>:left, :expand=>true} ]} ]) # # Elements: # if TkPackage.vcompare(Tk::Tile.package_version, '0.5') >= 0 Tk::Tile::Style.element_create('Button.button', :image, $images['button-n'], :map=>[ :pressed, $images['button-p'], :active, $images['button-h'], ], :border=>3, :sticky=>:ew) Tk::Tile::Style.element_create('Checkbutton.indicator', :image, $images['check-nu'], :map=>[ [:pressed, :selected],$images['check-nc'], :pressed, $images['check-nu'], [:active, :selected], $images['check-hc'], :active, $images['check-hu'], :selected, $images['check-nc'], ], :sticky=>:w) Tk::Tile::Style.element_create('Radiobutton.indicator', :image, $images['radio-nu'], :map=>[ [:pressed, :selected],$images['radio-nc'], :pressed, $images['radio-nu'], [:active, :selected], $images['radio-hc'], :active, $images['radio-hu'], :selected, $images['radio-nc'], ], :sticky=>:w) else # tile 0.4 or earlier Tk::Tile::Style.element_create('Button.button', :pixmap, :images=>[ :pressed, $images['button-p'], :active, $images['button-h'], '', $images['button-n'] ], :border=>3, :tiling=>:tile) Tk::Tile::Style.element_create('Checkbutton.indicator', :pixmap, :images=>[ [:pressed, :selected],$images['check-nc'], :pressed, $images['check-nu'], [:active, :selected], $images['check-hc'], :active, $images['check-hu'], :selected, $images['check-nc'], '', $images['check-nu'], ], :tiling=>:fixed) Tk::Tile::Style.element_create('Radiobutton.indicator', :pixmap, :images=>[ [:pressed, :selected],$images['radio-nc'], :pressed, $images['radio-nu'], [:active, :selected], $images['radio-hc'], :active, $images['radio-hu'], :selected, $images['radio-nc'], '', $images['radio-nu'], ], :tiling=>:fixed) end # # Settings: # # Tk::Tile::Style.layout(Tk::Tile::TButton, Tk::Tile::Style.layout('TButton', [ 'Button.button', {:children=>[ 'Button.focus', {:children=>[ 'Button.padding', {:children=>[ 'Button.label', {:expand=>true, :sticky=>''} ]} ]} ]} ]) # Tk::Tile::Style.layout(Tk::Tile::TCheckbutton, Tk::Tile::Style.layout('TCheckbutton', [ 'Checkbutton.background', # this is not needed in tile 0.5 or later 'Checkbutton.border', {:children=>[ 'Checkbutton.padding', {:children=>[ 'Checkbutton.indicator', {:side=>:left}, 'Checkbutton.focus', {:side=>:left, :children=>[ 'Checkbutton.label' ]} ]} ]} ]) # Tk::Tile::Style.layout(Tk::Tile::TRadiobutton, Tk::Tile::Style.layout('TRadiobutton', [ 'Radiobutton.background', # this is not needed in tile 0.5 or later 'Radiobutton.border', {:children=>[ 'Radiobutton.padding', {:children=>[ 'Radiobutton.indicator', {:side=>:left}, 'Radiobutton.focus', {:expand=>true, :sticky=>:w, :children=>[ 'Radiobutton.label', {:side=>:right, :expand=>true} ]} ]} ]} ]) end Tk::Tile::Style.theme_create('kroc-rb', :parent=>'alt', :settings=>proc{ kroc_rb_settings() })
bsd-3-clause
Dekken/tick
lib/cpp/array/alloc.cpp
140
// License: BSD 3 clause #include "tick/array/alloc.h" #if defined(DEBUG_C_ARRAY) DEBUGCAllocArrayCount_t DEBUGCAllocArrayCount; #endif
bsd-3-clause
zhaokunfay/ServiceStack.Examples
src/RestFiles/RestFiles.ServiceModel/RevertFiles.cs
847
using ServiceStack; namespace RestFiles.ServiceModel { /// <summary> /// Define your ServiceStack web service request (i.e. the Request DTO). /// </summary> [Route("/revertfiles")] public class RevertFiles { } /// <summary> /// Define your ServiceStack web service response (i.e. Response DTO). /// </summary> public class RevertFilesResponse : IHasResponseStatus { public RevertFilesResponse() { //Comment this out if you wish to receive the response status. this.ResponseStatus = new ResponseStatus(); } /// <summary> /// Gets or sets the ResponseStatus. The built-in Ioc used with ServiceStack autowires this property with service exceptions. /// </summary> public ResponseStatus ResponseStatus { get; set; } } }
bsd-3-clause
lcp0578/kitcmf
vendor/symfony/symfony/src/Symfony/Component/Serializer/Mapping/Factory/ClassResolverTrait.php
1245
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Serializer\Mapping\Factory; use Symfony\Component\Serializer\Exception\InvalidArgumentException; /** * Resolves a class name. * * @internal * * @author Kévin Dunglas <dunglas@gmail.com> */ trait ClassResolverTrait { /** * Gets a class name for a given class or instance. * * @param mixed $value * * @return string * * @throws InvalidArgumentException If the class does not exists */ private function getClass($value) { if (is_string($value)) { if (!class_exists($value) && !interface_exists($value)) { throw new InvalidArgumentException(sprintf('The class or interface "%s" does not exist.', $value)); } return ltrim($value, '\\'); } if (!is_object($value)) { throw new InvalidArgumentException(sprintf('Cannot create metadata for non-objects. Got: "%s"', gettype($value))); } return get_class($value); } }
mit