file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else | ;
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0,
XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen + 'static>> {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
}
| {
self.seq
} | conditional_block |
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else {
self.seq
};
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0,
XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen + 'static>> | {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
} | identifier_body | |
bad_transaction.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_universe::{AUTransactionGen, AccountUniverse},
common_transactions::{empty_txn, EMPTY_SCRIPT},
gas_costs,
};
use diem_crypto::{
ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey},
test_utils::KeyPair,
};
use diem_proptest_helpers::Index;
use diem_types::{
account_config::XUS_NAME,
transaction::{Script, SignedTransaction, TransactionStatus},
vm_status::StatusCode,
};
use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants};
use move_vm_types::gas_schedule::calculate_intrinsic_gas;
use proptest::prelude::*;
use proptest_derive::Arbitrary;
use std::sync::Arc;
/// Represents a sequence number mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct SequenceNumberMismatchGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
seq: u64,
}
impl AUTransactionGen for SequenceNumberMismatchGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let seq = if sender.sequence_number == self.seq {
self.seq + 1
} else {
self.seq
};
let txn = empty_txn(
sender.account(),
seq,
gas_costs::TXN_RESERVED,
0, | XUS_NAME.to_string(),
);
(
txn,
(
if seq >= sender.sequence_number {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW)
} else {
TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD)
},
0,
),
)
}
}
/// Represents a insufficient balance transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(params = "(u64, u64)")]
pub struct InsufficientBalanceGen {
sender: Index,
#[proptest(strategy = "params.0 ..= params.1")]
gas_unit_price: u64,
}
impl AUTransactionGen for InsufficientBalanceGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let max_gas_unit = (sender.balance / self.gas_unit_price) + 1;
let txn = empty_txn(
sender.account(),
sender.sequence_number,
max_gas_unit,
self.gas_unit_price,
XUS_NAME.to_string(),
);
// TODO: Move such config to AccountUniverse
let default_constants = GasConstants::default();
let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier);
let min_cost = GasConstants::default()
.to_external_units(calculate_intrinsic_gas(
raw_bytes_len,
&GasConstants::default(),
))
.get();
(
txn,
(
if max_gas_unit > default_constants.maximum_number_of_gas_units.get() {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND,
)
} else if max_gas_unit < min_cost {
TransactionStatus::Discard(
StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS,
)
} else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND)
} else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() {
TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND)
} else {
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE)
},
0,
),
)
}
}
/// Represents a authkey mismatch transaction
///
#[derive(Arbitrary, Clone, Debug)]
#[proptest(no_params)]
pub struct InvalidAuthkeyGen {
sender: Index,
#[proptest(strategy = "ed25519::keypair_strategy()")]
new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>,
}
impl AUTransactionGen for InvalidAuthkeyGen {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
let sender = universe.pick(self.sender).1;
let txn = sender
.account()
.transaction()
.script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![]))
.sequence_number(sender.sequence_number)
.raw()
.sign(
&self.new_keypair.private_key,
self.new_keypair.public_key.clone(),
)
.unwrap()
.into_inner();
(
txn,
(TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0),
)
}
}
pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen + 'static>> {
prop_oneof![
1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced),
1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced),
1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced),
]
} | random_line_split | |
ExpandRange.ts | import { Optional, Strings, Type } from '@ephox/katamari';
import DOMUtils from '../api/dom/DOMUtils';
import TextSeeker from '../api/dom/TextSeeker';
import Editor from '../api/Editor';
import * as Bookmarks from '../bookmark/Bookmarks';
import * as NodeType from '../dom/NodeType';
import * as RangeNodes from '../selection/RangeNodes';
import { RangeLikeObject } from '../selection/RangeTypes';
import { isContent, isNbsp, isWhiteSpace } from '../text/CharType';
import { Format } from './FormatTypes';
import * as FormatUtils from './FormatUtils';
type Sibling = 'previousSibling' | 'nextSibling';
const isBookmarkNode = Bookmarks.isBookmarkNode;
const getParents = FormatUtils.getParents;
const isWhiteSpaceNode = FormatUtils.isWhiteSpaceNode;
const isTextBlock = FormatUtils.isTextBlock;
const isBogusBr = (node: Node) => {
return NodeType.isBr(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
};
// Expands the node to the closes contentEditable false element if it exists
const findParentContentEditable = (dom: DOMUtils, node: Node) => {
let parent = node;
while (parent) {
if (NodeType.isElement(parent) && dom.getContentEditable(parent)) {
return dom.getContentEditable(parent) === 'false' ? parent : node;
}
parent = parent.parentNode;
}
return node;
};
const walkText = (start: boolean, node: Text, offset: number, predicate: (chr: string) => boolean) => {
const str = node.data;
for (let i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
if (predicate(str.charAt(i))) {
return start ? i + 1 : i;
}
}
return -1;
};
const findSpace = (start: boolean, node: Text, offset: number) =>
walkText(start, node, offset, (c) => isNbsp(c) || isWhiteSpace(c));
const findContent = (start: boolean, node: Text, offset: number) =>
walkText(start, node, offset, isContent);
const findWordEndPoint = (
dom: DOMUtils,
body: HTMLElement,
container: Node,
offset: number,
start: boolean,
includeTrailingSpaces: boolean
) => {
let lastTextNode: Text;
const rootNode = dom.getParent(container, dom.isBlock) || body;
const walk = (container: Node, offset: number, pred: (start: boolean, node: Text, offset?: number) => number) => {
const textSeeker = TextSeeker(dom);
const walker = start ? textSeeker.backwards : textSeeker.forwards;
return Optional.from(walker(container, offset, (text, textOffset) => {
if (isBookmarkNode(text.parentNode)) {
return -1;
} else {
lastTextNode = text;
return pred(start, text, textOffset);
}
}, rootNode));
};
const spaceResult = walk(container, offset, findSpace);
return spaceResult.bind(
(result) => includeTrailingSpaces ?
walk(result.container, result.offset + (start ? -1 : 0), findContent) :
Optional.some(result)
).orThunk(
() => lastTextNode ?
Optional.some({ container: lastTextNode, offset: start ? 0 : lastTextNode.length }) :
Optional.none()
);
};
const findSelectorEndPoint = (dom: DOMUtils, formatList: Format[], rng: Range, container: Node, siblingName: Sibling) => {
if (NodeType.isText(container) && Strings.isEmpty(container.data) && container[siblingName]) {
container = container[siblingName];
}
const parents = getParents(dom, container);
for (let i = 0; i < parents.length; i++) {
for (let y = 0; y < formatList.length; y++) {
const curFormat = formatList[y];
// If collapsed state is set then skip formats that doesn't match that
if (Type.isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
continue;
}
if (FormatUtils.isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
return parents[i];
}
}
}
return container;
};
const findBlockEndPoint = (editor: Editor, formatList: Format[], container: Node, siblingName: Sibling) => {
let node: Node | null = container;
const dom = editor.dom;
const root = dom.getRoot();
const format = formatList[0];
// Expand to block of similar type
if (FormatUtils.isBlockFormat(format)) |
// Expand to first wrappable block element or any block element
if (!node) {
const scopeRoot = dom.getParent(container, 'LI,TD,TH');
node = dom.getParent(
NodeType.isText(container) ? container.parentNode : container,
// Fixes #6183 where it would expand to editable parent element in inline mode
(node) => node !== root && isTextBlock(editor, node),
scopeRoot
);
}
// Exclude inner lists from wrapping
if (node && FormatUtils.isBlockFormat(format) && format.wrapper) {
node = getParents(dom, node, 'ul,ol').reverse()[0] || node;
}
// Didn't find a block element look for first/last wrappable element
if (!node) {
node = container;
while (node[siblingName] && !dom.isBlock(node[siblingName])) {
node = node[siblingName];
// Break on BR but include it will be removed later on
// we can't remove it now since we need to check if it can be wrapped
if (FormatUtils.isEq(node, 'br')) {
break;
}
}
}
return node || container;
};
// We're at the edge if the parent is a block and there's no next sibling. Alternatively,
// if we reach the root or can't walk further we also consider it to be a boundary.
const isAtBlockBoundary = (dom: DOMUtils, root: Node, container: Node, siblingName: Sibling) => {
const parent = container.parentNode;
if (Type.isNonNullable(container[siblingName])) {
return false;
} else if (parent === root || Type.isNullable(parent) || dom.isBlock(parent)) {
return true;
} else {
return isAtBlockBoundary(dom, root, parent, siblingName);
}
};
// This function walks up the tree if there is no siblings before/after the node.
// If a sibling is found then the container is returned
const findParentContainer = (
dom: DOMUtils,
formatList: Format[],
container: Node,
offset: number,
start: boolean
) => {
let parent = container;
const siblingName = start ? 'previousSibling' : 'nextSibling';
const root = dom.getRoot();
// If it's a text node and the offset is inside the text
if (NodeType.isText(container) && !isWhiteSpaceNode(container)) {
if (start ? offset > 0 : offset < container.data.length) {
return container;
}
}
/* eslint no-constant-condition:0 */
while (true) {
// Stop expanding on block elements
if (!formatList[0].block_expand && dom.isBlock(parent)) {
return parent;
}
// Walk left/right
for (let sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
// Allow spaces if not at the edge of a block element, as the spaces won't have been collapsed
const allowSpaces = NodeType.isText(sibling) && !isAtBlockBoundary(dom, root, sibling, siblingName);
if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
return parent;
}
}
// Check if we can move up are we at root level or body level
if (parent === root || parent.parentNode === root) {
container = parent;
break;
}
parent = parent.parentNode;
}
return container;
};
const isSelfOrParentBookmark = (container: Node) => isBookmarkNode(container.parentNode) || isBookmarkNode(container);
const expandRng = (editor: Editor, rng: Range, formatList: Format[], includeTrailingSpace: boolean = false): RangeLikeObject => {
let { startContainer, startOffset, endContainer, endOffset } = rng;
const dom = editor.dom;
const format = formatList[0];
// If index based start position then resolve it
if (NodeType.isElement(startContainer) && startContainer.hasChildNodes()) {
startContainer = RangeNodes.getNode(startContainer, startOffset);
if (NodeType.isText(startContainer)) {
startOffset = 0;
}
}
// If index based end position then resolve it
if (NodeType.isElement(endContainer) && endContainer.hasChildNodes()) {
endContainer = RangeNodes.getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
if (NodeType.isText(endContainer)) {
endOffset = endContainer.nodeValue.length;
}
}
// Expand to closest contentEditable element
startContainer = findParentContentEditable(dom, startContainer);
endContainer = findParentContentEditable(dom, endContainer);
// Exclude bookmark nodes if possible
if (isSelfOrParentBookmark(startContainer)) {
startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
if (rng.collapsed) {
startContainer = startContainer.previousSibling || startContainer;
} else {
startContainer = startContainer.nextSibling || startContainer;
}
if (NodeType.isText(startContainer)) {
startOffset = rng.collapsed ? startContainer.length : 0;
}
}
if (isSelfOrParentBookmark(endContainer)) {
endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
if (rng.collapsed) {
endContainer = endContainer.nextSibling || endContainer;
} else {
endContainer = endContainer.previousSibling || endContainer;
}
if (NodeType.isText(endContainer)) {
endOffset = rng.collapsed ? 0 : endContainer.length;
}
}
if (rng.collapsed) {
// Expand left to closest word boundary
const startPoint = findWordEndPoint(
dom,
editor.getBody(),
startContainer,
startOffset,
true,
includeTrailingSpace
);
startPoint.each(({ container, offset }) => {
startContainer = container;
startOffset = offset;
});
// Expand right to closest word boundary
const endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
endPoint.each(({ container, offset }) => {
endContainer = container;
endOffset = offset;
});
}
// Move start/end point up the tree if the leaves are sharp and if we are in different containers
// Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
// This will reduce the number of wrapper elements that needs to be created
// Move start point up the tree
if (FormatUtils.isInlineFormat(format) || format.block_expand) {
if (!FormatUtils.isInlineFormat(format) || (!NodeType.isText(startContainer) || startOffset === 0)) {
startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
}
if (!FormatUtils.isInlineFormat(format) || (!NodeType.isText(endContainer) || endOffset === endContainer.nodeValue.length)) {
endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
}
}
// Expand start/end container to matching selector
if (FormatUtils.shouldExpandToSelector(format)) {
// Find new startContainer/endContainer if there is better one
startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
}
// Expand start/end container to matching block element or text node
if (FormatUtils.isBlockFormat(format) || FormatUtils.isSelectorFormat(format)) {
// Find new startContainer/endContainer if there is better one
startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
// Non block element then try to expand up the leaf
if (FormatUtils.isBlockFormat(format)) {
if (!dom.isBlock(startContainer)) {
startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
}
if (!dom.isBlock(endContainer)) {
endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
}
}
}
// Setup index for startContainer
if (NodeType.isElement(startContainer)) {
startOffset = dom.nodeIndex(startContainer);
startContainer = startContainer.parentNode;
}
// Setup index for endContainer
if (NodeType.isElement(endContainer)) {
endOffset = dom.nodeIndex(endContainer) + 1;
endContainer = endContainer.parentNode;
}
// Return new range like object
return {
startContainer,
startOffset,
endContainer,
endOffset
};
};
export {
expandRng
};
| {
node = format.wrapper ? null : dom.getParent(container, format.block, root);
} | conditional_block |
ExpandRange.ts | import { Optional, Strings, Type } from '@ephox/katamari';
import DOMUtils from '../api/dom/DOMUtils';
import TextSeeker from '../api/dom/TextSeeker';
import Editor from '../api/Editor';
import * as Bookmarks from '../bookmark/Bookmarks';
import * as NodeType from '../dom/NodeType';
import * as RangeNodes from '../selection/RangeNodes';
import { RangeLikeObject } from '../selection/RangeTypes';
import { isContent, isNbsp, isWhiteSpace } from '../text/CharType';
import { Format } from './FormatTypes';
import * as FormatUtils from './FormatUtils';
type Sibling = 'previousSibling' | 'nextSibling';
const isBookmarkNode = Bookmarks.isBookmarkNode;
const getParents = FormatUtils.getParents;
const isWhiteSpaceNode = FormatUtils.isWhiteSpaceNode;
const isTextBlock = FormatUtils.isTextBlock;
const isBogusBr = (node: Node) => {
return NodeType.isBr(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
};
// Expands the node to the closes contentEditable false element if it exists
const findParentContentEditable = (dom: DOMUtils, node: Node) => {
let parent = node;
while (parent) {
if (NodeType.isElement(parent) && dom.getContentEditable(parent)) {
return dom.getContentEditable(parent) === 'false' ? parent : node;
}
parent = parent.parentNode;
}
return node;
};
const walkText = (start: boolean, node: Text, offset: number, predicate: (chr: string) => boolean) => {
const str = node.data;
for (let i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
if (predicate(str.charAt(i))) {
return start ? i + 1 : i;
}
}
return -1;
};
const findSpace = (start: boolean, node: Text, offset: number) =>
walkText(start, node, offset, (c) => isNbsp(c) || isWhiteSpace(c));
const findContent = (start: boolean, node: Text, offset: number) =>
walkText(start, node, offset, isContent);
const findWordEndPoint = (
dom: DOMUtils,
body: HTMLElement,
container: Node,
offset: number,
start: boolean,
includeTrailingSpaces: boolean
) => {
let lastTextNode: Text;
const rootNode = dom.getParent(container, dom.isBlock) || body;
const walk = (container: Node, offset: number, pred: (start: boolean, node: Text, offset?: number) => number) => {
const textSeeker = TextSeeker(dom);
const walker = start ? textSeeker.backwards : textSeeker.forwards;
return Optional.from(walker(container, offset, (text, textOffset) => {
if (isBookmarkNode(text.parentNode)) {
return -1;
} else {
lastTextNode = text;
return pred(start, text, textOffset);
}
}, rootNode));
};
const spaceResult = walk(container, offset, findSpace);
return spaceResult.bind(
(result) => includeTrailingSpaces ?
walk(result.container, result.offset + (start ? -1 : 0), findContent) :
Optional.some(result)
).orThunk(
() => lastTextNode ?
Optional.some({ container: lastTextNode, offset: start ? 0 : lastTextNode.length }) :
Optional.none()
);
};
const findSelectorEndPoint = (dom: DOMUtils, formatList: Format[], rng: Range, container: Node, siblingName: Sibling) => {
if (NodeType.isText(container) && Strings.isEmpty(container.data) && container[siblingName]) {
container = container[siblingName];
}
const parents = getParents(dom, container);
for (let i = 0; i < parents.length; i++) {
for (let y = 0; y < formatList.length; y++) {
const curFormat = formatList[y];
// If collapsed state is set then skip formats that doesn't match that
if (Type.isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
continue;
}
if (FormatUtils.isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
return parents[i];
}
}
}
return container;
};
const findBlockEndPoint = (editor: Editor, formatList: Format[], container: Node, siblingName: Sibling) => {
let node: Node | null = container;
const dom = editor.dom;
const root = dom.getRoot();
const format = formatList[0];
// Expand to block of similar type
if (FormatUtils.isBlockFormat(format)) {
node = format.wrapper ? null : dom.getParent(container, format.block, root);
}
// Expand to first wrappable block element or any block element
if (!node) {
const scopeRoot = dom.getParent(container, 'LI,TD,TH');
node = dom.getParent(
NodeType.isText(container) ? container.parentNode : container,
// Fixes #6183 where it would expand to editable parent element in inline mode
(node) => node !== root && isTextBlock(editor, node),
scopeRoot
);
}
// Exclude inner lists from wrapping
if (node && FormatUtils.isBlockFormat(format) && format.wrapper) {
node = getParents(dom, node, 'ul,ol').reverse()[0] || node;
}
// Didn't find a block element look for first/last wrappable element
if (!node) {
node = container;
while (node[siblingName] && !dom.isBlock(node[siblingName])) {
node = node[siblingName];
// Break on BR but include it will be removed later on
// we can't remove it now since we need to check if it can be wrapped
if (FormatUtils.isEq(node, 'br')) {
break;
}
}
}
return node || container;
};
// We're at the edge if the parent is a block and there's no next sibling. Alternatively,
// if we reach the root or can't walk further we also consider it to be a boundary.
const isAtBlockBoundary = (dom: DOMUtils, root: Node, container: Node, siblingName: Sibling) => {
const parent = container.parentNode;
if (Type.isNonNullable(container[siblingName])) {
return false;
} else if (parent === root || Type.isNullable(parent) || dom.isBlock(parent)) {
return true;
} else {
return isAtBlockBoundary(dom, root, parent, siblingName);
}
};
// This function walks up the tree if there is no siblings before/after the node.
// If a sibling is found then the container is returned
const findParentContainer = (
dom: DOMUtils,
formatList: Format[],
container: Node,
offset: number,
start: boolean
) => {
let parent = container;
const siblingName = start ? 'previousSibling' : 'nextSibling';
const root = dom.getRoot();
// If it's a text node and the offset is inside the text
if (NodeType.isText(container) && !isWhiteSpaceNode(container)) {
if (start ? offset > 0 : offset < container.data.length) {
return container;
}
}
/* eslint no-constant-condition:0 */
while (true) {
// Stop expanding on block elements
if (!formatList[0].block_expand && dom.isBlock(parent)) {
return parent;
}
// Walk left/right
for (let sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
// Allow spaces if not at the edge of a block element, as the spaces won't have been collapsed
const allowSpaces = NodeType.isText(sibling) && !isAtBlockBoundary(dom, root, sibling, siblingName);
if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
return parent;
}
}
// Check if we can move up are we at root level or body level
if (parent === root || parent.parentNode === root) {
container = parent;
break;
}
parent = parent.parentNode;
}
return container;
};
const isSelfOrParentBookmark = (container: Node) => isBookmarkNode(container.parentNode) || isBookmarkNode(container);
const expandRng = (editor: Editor, rng: Range, formatList: Format[], includeTrailingSpace: boolean = false): RangeLikeObject => {
let { startContainer, startOffset, endContainer, endOffset } = rng;
const dom = editor.dom;
const format = formatList[0];
// If index based start position then resolve it
if (NodeType.isElement(startContainer) && startContainer.hasChildNodes()) {
startContainer = RangeNodes.getNode(startContainer, startOffset);
if (NodeType.isText(startContainer)) {
startOffset = 0;
}
}
| }
}
// Expand to closest contentEditable element
startContainer = findParentContentEditable(dom, startContainer);
endContainer = findParentContentEditable(dom, endContainer);
// Exclude bookmark nodes if possible
if (isSelfOrParentBookmark(startContainer)) {
startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
if (rng.collapsed) {
startContainer = startContainer.previousSibling || startContainer;
} else {
startContainer = startContainer.nextSibling || startContainer;
}
if (NodeType.isText(startContainer)) {
startOffset = rng.collapsed ? startContainer.length : 0;
}
}
if (isSelfOrParentBookmark(endContainer)) {
endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
if (rng.collapsed) {
endContainer = endContainer.nextSibling || endContainer;
} else {
endContainer = endContainer.previousSibling || endContainer;
}
if (NodeType.isText(endContainer)) {
endOffset = rng.collapsed ? 0 : endContainer.length;
}
}
if (rng.collapsed) {
// Expand left to closest word boundary
const startPoint = findWordEndPoint(
dom,
editor.getBody(),
startContainer,
startOffset,
true,
includeTrailingSpace
);
startPoint.each(({ container, offset }) => {
startContainer = container;
startOffset = offset;
});
// Expand right to closest word boundary
const endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
endPoint.each(({ container, offset }) => {
endContainer = container;
endOffset = offset;
});
}
// Move start/end point up the tree if the leaves are sharp and if we are in different containers
// Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
// This will reduce the number of wrapper elements that needs to be created
// Move start point up the tree
if (FormatUtils.isInlineFormat(format) || format.block_expand) {
if (!FormatUtils.isInlineFormat(format) || (!NodeType.isText(startContainer) || startOffset === 0)) {
startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
}
if (!FormatUtils.isInlineFormat(format) || (!NodeType.isText(endContainer) || endOffset === endContainer.nodeValue.length)) {
endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
}
}
// Expand start/end container to matching selector
if (FormatUtils.shouldExpandToSelector(format)) {
// Find new startContainer/endContainer if there is better one
startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
}
// Expand start/end container to matching block element or text node
if (FormatUtils.isBlockFormat(format) || FormatUtils.isSelectorFormat(format)) {
// Find new startContainer/endContainer if there is better one
startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
// Non block element then try to expand up the leaf
if (FormatUtils.isBlockFormat(format)) {
if (!dom.isBlock(startContainer)) {
startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
}
if (!dom.isBlock(endContainer)) {
endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
}
}
}
// Setup index for startContainer
if (NodeType.isElement(startContainer)) {
startOffset = dom.nodeIndex(startContainer);
startContainer = startContainer.parentNode;
}
// Setup index for endContainer
if (NodeType.isElement(endContainer)) {
endOffset = dom.nodeIndex(endContainer) + 1;
endContainer = endContainer.parentNode;
}
// Return new range like object
return {
startContainer,
startOffset,
endContainer,
endOffset
};
};
export {
expandRng
}; | // If index based end position then resolve it
if (NodeType.isElement(endContainer) && endContainer.hasChildNodes()) {
endContainer = RangeNodes.getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
if (NodeType.isText(endContainer)) {
endOffset = endContainer.nodeValue.length; | random_line_split |
index.module.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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.
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core'; | import { AddonModUrlIndexPage } from './index';
@NgModule({
declarations: [
AddonModUrlIndexPage,
],
imports: [
CoreDirectivesModule,
AddonModUrlComponentsModule,
IonicPageModule.forChild(AddonModUrlIndexPage),
TranslateModule.forChild()
],
})
export class AddonModUrlIndexPageModule {} | import { CoreDirectivesModule } from '@directives/directives.module';
import { AddonModUrlComponentsModule } from '../../components/components.module'; | random_line_split |
index.module.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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.
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core';
import { CoreDirectivesModule } from '@directives/directives.module';
import { AddonModUrlComponentsModule } from '../../components/components.module';
import { AddonModUrlIndexPage } from './index';
@NgModule({
declarations: [
AddonModUrlIndexPage,
],
imports: [
CoreDirectivesModule,
AddonModUrlComponentsModule,
IonicPageModule.forChild(AddonModUrlIndexPage),
TranslateModule.forChild()
],
})
export class | {}
| AddonModUrlIndexPageModule | identifier_name |
app.component.ts | import { Component, HostListener, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Params, Router, NavigationEnd } from '@angular/router';
import { AppState } from './app.service';
import { AppStore } from './app.store';
import { AuthService } from './user/auth.service';
import { User } from './user/user/user.service';
import { TinCanService } from './tincan/tincan.service';
import { MatIconRegistry } from '@angular/material';
import { APIService } from './shared/services/api.service';
import * as _ from 'underscore';
@Component({
selector: 'app',
styleUrls: [
'./app.component.scss', "../assets/scss/hsa-theme.scss"
],
templateUrl: './app.component.html',
encapsulation : ViewEncapsulation.None
}) | export class AppComponent implements OnInit{
angularclassLogo = 'assets/img/pa_logo.png';
name = 'peer activate';
url = 'https://github.com/leChuckles/PeerActivate';
//@HostListener('window:beforeunload', [ '$event' ])
//beforeUnloadHander(event) {
//this.setUnload();
//}
constructor(private api : APIService, public appState: AppState, public authService: AuthService, public route: ActivatedRoute, public router : Router, public store : AppStore, public tinCanService : TinCanService, public MatIconRegistry : MatIconRegistry) {
MatIconRegistry.registerFontClassAlias('materialdesignicons-webfont', 'mat-custom-icons');
}
setUnload(){
this.tinCanService.makeStatement()
.subscribe(res => res)
/*this.authService.setLogout()
.subscribe(res => res)*/
}
ngOnInit() {
console.log('START')
//this.startSession();
this.api.findOne({'username' : this.authService.getUser().username}, 'user')
.subscribe((user : User) => {
console.log('USER: ', this.authService.getUser().username, user)
this.store.setState({user : user});
})
}
startSession(){
this.appState.set('session', {
session_id : Date.now(),
statements : []
});
}
} | random_line_split | |
app.component.ts | import { Component, HostListener, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Params, Router, NavigationEnd } from '@angular/router';
import { AppState } from './app.service';
import { AppStore } from './app.store';
import { AuthService } from './user/auth.service';
import { User } from './user/user/user.service';
import { TinCanService } from './tincan/tincan.service';
import { MatIconRegistry } from '@angular/material';
import { APIService } from './shared/services/api.service';
import * as _ from 'underscore';
@Component({
selector: 'app',
styleUrls: [
'./app.component.scss', "../assets/scss/hsa-theme.scss"
],
templateUrl: './app.component.html',
encapsulation : ViewEncapsulation.None
})
export class AppComponent implements OnInit{
angularclassLogo = 'assets/img/pa_logo.png';
name = 'peer activate';
url = 'https://github.com/leChuckles/PeerActivate';
//@HostListener('window:beforeunload', [ '$event' ])
//beforeUnloadHander(event) {
//this.setUnload();
//}
constructor(private api : APIService, public appState: AppState, public authService: AuthService, public route: ActivatedRoute, public router : Router, public store : AppStore, public tinCanService : TinCanService, public MatIconRegistry : MatIconRegistry) {
MatIconRegistry.registerFontClassAlias('materialdesignicons-webfont', 'mat-custom-icons');
}
setUnload(){
this.tinCanService.makeStatement()
.subscribe(res => res)
/*this.authService.setLogout()
.subscribe(res => res)*/
}
ngOnInit() |
startSession(){
this.appState.set('session', {
session_id : Date.now(),
statements : []
});
}
} | {
console.log('START')
//this.startSession();
this.api.findOne({'username' : this.authService.getUser().username}, 'user')
.subscribe((user : User) => {
console.log('USER: ', this.authService.getUser().username, user)
this.store.setState({user : user});
})
} | identifier_body |
app.component.ts | import { Component, HostListener, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Params, Router, NavigationEnd } from '@angular/router';
import { AppState } from './app.service';
import { AppStore } from './app.store';
import { AuthService } from './user/auth.service';
import { User } from './user/user/user.service';
import { TinCanService } from './tincan/tincan.service';
import { MatIconRegistry } from '@angular/material';
import { APIService } from './shared/services/api.service';
import * as _ from 'underscore';
@Component({
selector: 'app',
styleUrls: [
'./app.component.scss', "../assets/scss/hsa-theme.scss"
],
templateUrl: './app.component.html',
encapsulation : ViewEncapsulation.None
})
export class AppComponent implements OnInit{
angularclassLogo = 'assets/img/pa_logo.png';
name = 'peer activate';
url = 'https://github.com/leChuckles/PeerActivate';
//@HostListener('window:beforeunload', [ '$event' ])
//beforeUnloadHander(event) {
//this.setUnload();
//}
| (private api : APIService, public appState: AppState, public authService: AuthService, public route: ActivatedRoute, public router : Router, public store : AppStore, public tinCanService : TinCanService, public MatIconRegistry : MatIconRegistry) {
MatIconRegistry.registerFontClassAlias('materialdesignicons-webfont', 'mat-custom-icons');
}
setUnload(){
this.tinCanService.makeStatement()
.subscribe(res => res)
/*this.authService.setLogout()
.subscribe(res => res)*/
}
ngOnInit() {
console.log('START')
//this.startSession();
this.api.findOne({'username' : this.authService.getUser().username}, 'user')
.subscribe((user : User) => {
console.log('USER: ', this.authService.getUser().username, user)
this.store.setState({user : user});
})
}
startSession(){
this.appState.set('session', {
session_id : Date.now(),
statements : []
});
}
} | constructor | identifier_name |
test_data.ts | import { ChangelistsResponse } from '../rpc_types';
export const fakeNow = Date.parse('2019-09-09T19:32:30Z');
export const changelistSummaries_5: ChangelistsResponse = {
changelists: [
{
system: 'gerrit',
id: '1788313', | url: 'https://chromium-review.googlesource.com/1788313',
},
{
system: 'gerrit',
id: '1787403',
owner: 'beta-autoroll@example.iam.gserviceaccount.com',
status: 'Open',
subject: 'Convert AssociatedInterfacePtr to AssociatedRemote in chrome/b/android',
updated: '2019-09-09T19:30:41Z',
url: 'https://chromium-review.googlesource.com/1787403',
},
{
system: 'gerrit',
id: '1788259',
owner: 'gamma@example.org',
status: 'Open',
subject:
'Implement deep content compliance and malware scans for uploads. '
+ 'This is a really long subject, like wow! '
+ "I hope the web UI doesn't mishandle this massively long subject",
updated: '2019-09-09T19:28:54Z',
url: 'https://chromium-review.googlesource.com/1788259',
},
{
system: 'gerrit',
id: '1792459',
owner: 'delta@example.org',
status: 'Abandoned',
subject: 'Remove unneeded SurfaceSync CHECK',
updated: '2019-09-09T19:26:25Z',
url: 'https://chromium-review.googlesource.com/1792459',
},
{
system: 'gerrit',
id: '1790066',
owner: 'epsilon@example.com',
status: 'Landed',
subject: 'Performance improvement for ITextRangeProvider::GetEnclosingElement',
updated: '2019-09-09T19:24:10Z',
url: 'https://chromium-review.googlesource.com/1790066',
},
],
offset: 0,
size: 5,
total: 2147483647,
};
export const changelistSummaries_5_offset5 = {
changelists: [
{
system: 'gerrit',
id: '1806853',
owner: 'zeta@example.org',
status: 'Open',
subject: 'Fix cursor in <pin-keyboard> on taps after keybrd',
updated: '2019-09-09T18:12:34Z',
url: 'https://chromium-review.googlesource.com/1806853',
},
{
system: 'gerrit',
id: '1790204',
owner: 'eta@example.com',
status: 'Open',
subject: 'Replaced WrapUnique with make_unique in components/',
updated: '2019-09-09T17:12:34Z',
url: 'https://chromium-review.googlesource.com/1790204',
},
{
system: 'gerrit',
id: '1787402',
owner: 'theta@example.org',
status: 'Open',
subject: 'Use an Omaha-style GUID app ID for updater self-updates.',
updated: '2019-09-09T16:12:34Z',
url: 'https://chromium-review.googlesource.com/1787402',
},
{
system: 'gerrit',
id: '1804242',
owner: 'iota@example.org',
status: 'Abandoned',
subject: 'Register CUS paths on ios.',
updated: '2019-09-09T15:12:34Z',
url: 'https://chromium-review.googlesource.com/1804242',
},
{
system: 'gerrit',
id: '1804507',
owner: 'kappa@example.com',
status: 'Landed',
subject: "PM: Don't use mojo for UKM no more.",
updated: '2019-09-09T14:12:34Z',
url: 'https://chromium-review.googlesource.com/1804507',
},
],
offset: 5,
size: 5,
total: 2147483647,
};
export const changelistSummaries_5_offset10: ChangelistsResponse = {
changelists: [
{
system: 'gerrit',
id: '1793168',
owner: 'lambda@example.org',
status: 'Open',
subject: 'Validate scanned card number',
updated: '2019-09-09T13:12:34Z',
url: 'https://chromium-review.googlesource.com/1793168',
},
{
system: 'gerrit',
id: '1805865',
owner: 'mu@example.com',
status: 'Open',
subject: 'Update SkiaRenderer BrowserTests Filter',
updated: '2019-09-09T12:12:34Z',
url: 'https://chromium-review.googlesource.com/1805865',
},
{
system: 'gerrit',
id: '1798703',
owner: 'nu@example.org',
status: 'Open',
subject: '[IOS] Pass dispatcher to CardMediator',
updated: '2019-09-09T11:12:34Z',
url: 'https://chromium-review.googlesource.com/1798703',
},
{
system: 'gerrit',
id: '1805862',
owner: 'xi@example.org',
status: 'Abandoned',
subject: 'Updating XTBs based on .GRDs from branch master',
updated: '2019-09-09T10:12:34Z',
url: 'https://chromium-review.googlesource.com/1805862',
},
{
system: 'gerrit',
id: '1805646',
owner: 'omicron@example.com',
status: 'Landed',
subject: '[Sheriff] Disable UkmBrowserTest.EvictObsoleteSources',
updated: '2019-09-09T09:12:34Z',
url: 'https://chromium-review.googlesource.com/1805646',
},
],
offset: 10,
size: 5,
total: 2147483647,
};
export const empty = (partial?: Partial<ChangelistsResponse>): ChangelistsResponse => ({
changelists: null,
offset: partial?.offset || 0,
size: partial?.size || 5,
total: partial?.total || 2147483647,
}); | owner: 'alpha@example.org',
status: 'Open',
subject: '[omnibox] Add flag to preserve the default match against async updates',
updated: '2019-09-09T19:31:14Z', | random_line_split |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn | (ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
| realloc_raw | identifier_name |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 |
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
| {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
} | identifier_body |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8 | } | } | random_line_split |
libc_heap.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The global (exchange) heap.
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, null_mut};
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html
if size == 0 {
null_mut()
} else {
let p = malloc(size as size_t);
if p.is_null() {
::oom();
}
p as *mut u8
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
if size == 0 {
free(ptr as *mut c_void);
null_mut()
} else {
let p = realloc(ptr as *mut c_void, size as size_t);
if p.is_null() |
p as *mut u8
}
}
| {
::oom();
} | conditional_block |
mmv.ui.reuse.dialog.js | /*
* This file is part of the MediaWiki extension MultimediaViewer.
*
* MultimediaViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MultimediaViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultimediaViewer. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
// Shortcut for prototype later
var DP;
/**
* Represents the file reuse dialog and the link to open it.
*
* @class mw.mmv.ui.reuse.Dialog
* @extends mw.mmv.ui.Element
* @param {jQuery} $container the element to which the dialog will be appended
* @param {jQuery} $openButton the button which opens the dialog. Only used for positioning.
* @param {mw.mmv.Config} config
*/
function Dialog( $container, $openButton, config ) {
mw.mmv.ui.Dialog.call( this, $container, $openButton, config );
/**
* @property {Object.<string, mw.mmv.ui.Element>} tabs List of tab ui objects.
*/
this.tabs = null;
/**
* @property {Object.<string, OO.ui.MenuOptionWidget>} ooTabs List of tab OOUI objects.
*/
this.ooTabs = null;
this.loadDependencies.push( 'mmv.ui.reuse.shareembed' );
this.$dialog.addClass( 'mw-mmv-reuse-dialog' );
this.eventPrefix = 'use-this-file';
}
OO.inheritClass( Dialog, mw.mmv.ui.Dialog );
DP = Dialog.prototype;
// FIXME this should happen outside the dialog and the tabs, but we need to improve
DP.initTabs = function () {
function makeTab( type ) {
return new OO.ui.MenuOptionWidget( {
data: type,
label: mw.message( 'multimediaviewer-' + type + '-tab' ).text()
} );
}
this.reuseTabs = new OO.ui.MenuSelectWidget( {
autoHide: false,
classes: [ 'mw-mmv-reuse-tabs' ]
} );
this.reuseTabs.$element.appendTo( this.$dialog );
this.tabs = {
share: new mw.mmv.ui.reuse.Share( this.$dialog ),
embed: new mw.mmv.ui.reuse.Embed( this.$dialog )
};
this.ooTabs = {
share: makeTab( 'share' ),
embed: makeTab( 'embed' )
};
this.reuseTabs.addItems( [
this.ooTabs.share,
this.ooTabs.embed
] );
// MenuSelectWidget has a nasty tendency to hide itself, maybe we're not using it right?
this.reuseTabs.toggle( true );
this.reuseTabs.toggle = function () {};
this.selectedTab = this.getLastUsedTab();
// In case nothing is saved in localStorage or it contains junk
if ( !Object.prototype.hasOwnProperty.call( this.tabs, this.selectedTab ) ) {
this.selectedTab = 'share';
}
this.reuseTabs.selectItem( this.ooTabs[ this.selectedTab ] );
if ( this.dependenciesNeedToBeAttached ) {
this.attachDependencies();
}
if ( this.tabsSetValues ) {
// This is a delayed set() for the elements we've just created on demand
this.tabs.share.set.apply( this.tabs.share, this.tabsSetValues.share );
this.tabs.embed.set.apply( this.tabs.embed, this.tabsSetValues.embed );
this.showImageWarnings( this.tabsSetValues.share[ 0 ] );
this.tabsSetValues = undefined;
}
};
DP.toggleDialog = function () {
if ( this.tabs === null ) {
this.initTabs();
}
mw.mmv.ui.Dialog.prototype.toggleDialog.call( this );
};
/**
* Handles tab selection.
*
* @param {OO.ui.MenuOptionWidget} option
*/
DP.handleTabSelection = function ( option ) {
var tab;
this.selectedTab = option.getData();
for ( tab in this.tabs ) {
if ( tab === this.selectedTab ) {
this.tabs[ tab ].show();
} else {
this.tabs[ tab ].hide();
}
}
this.config.setInLocalStorage( 'mmv-lastUsedTab', this.selectedTab );
};
/**
* @return {string} Last used tab
*/
DP.getLastUsedTab = function () {
return this.config.getFromLocalStorage( 'mmv-lastUsedTab' );
};
/**
* Registers listeners.
*/
DP.attach = function () {
this.handleEvent( 'mmv-reuse-open', this.handleOpenCloseClick.bind( this ) );
| };
/**
* Registrers listeners for dependencies loaded on demand
*/
DP.attachDependencies = function () {
var tab, dialog = this;
if ( this.reuseTabs && this.tabs ) {
// This is a delayed attach() for the elements we've just created on demand
this.reuseTabs.on( 'select', dialog.handleTabSelection.bind( dialog ) );
for ( tab in this.tabs ) {
this.tabs[ tab ].attach();
}
this.dependenciesNeedToBeAttached = false;
} else {
this.dependenciesNeedToBeAttached = true;
}
};
/**
* Clears listeners.
*/
DP.unattach = function () {
var tab;
mw.mmv.ui.Dialog.prototype.unattach.call( this );
if ( this.reuseTabs ) {
this.reuseTabs.off( 'select' );
}
if ( this.tabs ) {
for ( tab in this.tabs ) {
this.tabs[ tab ].unattach();
}
}
};
/**
* Sets data needed by contaned tabs and makes dialog launch link visible.
*
* @param {mw.mmv.model.Image} image
* @param {mw.mmv.model.Repo} repo
* @param {string} caption
* @param {string} alt
*/
DP.set = function ( image, repo, caption, alt ) {
if ( this.tabs !== null ) {
this.tabs.share.set( image );
this.tabs.embed.set( image, repo, caption, alt );
this.tabs.embed.set( image, repo, caption );
this.showImageWarnings( image );
} else {
this.tabsSetValues = {
share: [ image ],
embed: [ image, repo, caption, alt ]
};
}
};
/**
* @inheritdoc
*/
DP.empty = function () {
var tab;
mw.mmv.ui.Dialog.prototype.empty.call( this );
for ( tab in this.tabs ) {
this.tabs[ tab ].empty();
}
};
/**
* @event mmv-reuse-opened
* Fired when the dialog is opened.
*/
/**
* Opens a dialog with information about file reuse.
*/
DP.openDialog = function () {
mw.mmv.ui.Dialog.prototype.openDialog.call( this );
// move warnings after the tabs
this.$warning.insertAfter( this.reuseTabs.$element );
this.tabs[ this.selectedTab ].show();
$( document ).trigger( 'mmv-reuse-opened' );
};
/**
* @event mmv-reuse-closed
* Fired when the dialog is closed.
*/
/**
* Closes the reuse dialog.
*/
DP.closeDialog = function () {
mw.mmv.ui.Dialog.prototype.closeDialog.call( this );
$( document ).trigger( 'mmv-reuse-closed' );
};
mw.mmv.ui.reuse.Dialog = Dialog;
}() ); | this.handleEvent( 'mmv-download-open', this.closeDialog.bind( this ) );
this.handleEvent( 'mmv-options-open', this.closeDialog.bind( this ) );
this.attachDependencies(); | random_line_split |
mmv.ui.reuse.dialog.js | /*
* This file is part of the MediaWiki extension MultimediaViewer.
*
* MultimediaViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MultimediaViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultimediaViewer. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
// Shortcut for prototype later
var DP;
/**
* Represents the file reuse dialog and the link to open it.
*
* @class mw.mmv.ui.reuse.Dialog
* @extends mw.mmv.ui.Element
* @param {jQuery} $container the element to which the dialog will be appended
* @param {jQuery} $openButton the button which opens the dialog. Only used for positioning.
* @param {mw.mmv.Config} config
*/
function Dialog( $container, $openButton, config ) {
mw.mmv.ui.Dialog.call( this, $container, $openButton, config );
/**
* @property {Object.<string, mw.mmv.ui.Element>} tabs List of tab ui objects.
*/
this.tabs = null;
/**
* @property {Object.<string, OO.ui.MenuOptionWidget>} ooTabs List of tab OOUI objects.
*/
this.ooTabs = null;
this.loadDependencies.push( 'mmv.ui.reuse.shareembed' );
this.$dialog.addClass( 'mw-mmv-reuse-dialog' );
this.eventPrefix = 'use-this-file';
}
OO.inheritClass( Dialog, mw.mmv.ui.Dialog );
DP = Dialog.prototype;
// FIXME this should happen outside the dialog and the tabs, but we need to improve
DP.initTabs = function () {
function makeTab( type ) |
this.reuseTabs = new OO.ui.MenuSelectWidget( {
autoHide: false,
classes: [ 'mw-mmv-reuse-tabs' ]
} );
this.reuseTabs.$element.appendTo( this.$dialog );
this.tabs = {
share: new mw.mmv.ui.reuse.Share( this.$dialog ),
embed: new mw.mmv.ui.reuse.Embed( this.$dialog )
};
this.ooTabs = {
share: makeTab( 'share' ),
embed: makeTab( 'embed' )
};
this.reuseTabs.addItems( [
this.ooTabs.share,
this.ooTabs.embed
] );
// MenuSelectWidget has a nasty tendency to hide itself, maybe we're not using it right?
this.reuseTabs.toggle( true );
this.reuseTabs.toggle = function () {};
this.selectedTab = this.getLastUsedTab();
// In case nothing is saved in localStorage or it contains junk
if ( !Object.prototype.hasOwnProperty.call( this.tabs, this.selectedTab ) ) {
this.selectedTab = 'share';
}
this.reuseTabs.selectItem( this.ooTabs[ this.selectedTab ] );
if ( this.dependenciesNeedToBeAttached ) {
this.attachDependencies();
}
if ( this.tabsSetValues ) {
// This is a delayed set() for the elements we've just created on demand
this.tabs.share.set.apply( this.tabs.share, this.tabsSetValues.share );
this.tabs.embed.set.apply( this.tabs.embed, this.tabsSetValues.embed );
this.showImageWarnings( this.tabsSetValues.share[ 0 ] );
this.tabsSetValues = undefined;
}
};
DP.toggleDialog = function () {
if ( this.tabs === null ) {
this.initTabs();
}
mw.mmv.ui.Dialog.prototype.toggleDialog.call( this );
};
/**
* Handles tab selection.
*
* @param {OO.ui.MenuOptionWidget} option
*/
DP.handleTabSelection = function ( option ) {
var tab;
this.selectedTab = option.getData();
for ( tab in this.tabs ) {
if ( tab === this.selectedTab ) {
this.tabs[ tab ].show();
} else {
this.tabs[ tab ].hide();
}
}
this.config.setInLocalStorage( 'mmv-lastUsedTab', this.selectedTab );
};
/**
* @return {string} Last used tab
*/
DP.getLastUsedTab = function () {
return this.config.getFromLocalStorage( 'mmv-lastUsedTab' );
};
/**
* Registers listeners.
*/
DP.attach = function () {
this.handleEvent( 'mmv-reuse-open', this.handleOpenCloseClick.bind( this ) );
this.handleEvent( 'mmv-download-open', this.closeDialog.bind( this ) );
this.handleEvent( 'mmv-options-open', this.closeDialog.bind( this ) );
this.attachDependencies();
};
/**
* Registrers listeners for dependencies loaded on demand
*/
DP.attachDependencies = function () {
var tab, dialog = this;
if ( this.reuseTabs && this.tabs ) {
// This is a delayed attach() for the elements we've just created on demand
this.reuseTabs.on( 'select', dialog.handleTabSelection.bind( dialog ) );
for ( tab in this.tabs ) {
this.tabs[ tab ].attach();
}
this.dependenciesNeedToBeAttached = false;
} else {
this.dependenciesNeedToBeAttached = true;
}
};
/**
* Clears listeners.
*/
DP.unattach = function () {
var tab;
mw.mmv.ui.Dialog.prototype.unattach.call( this );
if ( this.reuseTabs ) {
this.reuseTabs.off( 'select' );
}
if ( this.tabs ) {
for ( tab in this.tabs ) {
this.tabs[ tab ].unattach();
}
}
};
/**
* Sets data needed by contaned tabs and makes dialog launch link visible.
*
* @param {mw.mmv.model.Image} image
* @param {mw.mmv.model.Repo} repo
* @param {string} caption
* @param {string} alt
*/
DP.set = function ( image, repo, caption, alt ) {
if ( this.tabs !== null ) {
this.tabs.share.set( image );
this.tabs.embed.set( image, repo, caption, alt );
this.tabs.embed.set( image, repo, caption );
this.showImageWarnings( image );
} else {
this.tabsSetValues = {
share: [ image ],
embed: [ image, repo, caption, alt ]
};
}
};
/**
* @inheritdoc
*/
DP.empty = function () {
var tab;
mw.mmv.ui.Dialog.prototype.empty.call( this );
for ( tab in this.tabs ) {
this.tabs[ tab ].empty();
}
};
/**
* @event mmv-reuse-opened
* Fired when the dialog is opened.
*/
/**
* Opens a dialog with information about file reuse.
*/
DP.openDialog = function () {
mw.mmv.ui.Dialog.prototype.openDialog.call( this );
// move warnings after the tabs
this.$warning.insertAfter( this.reuseTabs.$element );
this.tabs[ this.selectedTab ].show();
$( document ).trigger( 'mmv-reuse-opened' );
};
/**
* @event mmv-reuse-closed
* Fired when the dialog is closed.
*/
/**
* Closes the reuse dialog.
*/
DP.closeDialog = function () {
mw.mmv.ui.Dialog.prototype.closeDialog.call( this );
$( document ).trigger( 'mmv-reuse-closed' );
};
mw.mmv.ui.reuse.Dialog = Dialog;
}() );
| {
return new OO.ui.MenuOptionWidget( {
data: type,
label: mw.message( 'multimediaviewer-' + type + '-tab' ).text()
} );
} | identifier_body |
mmv.ui.reuse.dialog.js | /*
* This file is part of the MediaWiki extension MultimediaViewer.
*
* MultimediaViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MultimediaViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultimediaViewer. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
// Shortcut for prototype later
var DP;
/**
* Represents the file reuse dialog and the link to open it.
*
* @class mw.mmv.ui.reuse.Dialog
* @extends mw.mmv.ui.Element
* @param {jQuery} $container the element to which the dialog will be appended
* @param {jQuery} $openButton the button which opens the dialog. Only used for positioning.
* @param {mw.mmv.Config} config
*/
function Dialog( $container, $openButton, config ) {
mw.mmv.ui.Dialog.call( this, $container, $openButton, config );
/**
* @property {Object.<string, mw.mmv.ui.Element>} tabs List of tab ui objects.
*/
this.tabs = null;
/**
* @property {Object.<string, OO.ui.MenuOptionWidget>} ooTabs List of tab OOUI objects.
*/
this.ooTabs = null;
this.loadDependencies.push( 'mmv.ui.reuse.shareembed' );
this.$dialog.addClass( 'mw-mmv-reuse-dialog' );
this.eventPrefix = 'use-this-file';
}
OO.inheritClass( Dialog, mw.mmv.ui.Dialog );
DP = Dialog.prototype;
// FIXME this should happen outside the dialog and the tabs, but we need to improve
DP.initTabs = function () {
function | ( type ) {
return new OO.ui.MenuOptionWidget( {
data: type,
label: mw.message( 'multimediaviewer-' + type + '-tab' ).text()
} );
}
this.reuseTabs = new OO.ui.MenuSelectWidget( {
autoHide: false,
classes: [ 'mw-mmv-reuse-tabs' ]
} );
this.reuseTabs.$element.appendTo( this.$dialog );
this.tabs = {
share: new mw.mmv.ui.reuse.Share( this.$dialog ),
embed: new mw.mmv.ui.reuse.Embed( this.$dialog )
};
this.ooTabs = {
share: makeTab( 'share' ),
embed: makeTab( 'embed' )
};
this.reuseTabs.addItems( [
this.ooTabs.share,
this.ooTabs.embed
] );
// MenuSelectWidget has a nasty tendency to hide itself, maybe we're not using it right?
this.reuseTabs.toggle( true );
this.reuseTabs.toggle = function () {};
this.selectedTab = this.getLastUsedTab();
// In case nothing is saved in localStorage or it contains junk
if ( !Object.prototype.hasOwnProperty.call( this.tabs, this.selectedTab ) ) {
this.selectedTab = 'share';
}
this.reuseTabs.selectItem( this.ooTabs[ this.selectedTab ] );
if ( this.dependenciesNeedToBeAttached ) {
this.attachDependencies();
}
if ( this.tabsSetValues ) {
// This is a delayed set() for the elements we've just created on demand
this.tabs.share.set.apply( this.tabs.share, this.tabsSetValues.share );
this.tabs.embed.set.apply( this.tabs.embed, this.tabsSetValues.embed );
this.showImageWarnings( this.tabsSetValues.share[ 0 ] );
this.tabsSetValues = undefined;
}
};
DP.toggleDialog = function () {
if ( this.tabs === null ) {
this.initTabs();
}
mw.mmv.ui.Dialog.prototype.toggleDialog.call( this );
};
/**
* Handles tab selection.
*
* @param {OO.ui.MenuOptionWidget} option
*/
DP.handleTabSelection = function ( option ) {
var tab;
this.selectedTab = option.getData();
for ( tab in this.tabs ) {
if ( tab === this.selectedTab ) {
this.tabs[ tab ].show();
} else {
this.tabs[ tab ].hide();
}
}
this.config.setInLocalStorage( 'mmv-lastUsedTab', this.selectedTab );
};
/**
* @return {string} Last used tab
*/
DP.getLastUsedTab = function () {
return this.config.getFromLocalStorage( 'mmv-lastUsedTab' );
};
/**
* Registers listeners.
*/
DP.attach = function () {
this.handleEvent( 'mmv-reuse-open', this.handleOpenCloseClick.bind( this ) );
this.handleEvent( 'mmv-download-open', this.closeDialog.bind( this ) );
this.handleEvent( 'mmv-options-open', this.closeDialog.bind( this ) );
this.attachDependencies();
};
/**
* Registrers listeners for dependencies loaded on demand
*/
DP.attachDependencies = function () {
var tab, dialog = this;
if ( this.reuseTabs && this.tabs ) {
// This is a delayed attach() for the elements we've just created on demand
this.reuseTabs.on( 'select', dialog.handleTabSelection.bind( dialog ) );
for ( tab in this.tabs ) {
this.tabs[ tab ].attach();
}
this.dependenciesNeedToBeAttached = false;
} else {
this.dependenciesNeedToBeAttached = true;
}
};
/**
* Clears listeners.
*/
DP.unattach = function () {
var tab;
mw.mmv.ui.Dialog.prototype.unattach.call( this );
if ( this.reuseTabs ) {
this.reuseTabs.off( 'select' );
}
if ( this.tabs ) {
for ( tab in this.tabs ) {
this.tabs[ tab ].unattach();
}
}
};
/**
* Sets data needed by contaned tabs and makes dialog launch link visible.
*
* @param {mw.mmv.model.Image} image
* @param {mw.mmv.model.Repo} repo
* @param {string} caption
* @param {string} alt
*/
DP.set = function ( image, repo, caption, alt ) {
if ( this.tabs !== null ) {
this.tabs.share.set( image );
this.tabs.embed.set( image, repo, caption, alt );
this.tabs.embed.set( image, repo, caption );
this.showImageWarnings( image );
} else {
this.tabsSetValues = {
share: [ image ],
embed: [ image, repo, caption, alt ]
};
}
};
/**
* @inheritdoc
*/
DP.empty = function () {
var tab;
mw.mmv.ui.Dialog.prototype.empty.call( this );
for ( tab in this.tabs ) {
this.tabs[ tab ].empty();
}
};
/**
* @event mmv-reuse-opened
* Fired when the dialog is opened.
*/
/**
* Opens a dialog with information about file reuse.
*/
DP.openDialog = function () {
mw.mmv.ui.Dialog.prototype.openDialog.call( this );
// move warnings after the tabs
this.$warning.insertAfter( this.reuseTabs.$element );
this.tabs[ this.selectedTab ].show();
$( document ).trigger( 'mmv-reuse-opened' );
};
/**
* @event mmv-reuse-closed
* Fired when the dialog is closed.
*/
/**
* Closes the reuse dialog.
*/
DP.closeDialog = function () {
mw.mmv.ui.Dialog.prototype.closeDialog.call( this );
$( document ).trigger( 'mmv-reuse-closed' );
};
mw.mmv.ui.reuse.Dialog = Dialog;
}() );
| makeTab | identifier_name |
mmv.ui.reuse.dialog.js | /*
* This file is part of the MediaWiki extension MultimediaViewer.
*
* MultimediaViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MultimediaViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultimediaViewer. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
// Shortcut for prototype later
var DP;
/**
* Represents the file reuse dialog and the link to open it.
*
* @class mw.mmv.ui.reuse.Dialog
* @extends mw.mmv.ui.Element
* @param {jQuery} $container the element to which the dialog will be appended
* @param {jQuery} $openButton the button which opens the dialog. Only used for positioning.
* @param {mw.mmv.Config} config
*/
function Dialog( $container, $openButton, config ) {
mw.mmv.ui.Dialog.call( this, $container, $openButton, config );
/**
* @property {Object.<string, mw.mmv.ui.Element>} tabs List of tab ui objects.
*/
this.tabs = null;
/**
* @property {Object.<string, OO.ui.MenuOptionWidget>} ooTabs List of tab OOUI objects.
*/
this.ooTabs = null;
this.loadDependencies.push( 'mmv.ui.reuse.shareembed' );
this.$dialog.addClass( 'mw-mmv-reuse-dialog' );
this.eventPrefix = 'use-this-file';
}
OO.inheritClass( Dialog, mw.mmv.ui.Dialog );
DP = Dialog.prototype;
// FIXME this should happen outside the dialog and the tabs, but we need to improve
DP.initTabs = function () {
function makeTab( type ) {
return new OO.ui.MenuOptionWidget( {
data: type,
label: mw.message( 'multimediaviewer-' + type + '-tab' ).text()
} );
}
this.reuseTabs = new OO.ui.MenuSelectWidget( {
autoHide: false,
classes: [ 'mw-mmv-reuse-tabs' ]
} );
this.reuseTabs.$element.appendTo( this.$dialog );
this.tabs = {
share: new mw.mmv.ui.reuse.Share( this.$dialog ),
embed: new mw.mmv.ui.reuse.Embed( this.$dialog )
};
this.ooTabs = {
share: makeTab( 'share' ),
embed: makeTab( 'embed' )
};
this.reuseTabs.addItems( [
this.ooTabs.share,
this.ooTabs.embed
] );
// MenuSelectWidget has a nasty tendency to hide itself, maybe we're not using it right?
this.reuseTabs.toggle( true );
this.reuseTabs.toggle = function () {};
this.selectedTab = this.getLastUsedTab();
// In case nothing is saved in localStorage or it contains junk
if ( !Object.prototype.hasOwnProperty.call( this.tabs, this.selectedTab ) ) {
this.selectedTab = 'share';
}
this.reuseTabs.selectItem( this.ooTabs[ this.selectedTab ] );
if ( this.dependenciesNeedToBeAttached ) {
this.attachDependencies();
}
if ( this.tabsSetValues ) {
// This is a delayed set() for the elements we've just created on demand
this.tabs.share.set.apply( this.tabs.share, this.tabsSetValues.share );
this.tabs.embed.set.apply( this.tabs.embed, this.tabsSetValues.embed );
this.showImageWarnings( this.tabsSetValues.share[ 0 ] );
this.tabsSetValues = undefined;
}
};
DP.toggleDialog = function () {
if ( this.tabs === null ) {
this.initTabs();
}
mw.mmv.ui.Dialog.prototype.toggleDialog.call( this );
};
/**
* Handles tab selection.
*
* @param {OO.ui.MenuOptionWidget} option
*/
DP.handleTabSelection = function ( option ) {
var tab;
this.selectedTab = option.getData();
for ( tab in this.tabs ) {
if ( tab === this.selectedTab ) | else {
this.tabs[ tab ].hide();
}
}
this.config.setInLocalStorage( 'mmv-lastUsedTab', this.selectedTab );
};
/**
* @return {string} Last used tab
*/
DP.getLastUsedTab = function () {
return this.config.getFromLocalStorage( 'mmv-lastUsedTab' );
};
/**
* Registers listeners.
*/
DP.attach = function () {
this.handleEvent( 'mmv-reuse-open', this.handleOpenCloseClick.bind( this ) );
this.handleEvent( 'mmv-download-open', this.closeDialog.bind( this ) );
this.handleEvent( 'mmv-options-open', this.closeDialog.bind( this ) );
this.attachDependencies();
};
/**
* Registrers listeners for dependencies loaded on demand
*/
DP.attachDependencies = function () {
var tab, dialog = this;
if ( this.reuseTabs && this.tabs ) {
// This is a delayed attach() for the elements we've just created on demand
this.reuseTabs.on( 'select', dialog.handleTabSelection.bind( dialog ) );
for ( tab in this.tabs ) {
this.tabs[ tab ].attach();
}
this.dependenciesNeedToBeAttached = false;
} else {
this.dependenciesNeedToBeAttached = true;
}
};
/**
* Clears listeners.
*/
DP.unattach = function () {
var tab;
mw.mmv.ui.Dialog.prototype.unattach.call( this );
if ( this.reuseTabs ) {
this.reuseTabs.off( 'select' );
}
if ( this.tabs ) {
for ( tab in this.tabs ) {
this.tabs[ tab ].unattach();
}
}
};
/**
* Sets data needed by contaned tabs and makes dialog launch link visible.
*
* @param {mw.mmv.model.Image} image
* @param {mw.mmv.model.Repo} repo
* @param {string} caption
* @param {string} alt
*/
DP.set = function ( image, repo, caption, alt ) {
if ( this.tabs !== null ) {
this.tabs.share.set( image );
this.tabs.embed.set( image, repo, caption, alt );
this.tabs.embed.set( image, repo, caption );
this.showImageWarnings( image );
} else {
this.tabsSetValues = {
share: [ image ],
embed: [ image, repo, caption, alt ]
};
}
};
/**
* @inheritdoc
*/
DP.empty = function () {
var tab;
mw.mmv.ui.Dialog.prototype.empty.call( this );
for ( tab in this.tabs ) {
this.tabs[ tab ].empty();
}
};
/**
* @event mmv-reuse-opened
* Fired when the dialog is opened.
*/
/**
* Opens a dialog with information about file reuse.
*/
DP.openDialog = function () {
mw.mmv.ui.Dialog.prototype.openDialog.call( this );
// move warnings after the tabs
this.$warning.insertAfter( this.reuseTabs.$element );
this.tabs[ this.selectedTab ].show();
$( document ).trigger( 'mmv-reuse-opened' );
};
/**
* @event mmv-reuse-closed
* Fired when the dialog is closed.
*/
/**
* Closes the reuse dialog.
*/
DP.closeDialog = function () {
mw.mmv.ui.Dialog.prototype.closeDialog.call( this );
$( document ).trigger( 'mmv-reuse-closed' );
};
mw.mmv.ui.reuse.Dialog = Dialog;
}() );
| {
this.tabs[ tab ].show();
} | conditional_block |
functions_b.js | var searchData=
[
['senderrmessage',['sendERRMessage',['../class_merg_c_b_u_s.html#a08c4a666820ed63f2b574c75cc66482f',1,'MergCBUS']]],
['setcanid',['setCanId',['../class_message.html#afb26a027ffa7e45750f1c738017bb41c',1,'Message::setCanId()'],['../class_merg_memory_management.html#afda2b8368819f35abb28e812b3d02130',1,'MergMemoryManagement::setCanId()'],['../class_merg_node_identification.html#a83076917e774e4eab71503bf7589530e',1,'MergNodeIdentification::setCanID()']]],
['setcanmessagesize',['setCanMessageSize',['../class_message.html#a013e607e51f2912ba11022300fda1227',1,'Message']]],
['setconsumernode',['setConsumerNode',['../class_merg_node_identification.html#a1ddd550e0081516713ad47881b8ab239',1,'MergNodeIdentification']]],
['setcv',['setCV',['../class_message.html#ad051e496867ecab822b471636f45fa43',1,'Message']]],
['setdatabuffer',['setDataBuffer',['../class_message.html#af86c9c36d185a2d7abfd5c62f87fc0ca',1,'Message']]],
['setdebug',['setDebug',['../class_merg_c_b_u_s.html#ad0da4eb3df275b6b37bdf5cff96bceaa',1,'MergCBUS::setDebug()'],['../class_message.html#a13a72dff57c0acb792d06ca297324621',1,'Message::setDebug()']]],
['setdecoder',['setDecoder',['../class_message.html#a991dabf8f34d36ae45a33b84141ab5f9',1,'Message']]],
['setdevicenumber',['setDeviceNumber',['../class_merg_c_b_u_s.html#a3d531d2cc7827b0b6be3f3a25f55c3bf',1,'MergCBUS::setDeviceNumber()'],['../class_message.html#af6be3cb87c2958432cd17bcaac304828',1,'Message::setDeviceNumber()'],['../class_merg_memory_management.html#aa95e1e0870c3ef5cc934b813ad67dbab',1,'MergMemoryManagement::setDeviceNumber()']]],
['setevent',['setEvent',['../class_merg_memory_management.html#aefdd07a891bbd50dbd63187288efa254',1,'MergMemoryManagement::setEvent(byte *event)'],['../class_merg_memory_management.html#a6d91785c443bd03a96d31d01e6324515',1,'MergMemoryManagement::setEvent(byte *event, unsigned int eventIdx)']]],
['seteventnumber',['setEventNumber',['../class_message.html#afd918c1f125e62ee2d5b8d2a1137bf73',1,'Message']]],
['seteventvar',['setEventVar',['../class_merg_memory_management.html#aa06b33a9e477c83c6eab42860c3e5ab9',1,'MergMemoryManagement']]],
['setflags',['setFlags',['../class_merg_node_identification.html#ac83602870fae89378f512de53363605b',1,'MergNodeIdentification']]],
['setflimmode',['setFlimMode',['../class_merg_c_b_u_s.html#a343d837fcd1769ba000f69a72b7e8542',1,'MergCBUS::setFlimMode()'],['../class_merg_node_identification.html#a02eb7a12697d556169517ea7d6f06cd9',1,'MergNodeIdentification::setFlimMode()']]],
['setheaderbuffer',['setHeaderBuffer',['../class_message.html#a5d9f6614ccca7ee4feebd734dbd21f77',1,'Message']]],
['setleds',['setLeds',['../class_merg_c_b_u_s.html#a3764ee3c7ccc005cdefb8914332abf20',1,'MergCBUS']]],
['setmanufacturerid',['setManufacturerId',['../class_merg_node_identification.html#a79ed072e120908504dcf19b3d75f8d42',1,'MergNodeIdentification']]],
['setmaxcodeversion',['setMaxCodeVersion',['../class_merg_node_identification.html#ae01db7cc73b68288fecc2eace1828899',1,'MergNodeIdentification']]],
['setmincodeversion',['setMinCodeVersion',['../class_merg_node_identification.html#a69dca01c0c99b3d97cd4d6f9598f3f64',1,'MergNodeIdentification']]],
['setmoduleid',['setModuleId',['../class_merg_node_identification.html#a42b1f85392ae472206d290681591ca4b',1,'MergNodeIdentification']]],
['setnodeflag',['setNodeFlag',['../class_merg_memory_management.html#a37cc7d00ccca93acd213f456a5c6ddba',1,'MergMemoryManagement']]],
['setnodename',['setNodeName',['../class_merg_node_identification.html#aba951c1739be029071d40634f6593d61',1,'MergNodeIdentification']]],
['setnodenumber',['setNodeNumber',['../class_merg_node_identification.html#a332a18e94b99a797ed8ae1ab223bc401',1,'MergNodeIdentification::setNodeNumber()'],['../class_message.html#acc36c61a540bd4ed1374e3437a4e40e8',1,'Message::setNodeNumber()'],['../class_merg_memory_management.html#aee708363c9f112bfb3ba96cc69ab2d4e',1,'MergMemoryManagement::setNodeNumber()']]],
['setnumbytes',['setNumBytes',['../class_message.html#a87972ab17c0129ba9e6bd04bcffeed6e',1,'Message']]],
['setopc',['setOpc',['../class_message.html#a8b97ccee81287d4cb824cce17f3a50ae',1,'Message']]],
['setpriority',['setPriority',['../class_message.html#a41549efc4487ecaa8e7be21172bf5d02',1,'Message']]],
['setproducernode',['setProducerNode',['../class_merg_node_identification.html#a035b64252ff8a9e680e481dbb788edd5',1,'MergNodeIdentification']]],
['setpushbutton',['setPushButton',['../class_merg_c_b_u_s.html#adf4f61203c1fc2f8312f8fc343aa5ea0',1,'MergCBUS']]],
['setrtr',['setRTR',['../class_message.html#af707419697acf59655187dc2e673170f',1,'Message']]], | ['setsuportbootloading',['setSuportBootLoading',['../class_merg_node_identification.html#a26dd508e5fdd061b1b7bd27ece11535c',1,'MergNodeIdentification']]],
['setsuportedevents',['setSuportedEvents',['../class_merg_node_identification.html#a20dec04b153357c80e6ad6646a707871',1,'MergNodeIdentification']]],
['setsuportedeventsvariables',['setSuportedEventsVariables',['../class_merg_node_identification.html#ae617f3c49d5800aa56e0add65aa8ee95',1,'MergNodeIdentification']]],
['setsuportednodevariables',['setSuportedNodeVariables',['../class_merg_node_identification.html#a72a738ead69d160b96d7fb7013331758',1,'MergNodeIdentification']]],
['settype',['setType',['../class_message.html#ab5fe14f551f377618aa0fd38ec26a465',1,'Message']]],
['setupnewmemory',['setUpNewMemory',['../class_merg_c_b_u_s.html#a0d2ce0784f942cb091c9b02696010806',1,'MergCBUS::setUpNewMemory()'],['../class_merg_memory_management.html#a79b3777391babb695257794d74244a9d',1,'MergMemoryManagement::setUpNewMemory()']]],
['setuserhandlerfunction',['setUserHandlerFunction',['../class_merg_c_b_u_s.html#a4fca9209a4902005232a0e9e44aec543',1,'MergCBUS']]],
['setvar',['setVar',['../class_merg_memory_management.html#a8ad47ba19eff0099541d396bb1e39c08',1,'MergMemoryManagement']]],
['skipmessage',['skipMessage',['../class_merg_c_b_u_s.html#a0cdd8a6d13ede3cd1d3e5c2ceacec901',1,'MergCBUS']]],
['suportbootloading',['suportBootLoading',['../class_merg_node_identification.html#ab7e8783debece2f1ac891664e2995649',1,'MergNodeIdentification']]]
]; | ['setsession',['setSession',['../class_message.html#aeea5f6ae60eb166fcb1736c20b284e68',1,'Message']]],
['setslimmode',['setSlimMode',['../class_merg_c_b_u_s.html#a51234206c9584f6c2b4b2b67f2fee2a3',1,'MergCBUS::setSlimMode()'],['../class_merg_node_identification.html#aa81ce38db52f2508e71efafbef651b86',1,'MergNodeIdentification::setSlimMode()']]],
['setstdnn',['setStdNN',['../class_merg_c_b_u_s.html#adacc7060eff79875821af2e08e728c04',1,'MergCBUS']]], | random_line_split |
base.py | import os
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
import dj_database_url
def | (var_name):
"""Get the environment variable var_name or return an exception."""
try:
return os.environ[var_name]
except KeyError:
msg = "Please set the environment variable {}".format(var_name)
raise ImproperlyConfigured(msg)
SECRET_KEY = env_var("MT_SECRET_KEY")
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# ADMIN_PATH controls where the admin urls are.
# e.g. if ADMIN_PATH == 'adminsitemilktea', then the admin site
# should be available at /adminsitemilktea/ instead of /admin/.
ADMIN_PATH = env_var("MT_ADMIN_PATH")
DJANGO_CORE_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'djmoney',
'nested_admin',
]
CUSTOM_APPS = [
'core',
]
INSTALLED_APPS = DJANGO_CORE_APPS + THIRD_PARTY_APPS + CUSTOM_APPS
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mt.urls'
WSGI_APPLICATION = 'mt.wsgi.application'
BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child("media")
STATIC_ROOT = BASE_DIR.child("static")
STATICFILES_DIRS = (
BASE_DIR.child("assets"),
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': (BASE_DIR.child("templates"),),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {'default': dj_database_url.parse(env_var("MT_MYSQL_URL"), conn_max_age = 600)}
DATABASES['default']['ATOMIC_REQUESTS'] = True
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
| env_var | identifier_name |
base.py | import os
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
import dj_database_url
def env_var(var_name):
"""Get the environment variable var_name or return an exception."""
try:
return os.environ[var_name]
except KeyError:
msg = "Please set the environment variable {}".format(var_name)
raise ImproperlyConfigured(msg)
SECRET_KEY = env_var("MT_SECRET_KEY")
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
| # ADMIN_PATH controls where the admin urls are.
# e.g. if ADMIN_PATH == 'adminsitemilktea', then the admin site
# should be available at /adminsitemilktea/ instead of /admin/.
ADMIN_PATH = env_var("MT_ADMIN_PATH")
DJANGO_CORE_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'djmoney',
'nested_admin',
]
CUSTOM_APPS = [
'core',
]
INSTALLED_APPS = DJANGO_CORE_APPS + THIRD_PARTY_APPS + CUSTOM_APPS
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mt.urls'
WSGI_APPLICATION = 'mt.wsgi.application'
BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child("media")
STATIC_ROOT = BASE_DIR.child("static")
STATICFILES_DIRS = (
BASE_DIR.child("assets"),
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': (BASE_DIR.child("templates"),),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {'default': dj_database_url.parse(env_var("MT_MYSQL_URL"), conn_max_age = 600)}
DATABASES['default']['ATOMIC_REQUESTS'] = True
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/' | random_line_split | |
base.py | import os
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
import dj_database_url
def env_var(var_name):
|
SECRET_KEY = env_var("MT_SECRET_KEY")
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# ADMIN_PATH controls where the admin urls are.
# e.g. if ADMIN_PATH == 'adminsitemilktea', then the admin site
# should be available at /adminsitemilktea/ instead of /admin/.
ADMIN_PATH = env_var("MT_ADMIN_PATH")
DJANGO_CORE_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'djmoney',
'nested_admin',
]
CUSTOM_APPS = [
'core',
]
INSTALLED_APPS = DJANGO_CORE_APPS + THIRD_PARTY_APPS + CUSTOM_APPS
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mt.urls'
WSGI_APPLICATION = 'mt.wsgi.application'
BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child("media")
STATIC_ROOT = BASE_DIR.child("static")
STATICFILES_DIRS = (
BASE_DIR.child("assets"),
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': (BASE_DIR.child("templates"),),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {'default': dj_database_url.parse(env_var("MT_MYSQL_URL"), conn_max_age = 600)}
DATABASES['default']['ATOMIC_REQUESTS'] = True
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
| """Get the environment variable var_name or return an exception."""
try:
return os.environ[var_name]
except KeyError:
msg = "Please set the environment variable {}".format(var_name)
raise ImproperlyConfigured(msg) | identifier_body |
iframe.js | /*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) {
return;
}
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
});
socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function | (key, n) {
if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
};
document.body.appendChild(script);
})();
| update | identifier_name |
iframe.js | /*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) {
return;
}
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
}); | if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
};
document.body.appendChild(script);
})(); | socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function update(key, n) { | random_line_split |
iframe.js | /*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) {
return;
}
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
});
socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function update(key, n) | };
document.body.appendChild(script);
})();
| {
if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
| identifier_body |
iframe.js | /*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) |
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
});
socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function update(key, n) {
if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
};
document.body.appendChild(script);
})();
| {
return;
} | conditional_block |
0305.py | # -*- coding: UTF-8 -*-
from __future__ import print_function
import csv
import os
ignored_views = set(["HHB", "FFO", "FFOI"])
seen_views = set([])
seen_aliases = set([])
seen_groups = set([])
tpl = "check_journal(u'{1}', u'{4}', u'{11}', u'{10}')"
print("""# -*- coding: UTF-8 -*-
from __future__ import print_function
from lino.api import rt
ledger = rt.models.ledger
finan = rt.models.finan
vatless = rt.models.vatless
def check_journal(ref, name, view, group):
if ledger.Journal.objects.filter(ref=ref).count():
print("Journal", ref, "exists") | if not group:
return
if view == "REG":
voucher_type = 'vatless.ProjectInvoicesByJournal'
elif view == "AAW":
voucher_type = 'finan.DisbursementOrdersByJournal'
elif view == "KAS":
voucher_type = 'finan.BankStatementsByJournal'
elif view == "ZAU":
voucher_type = 'finan.PaymentOrdersByJournal'
else:
return
grp = ledger.JournalGroups.get_by_name(group.lower())
obj = ledger.Journal(ref=ref, name=name, voucher_type=voucher_type,
journal_group=grp)
obj.full_clean()
# uncomment the following line when ready:
# obj.save()
print("Journal", ref, "has been created")
""")
with open(os.path.expanduser('~/Downloads/JNL.csv'), 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar='"')
for row in reader:
row = [x.strip() for x in row]
alias = row[2].strip()
group = row[10].strip()
view = row[11].strip()
if alias in ["IMP"]:
if view not in ignored_views:
seen_views.add(view)
seen_aliases.add(alias)
seen_groups.add(group)
print(tpl.format(*row))
# print(', '.join(row))
#print("# Seen aliases:", seen_aliases)
print("# Seen views:", seen_views)
print("# Seen groups:", seen_groups) | return | random_line_split |
0305.py | # -*- coding: UTF-8 -*-
from __future__ import print_function
import csv
import os
ignored_views = set(["HHB", "FFO", "FFOI"])
seen_views = set([])
seen_aliases = set([])
seen_groups = set([])
tpl = "check_journal(u'{1}', u'{4}', u'{11}', u'{10}')"
print("""# -*- coding: UTF-8 -*-
from __future__ import print_function
from lino.api import rt
ledger = rt.models.ledger
finan = rt.models.finan
vatless = rt.models.vatless
def check_journal(ref, name, view, group):
if ledger.Journal.objects.filter(ref=ref).count():
print("Journal", ref, "exists")
return
if not group:
return
if view == "REG":
voucher_type = 'vatless.ProjectInvoicesByJournal'
elif view == "AAW":
voucher_type = 'finan.DisbursementOrdersByJournal'
elif view == "KAS":
voucher_type = 'finan.BankStatementsByJournal'
elif view == "ZAU":
voucher_type = 'finan.PaymentOrdersByJournal'
else:
return
grp = ledger.JournalGroups.get_by_name(group.lower())
obj = ledger.Journal(ref=ref, name=name, voucher_type=voucher_type,
journal_group=grp)
obj.full_clean()
# uncomment the following line when ready:
# obj.save()
print("Journal", ref, "has been created")
""")
with open(os.path.expanduser('~/Downloads/JNL.csv'), 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar='"')
for row in reader:
row = [x.strip() for x in row]
alias = row[2].strip()
group = row[10].strip()
view = row[11].strip()
if alias in ["IMP"]:
|
#print("# Seen aliases:", seen_aliases)
print("# Seen views:", seen_views)
print("# Seen groups:", seen_groups)
| if view not in ignored_views:
seen_views.add(view)
seen_aliases.add(alias)
seen_groups.add(group)
print(tpl.format(*row))
# print(', '.join(row)) | conditional_block |
server.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as Proto from './protocol';
import { CancelledResponse, NoContentResponse, ServerResponse } from './typescriptService';
import API from './utils/api';
import { TsServerLogLevel, TypeScriptServiceConfiguration } from './utils/configuration';
import { Disposable } from './utils/dispose';
import * as electron from './utils/electron';
import LogDirectoryProvider from './utils/logDirectoryProvider';
import Logger from './utils/logger';
import { TypeScriptPluginPathsProvider } from './utils/pluginPathsProvider';
import { TypeScriptServerPlugin } from './utils/plugins';
import TelemetryReporter from './utils/telemetry';
import Tracer from './utils/tracer';
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider';
import { Reader } from './utils/wireProtocol';
interface CallbackItem<R> {
readonly onSuccess: (value: R) => void;
readonly onError: (err: any) => void;
readonly startTime: number;
readonly isAsync: boolean;
}
class CallbackMap<R extends Proto.Response> {
private readonly _callbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
private readonly _asyncCallbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
public destroy(cause: string): void {
const cancellation = new CancelledResponse(cause);
for (const callback of this._callbacks.values()) {
callback.onSuccess(cancellation);
}
this._callbacks.clear();
for (const callback of this._asyncCallbacks.values()) {
callback.onSuccess(cancellation);
}
this._asyncCallbacks.clear();
}
public add(seq: number, callback: CallbackItem<ServerResponse<R> | undefined>, isAsync: boolean) {
if (isAsync) {
this._asyncCallbacks.set(seq, callback);
} else {
this._callbacks.set(seq, callback);
}
}
public fetch(seq: number): CallbackItem<ServerResponse<R> | undefined> | undefined {
const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
this.delete(seq);
return callback;
}
private delete(seq: number) {
if (!this._callbacks.delete(seq)) {
this._asyncCallbacks.delete(seq);
}
} | interface RequestItem {
readonly request: Proto.Request;
readonly expectsResponse: boolean;
readonly isAsync: boolean;
}
class RequestQueue {
private readonly queue: RequestItem[] = [];
private sequenceNumber: number = 0;
public get length(): number {
return this.queue.length;
}
public push(item: RequestItem): void {
this.queue.push(item);
}
public shift(): RequestItem | undefined {
return this.queue.shift();
}
public tryCancelPendingRequest(seq: number): boolean {
for (let i = 0; i < this.queue.length; i++) {
if (this.queue[i].request.seq === seq) {
this.queue.splice(i, 1);
return true;
}
}
return false;
}
public createRequest(command: string, args: any): Proto.Request {
return {
seq: this.sequenceNumber++,
type: 'request',
command: command,
arguments: args
};
}
}
export class TypeScriptServerSpawner {
public constructor(
private readonly _versionProvider: TypeScriptVersionProvider,
private readonly _logDirectoryProvider: LogDirectoryProvider,
private readonly _pluginPathsProvider: TypeScriptPluginPathsProvider,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) { }
public spawn(
version: TypeScriptVersion,
configuration: TypeScriptServiceConfiguration,
plugins: ReadonlyArray<TypeScriptServerPlugin>
): TypeScriptServer {
const apiVersion = version.version || API.defaultVersion;
const { args, cancellationPipeName, tsServerLogFile } = this.getTsServerArgs(configuration, version, plugins);
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
if (tsServerLogFile) {
this._logger.info(`TSServer log file: ${tsServerLogFile}`);
} else {
this._logger.error('Could not create TSServer log directory');
}
}
this._logger.info('Forking TSServer');
const childProcess = electron.fork(version.tsServerPath, args, this.getForkOptions());
this._logger.info('Started TSServer');
return new TypeScriptServer(childProcess, tsServerLogFile, cancellationPipeName, this._logger, this._telemetryReporter, this._tracer);
}
private getForkOptions() {
const debugPort = TypeScriptServerSpawner.getDebugPort();
const tsServerForkOptions: electron.IForkOptions = {
execArgv: debugPort ? [`--inspect=${debugPort}`] : [],
};
return tsServerForkOptions;
}
private getTsServerArgs(
configuration: TypeScriptServiceConfiguration,
currentVersion: TypeScriptVersion,
plugins: ReadonlyArray<TypeScriptServerPlugin>,
): { args: string[], cancellationPipeName: string | undefined, tsServerLogFile: string | undefined } {
const args: string[] = [];
let cancellationPipeName: string | undefined = undefined;
let tsServerLogFile: string | undefined = undefined;
const apiVersion = currentVersion.version || API.defaultVersion;
if (apiVersion.gte(API.v206)) {
if (apiVersion.gte(API.v250)) {
args.push('--useInferredProjectPerProjectRoot');
} else {
args.push('--useSingleInferredProject');
}
if (configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition');
}
}
if (apiVersion.gte(API.v208)) {
args.push('--enableTelemetry');
}
if (apiVersion.gte(API.v222)) {
cancellationPipeName = electron.getTempFile('tscancellation');
args.push('--cancellationPipeName', cancellationPipeName + '*');
}
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
const logDir = this._logDirectoryProvider.getNewLogDirectory();
if (logDir) {
tsServerLogFile = path.join(logDir, `tsserver.log`);
args.push('--logVerbosity', TsServerLogLevel.toString(configuration.tsServerLogLevel));
args.push('--logFile', tsServerLogFile);
}
}
if (apiVersion.gte(API.v230)) {
const pluginPaths = this._pluginPathsProvider.getPluginPaths();
if (plugins.length) {
args.push('--globalPlugins', plugins.map(x => x.name).join(','));
if (currentVersion.path === this._versionProvider.defaultVersion.path) {
pluginPaths.push(...plugins.map(x => x.path));
}
}
if (pluginPaths.length !== 0) {
args.push('--pluginProbeLocations', pluginPaths.join(','));
}
}
if (apiVersion.gte(API.v234)) {
if (configuration.npmLocation) {
args.push('--npmLocation', `"${configuration.npmLocation}"`);
}
}
if (apiVersion.gte(API.v260)) {
args.push('--locale', TypeScriptServerSpawner.getTsLocale(configuration));
}
if (apiVersion.gte(API.v291)) {
args.push('--noGetErrOnBackgroundUpdate');
}
return { args, cancellationPipeName, tsServerLogFile };
}
private static getDebugPort(): number | undefined {
const value = process.env['TSS_DEBUG'];
if (value) {
const port = parseInt(value);
if (!isNaN(port)) {
return port;
}
}
return undefined;
}
private static isLoggingEnabled(apiVersion: API, configuration: TypeScriptServiceConfiguration) {
return apiVersion.gte(API.v222) &&
configuration.tsServerLogLevel !== TsServerLogLevel.Off;
}
private static getTsLocale(configuration: TypeScriptServiceConfiguration): string {
return configuration.locale
? configuration.locale
: vscode.env.language;
}
}
export class TypeScriptServer extends Disposable {
private readonly _reader: Reader<Proto.Response>;
private readonly _requestQueue = new RequestQueue();
private readonly _callbacks = new CallbackMap<Proto.Response>();
private readonly _pendingResponses = new Set<number>();
constructor(
private readonly _childProcess: cp.ChildProcess,
private readonly _tsServerLogFile: string | undefined,
private readonly _cancellationPipeName: string | undefined,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) {
super();
this._reader = new Reader<Proto.Response>(this._childProcess.stdout);
this._reader.onData(msg => this.dispatchMessage(msg));
this._childProcess.on('exit', code => this.handleExit(code));
this._childProcess.on('error', error => this.handleError(error));
}
private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>());
public readonly onEvent = this._onEvent.event;
private readonly _onExit = this._register(new vscode.EventEmitter<any>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
public readonly onError = this._onError.event;
public get onReaderError() { return this._reader.onError; }
public get tsServerLogFile() { return this._tsServerLogFile; }
public write(serverRequest: Proto.Request) {
this._childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
}
public dispose() {
super.dispose();
this._callbacks.destroy('server disposed');
this._pendingResponses.clear();
}
public kill() {
this._childProcess.kill();
}
private handleExit(error: any) {
this._onExit.fire(error);
this._callbacks.destroy('server exited');
}
private handleError(error: any) {
this._onError.fire(error);
this._callbacks.destroy('server errored');
}
private dispatchMessage(message: Proto.Message) {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message as Proto.Response);
break;
case 'event':
const event = message as Proto.Event;
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq;
const p = this._callbacks.fetch(seq);
if (p) {
this._tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
p.onSuccess(undefined);
}
} else {
this._tracer.traceEvent(event);
this._onEvent.fire(event);
}
break;
default:
throw new Error(`Unknown message type ${message.type} received`);
}
} finally {
this.sendNextRequests();
}
}
private tryCancelRequest(seq: number, command: string): boolean {
try {
if (this._requestQueue.tryCancelPendingRequest(seq)) {
this._tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
return true;
}
if (this._cancellationPipeName) {
this._tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
try {
fs.writeFileSync(this._cancellationPipeName + seq, '');
} catch {
// noop
}
return true;
}
this._tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
return false;
} finally {
const callback = this.fetchCallback(seq);
if (callback) {
callback.onSuccess(new CancelledResponse(`Cancelled request ${seq} - ${command}`));
}
}
}
private dispatchResponse(response: Proto.Response) {
const callback = this.fetchCallback(response.request_seq);
if (!callback) {
return;
}
this._tracer.traceResponse(response, callback.startTime);
if (response.success) {
callback.onSuccess(response);
} else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(new NoContentResponse());
} else {
callback.onError(response);
}
}
public executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: vscode.CancellationToken, expectsResult: boolean }): Promise<any> {
const request = this._requestQueue.createRequest(command, args);
const requestInfo: RequestItem = {
request: request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync
};
let result: Promise<any>;
if (executeInfo.expectsResult) {
let wasCancelled = false;
result = new Promise<any>((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
wasCancelled = true;
this.tryCancelRequest(request.seq, command);
});
}
}).catch((err: any) => {
if (!wasCancelled) {
this._logger.error(`'${command}' request failed with error.`, err);
const properties = this.parseErrorText(err && err.message, command);
/* __GDPR__
"languageServiceErrorResponse" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"stack" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"errortext" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"${include}": [
"${TypeScriptCommonProperties}"
]
}
*/
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties);
}
throw err;
});
} else {
result = Promise.resolve(null);
}
this._requestQueue.push(requestInfo);
this.sendNextRequests();
return result;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private parseErrorText(errorText: string | undefined, command: string) {
const properties: ObjectMap<string> = Object.create(null);
properties['command'] = command;
if (errorText) {
properties['errorText'] = errorText;
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
properties['message'] = prefixFreeErrorText.substring(0, newlineIndex);
properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1);
}
}
}
return properties;
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.shift();
if (item) {
this.sendRequest(item);
}
}
}
private sendRequest(requestItem: RequestItem): void {
const serverRequest = requestItem.request;
this._tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq);
}
try {
this.write(serverRequest);
} catch (err) {
const callback = this.fetchCallback(serverRequest.seq);
if (callback) {
callback.onError(err);
}
}
}
private fetchCallback(seq: number) {
const callback = this._callbacks.fetch(seq);
if (!callback) {
return undefined;
}
this._pendingResponses.delete(seq);
return callback;
}
} | }
| random_line_split |
server.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as Proto from './protocol';
import { CancelledResponse, NoContentResponse, ServerResponse } from './typescriptService';
import API from './utils/api';
import { TsServerLogLevel, TypeScriptServiceConfiguration } from './utils/configuration';
import { Disposable } from './utils/dispose';
import * as electron from './utils/electron';
import LogDirectoryProvider from './utils/logDirectoryProvider';
import Logger from './utils/logger';
import { TypeScriptPluginPathsProvider } from './utils/pluginPathsProvider';
import { TypeScriptServerPlugin } from './utils/plugins';
import TelemetryReporter from './utils/telemetry';
import Tracer from './utils/tracer';
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider';
import { Reader } from './utils/wireProtocol';
interface CallbackItem<R> {
readonly onSuccess: (value: R) => void;
readonly onError: (err: any) => void;
readonly startTime: number;
readonly isAsync: boolean;
}
class CallbackMap<R extends Proto.Response> {
private readonly _callbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
private readonly _asyncCallbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
public destroy(cause: string): void {
const cancellation = new CancelledResponse(cause);
for (const callback of this._callbacks.values()) {
callback.onSuccess(cancellation);
}
this._callbacks.clear();
for (const callback of this._asyncCallbacks.values()) {
callback.onSuccess(cancellation);
}
this._asyncCallbacks.clear();
}
public add(seq: number, callback: CallbackItem<ServerResponse<R> | undefined>, isAsync: boolean) {
if (isAsync) {
this._asyncCallbacks.set(seq, callback);
} else {
this._callbacks.set(seq, callback);
}
}
public fetch(seq: number): CallbackItem<ServerResponse<R> | undefined> | undefined {
const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
this.delete(seq);
return callback;
}
private delete(seq: number) {
if (!this._callbacks.delete(seq)) {
this._asyncCallbacks.delete(seq);
}
}
}
interface RequestItem {
readonly request: Proto.Request;
readonly expectsResponse: boolean;
readonly isAsync: boolean;
}
class RequestQueue {
private readonly queue: RequestItem[] = [];
private sequenceNumber: number = 0;
public get length(): number {
return this.queue.length;
}
public push(item: RequestItem): void {
this.queue.push(item);
}
public shift(): RequestItem | undefined {
return this.queue.shift();
}
public tryCancelPendingRequest(seq: number): boolean {
for (let i = 0; i < this.queue.length; i++) {
if (this.queue[i].request.seq === seq) {
this.queue.splice(i, 1);
return true;
}
}
return false;
}
public createRequest(command: string, args: any): Proto.Request {
return {
seq: this.sequenceNumber++,
type: 'request',
command: command,
arguments: args
};
}
}
export class TypeScriptServerSpawner {
public constructor(
private readonly _versionProvider: TypeScriptVersionProvider,
private readonly _logDirectoryProvider: LogDirectoryProvider,
private readonly _pluginPathsProvider: TypeScriptPluginPathsProvider,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) { }
public spawn(
version: TypeScriptVersion,
configuration: TypeScriptServiceConfiguration,
plugins: ReadonlyArray<TypeScriptServerPlugin>
): TypeScriptServer {
const apiVersion = version.version || API.defaultVersion;
const { args, cancellationPipeName, tsServerLogFile } = this.getTsServerArgs(configuration, version, plugins);
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
if (tsServerLogFile) {
this._logger.info(`TSServer log file: ${tsServerLogFile}`);
} else {
this._logger.error('Could not create TSServer log directory');
}
}
this._logger.info('Forking TSServer');
const childProcess = electron.fork(version.tsServerPath, args, this.getForkOptions());
this._logger.info('Started TSServer');
return new TypeScriptServer(childProcess, tsServerLogFile, cancellationPipeName, this._logger, this._telemetryReporter, this._tracer);
}
private getForkOptions() {
const debugPort = TypeScriptServerSpawner.getDebugPort();
const tsServerForkOptions: electron.IForkOptions = {
execArgv: debugPort ? [`--inspect=${debugPort}`] : [],
};
return tsServerForkOptions;
}
private getTsServerArgs(
configuration: TypeScriptServiceConfiguration,
currentVersion: TypeScriptVersion,
plugins: ReadonlyArray<TypeScriptServerPlugin>,
): { args: string[], cancellationPipeName: string | undefined, tsServerLogFile: string | undefined } {
const args: string[] = [];
let cancellationPipeName: string | undefined = undefined;
let tsServerLogFile: string | undefined = undefined;
const apiVersion = currentVersion.version || API.defaultVersion;
if (apiVersion.gte(API.v206)) {
if (apiVersion.gte(API.v250)) {
args.push('--useInferredProjectPerProjectRoot');
} else {
args.push('--useSingleInferredProject');
}
if (configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition');
}
}
if (apiVersion.gte(API.v208)) {
args.push('--enableTelemetry');
}
if (apiVersion.gte(API.v222)) {
cancellationPipeName = electron.getTempFile('tscancellation');
args.push('--cancellationPipeName', cancellationPipeName + '*');
}
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
const logDir = this._logDirectoryProvider.getNewLogDirectory();
if (logDir) {
tsServerLogFile = path.join(logDir, `tsserver.log`);
args.push('--logVerbosity', TsServerLogLevel.toString(configuration.tsServerLogLevel));
args.push('--logFile', tsServerLogFile);
}
}
if (apiVersion.gte(API.v230)) {
const pluginPaths = this._pluginPathsProvider.getPluginPaths();
if (plugins.length) {
args.push('--globalPlugins', plugins.map(x => x.name).join(','));
if (currentVersion.path === this._versionProvider.defaultVersion.path) {
pluginPaths.push(...plugins.map(x => x.path));
}
}
if (pluginPaths.length !== 0) {
args.push('--pluginProbeLocations', pluginPaths.join(','));
}
}
if (apiVersion.gte(API.v234)) {
if (configuration.npmLocation) |
}
if (apiVersion.gte(API.v260)) {
args.push('--locale', TypeScriptServerSpawner.getTsLocale(configuration));
}
if (apiVersion.gte(API.v291)) {
args.push('--noGetErrOnBackgroundUpdate');
}
return { args, cancellationPipeName, tsServerLogFile };
}
private static getDebugPort(): number | undefined {
const value = process.env['TSS_DEBUG'];
if (value) {
const port = parseInt(value);
if (!isNaN(port)) {
return port;
}
}
return undefined;
}
private static isLoggingEnabled(apiVersion: API, configuration: TypeScriptServiceConfiguration) {
return apiVersion.gte(API.v222) &&
configuration.tsServerLogLevel !== TsServerLogLevel.Off;
}
private static getTsLocale(configuration: TypeScriptServiceConfiguration): string {
return configuration.locale
? configuration.locale
: vscode.env.language;
}
}
export class TypeScriptServer extends Disposable {
private readonly _reader: Reader<Proto.Response>;
private readonly _requestQueue = new RequestQueue();
private readonly _callbacks = new CallbackMap<Proto.Response>();
private readonly _pendingResponses = new Set<number>();
constructor(
private readonly _childProcess: cp.ChildProcess,
private readonly _tsServerLogFile: string | undefined,
private readonly _cancellationPipeName: string | undefined,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) {
super();
this._reader = new Reader<Proto.Response>(this._childProcess.stdout);
this._reader.onData(msg => this.dispatchMessage(msg));
this._childProcess.on('exit', code => this.handleExit(code));
this._childProcess.on('error', error => this.handleError(error));
}
private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>());
public readonly onEvent = this._onEvent.event;
private readonly _onExit = this._register(new vscode.EventEmitter<any>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
public readonly onError = this._onError.event;
public get onReaderError() { return this._reader.onError; }
public get tsServerLogFile() { return this._tsServerLogFile; }
public write(serverRequest: Proto.Request) {
this._childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
}
public dispose() {
super.dispose();
this._callbacks.destroy('server disposed');
this._pendingResponses.clear();
}
public kill() {
this._childProcess.kill();
}
private handleExit(error: any) {
this._onExit.fire(error);
this._callbacks.destroy('server exited');
}
private handleError(error: any) {
this._onError.fire(error);
this._callbacks.destroy('server errored');
}
private dispatchMessage(message: Proto.Message) {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message as Proto.Response);
break;
case 'event':
const event = message as Proto.Event;
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq;
const p = this._callbacks.fetch(seq);
if (p) {
this._tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
p.onSuccess(undefined);
}
} else {
this._tracer.traceEvent(event);
this._onEvent.fire(event);
}
break;
default:
throw new Error(`Unknown message type ${message.type} received`);
}
} finally {
this.sendNextRequests();
}
}
private tryCancelRequest(seq: number, command: string): boolean {
try {
if (this._requestQueue.tryCancelPendingRequest(seq)) {
this._tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
return true;
}
if (this._cancellationPipeName) {
this._tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
try {
fs.writeFileSync(this._cancellationPipeName + seq, '');
} catch {
// noop
}
return true;
}
this._tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
return false;
} finally {
const callback = this.fetchCallback(seq);
if (callback) {
callback.onSuccess(new CancelledResponse(`Cancelled request ${seq} - ${command}`));
}
}
}
private dispatchResponse(response: Proto.Response) {
const callback = this.fetchCallback(response.request_seq);
if (!callback) {
return;
}
this._tracer.traceResponse(response, callback.startTime);
if (response.success) {
callback.onSuccess(response);
} else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(new NoContentResponse());
} else {
callback.onError(response);
}
}
public executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: vscode.CancellationToken, expectsResult: boolean }): Promise<any> {
const request = this._requestQueue.createRequest(command, args);
const requestInfo: RequestItem = {
request: request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync
};
let result: Promise<any>;
if (executeInfo.expectsResult) {
let wasCancelled = false;
result = new Promise<any>((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
wasCancelled = true;
this.tryCancelRequest(request.seq, command);
});
}
}).catch((err: any) => {
if (!wasCancelled) {
this._logger.error(`'${command}' request failed with error.`, err);
const properties = this.parseErrorText(err && err.message, command);
/* __GDPR__
"languageServiceErrorResponse" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"stack" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"errortext" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"${include}": [
"${TypeScriptCommonProperties}"
]
}
*/
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties);
}
throw err;
});
} else {
result = Promise.resolve(null);
}
this._requestQueue.push(requestInfo);
this.sendNextRequests();
return result;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private parseErrorText(errorText: string | undefined, command: string) {
const properties: ObjectMap<string> = Object.create(null);
properties['command'] = command;
if (errorText) {
properties['errorText'] = errorText;
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
properties['message'] = prefixFreeErrorText.substring(0, newlineIndex);
properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1);
}
}
}
return properties;
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.shift();
if (item) {
this.sendRequest(item);
}
}
}
private sendRequest(requestItem: RequestItem): void {
const serverRequest = requestItem.request;
this._tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq);
}
try {
this.write(serverRequest);
} catch (err) {
const callback = this.fetchCallback(serverRequest.seq);
if (callback) {
callback.onError(err);
}
}
}
private fetchCallback(seq: number) {
const callback = this._callbacks.fetch(seq);
if (!callback) {
return undefined;
}
this._pendingResponses.delete(seq);
return callback;
}
}
| {
args.push('--npmLocation', `"${configuration.npmLocation}"`);
} | conditional_block |
server.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as Proto from './protocol';
import { CancelledResponse, NoContentResponse, ServerResponse } from './typescriptService';
import API from './utils/api';
import { TsServerLogLevel, TypeScriptServiceConfiguration } from './utils/configuration';
import { Disposable } from './utils/dispose';
import * as electron from './utils/electron';
import LogDirectoryProvider from './utils/logDirectoryProvider';
import Logger from './utils/logger';
import { TypeScriptPluginPathsProvider } from './utils/pluginPathsProvider';
import { TypeScriptServerPlugin } from './utils/plugins';
import TelemetryReporter from './utils/telemetry';
import Tracer from './utils/tracer';
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider';
import { Reader } from './utils/wireProtocol';
interface CallbackItem<R> {
readonly onSuccess: (value: R) => void;
readonly onError: (err: any) => void;
readonly startTime: number;
readonly isAsync: boolean;
}
class CallbackMap<R extends Proto.Response> {
private readonly _callbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
private readonly _asyncCallbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
public destroy(cause: string): void {
const cancellation = new CancelledResponse(cause);
for (const callback of this._callbacks.values()) {
callback.onSuccess(cancellation);
}
this._callbacks.clear();
for (const callback of this._asyncCallbacks.values()) {
callback.onSuccess(cancellation);
}
this._asyncCallbacks.clear();
}
public add(seq: number, callback: CallbackItem<ServerResponse<R> | undefined>, isAsync: boolean) {
if (isAsync) {
this._asyncCallbacks.set(seq, callback);
} else {
this._callbacks.set(seq, callback);
}
}
public fetch(seq: number): CallbackItem<ServerResponse<R> | undefined> | undefined {
const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
this.delete(seq);
return callback;
}
private delete(seq: number) {
if (!this._callbacks.delete(seq)) {
this._asyncCallbacks.delete(seq);
}
}
}
interface RequestItem {
readonly request: Proto.Request;
readonly expectsResponse: boolean;
readonly isAsync: boolean;
}
class RequestQueue {
private readonly queue: RequestItem[] = [];
private sequenceNumber: number = 0;
public get length(): number {
return this.queue.length;
}
public push(item: RequestItem): void {
this.queue.push(item);
}
public shift(): RequestItem | undefined {
return this.queue.shift();
}
public tryCancelPendingRequest(seq: number): boolean {
for (let i = 0; i < this.queue.length; i++) {
if (this.queue[i].request.seq === seq) {
this.queue.splice(i, 1);
return true;
}
}
return false;
}
public createRequest(command: string, args: any): Proto.Request {
return {
seq: this.sequenceNumber++,
type: 'request',
command: command,
arguments: args
};
}
}
export class TypeScriptServerSpawner {
public constructor(
private readonly _versionProvider: TypeScriptVersionProvider,
private readonly _logDirectoryProvider: LogDirectoryProvider,
private readonly _pluginPathsProvider: TypeScriptPluginPathsProvider,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) { }
public spawn(
version: TypeScriptVersion,
configuration: TypeScriptServiceConfiguration,
plugins: ReadonlyArray<TypeScriptServerPlugin>
): TypeScriptServer {
const apiVersion = version.version || API.defaultVersion;
const { args, cancellationPipeName, tsServerLogFile } = this.getTsServerArgs(configuration, version, plugins);
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
if (tsServerLogFile) {
this._logger.info(`TSServer log file: ${tsServerLogFile}`);
} else {
this._logger.error('Could not create TSServer log directory');
}
}
this._logger.info('Forking TSServer');
const childProcess = electron.fork(version.tsServerPath, args, this.getForkOptions());
this._logger.info('Started TSServer');
return new TypeScriptServer(childProcess, tsServerLogFile, cancellationPipeName, this._logger, this._telemetryReporter, this._tracer);
}
private getForkOptions() {
const debugPort = TypeScriptServerSpawner.getDebugPort();
const tsServerForkOptions: electron.IForkOptions = {
execArgv: debugPort ? [`--inspect=${debugPort}`] : [],
};
return tsServerForkOptions;
}
private getTsServerArgs(
configuration: TypeScriptServiceConfiguration,
currentVersion: TypeScriptVersion,
plugins: ReadonlyArray<TypeScriptServerPlugin>,
): { args: string[], cancellationPipeName: string | undefined, tsServerLogFile: string | undefined } {
const args: string[] = [];
let cancellationPipeName: string | undefined = undefined;
let tsServerLogFile: string | undefined = undefined;
const apiVersion = currentVersion.version || API.defaultVersion;
if (apiVersion.gte(API.v206)) {
if (apiVersion.gte(API.v250)) {
args.push('--useInferredProjectPerProjectRoot');
} else {
args.push('--useSingleInferredProject');
}
if (configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition');
}
}
if (apiVersion.gte(API.v208)) {
args.push('--enableTelemetry');
}
if (apiVersion.gte(API.v222)) {
cancellationPipeName = electron.getTempFile('tscancellation');
args.push('--cancellationPipeName', cancellationPipeName + '*');
}
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
const logDir = this._logDirectoryProvider.getNewLogDirectory();
if (logDir) {
tsServerLogFile = path.join(logDir, `tsserver.log`);
args.push('--logVerbosity', TsServerLogLevel.toString(configuration.tsServerLogLevel));
args.push('--logFile', tsServerLogFile);
}
}
if (apiVersion.gte(API.v230)) {
const pluginPaths = this._pluginPathsProvider.getPluginPaths();
if (plugins.length) {
args.push('--globalPlugins', plugins.map(x => x.name).join(','));
if (currentVersion.path === this._versionProvider.defaultVersion.path) {
pluginPaths.push(...plugins.map(x => x.path));
}
}
if (pluginPaths.length !== 0) {
args.push('--pluginProbeLocations', pluginPaths.join(','));
}
}
if (apiVersion.gte(API.v234)) {
if (configuration.npmLocation) {
args.push('--npmLocation', `"${configuration.npmLocation}"`);
}
}
if (apiVersion.gte(API.v260)) {
args.push('--locale', TypeScriptServerSpawner.getTsLocale(configuration));
}
if (apiVersion.gte(API.v291)) {
args.push('--noGetErrOnBackgroundUpdate');
}
return { args, cancellationPipeName, tsServerLogFile };
}
private static getDebugPort(): number | undefined {
const value = process.env['TSS_DEBUG'];
if (value) {
const port = parseInt(value);
if (!isNaN(port)) {
return port;
}
}
return undefined;
}
private static isLoggingEnabled(apiVersion: API, configuration: TypeScriptServiceConfiguration) {
return apiVersion.gte(API.v222) &&
configuration.tsServerLogLevel !== TsServerLogLevel.Off;
}
private static getTsLocale(configuration: TypeScriptServiceConfiguration): string {
return configuration.locale
? configuration.locale
: vscode.env.language;
}
}
export class TypeScriptServer extends Disposable {
private readonly _reader: Reader<Proto.Response>;
private readonly _requestQueue = new RequestQueue();
private readonly _callbacks = new CallbackMap<Proto.Response>();
private readonly _pendingResponses = new Set<number>();
constructor(
private readonly _childProcess: cp.ChildProcess,
private readonly _tsServerLogFile: string | undefined,
private readonly _cancellationPipeName: string | undefined,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) {
super();
this._reader = new Reader<Proto.Response>(this._childProcess.stdout);
this._reader.onData(msg => this.dispatchMessage(msg));
this._childProcess.on('exit', code => this.handleExit(code));
this._childProcess.on('error', error => this.handleError(error));
}
private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>());
public readonly onEvent = this._onEvent.event;
private readonly _onExit = this._register(new vscode.EventEmitter<any>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
public readonly onError = this._onError.event;
public get onReaderError() { return this._reader.onError; }
public get tsServerLogFile() { return this._tsServerLogFile; }
public write(serverRequest: Proto.Request) {
this._childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
}
public dispose() {
super.dispose();
this._callbacks.destroy('server disposed');
this._pendingResponses.clear();
}
public kill() {
this._childProcess.kill();
}
private | (error: any) {
this._onExit.fire(error);
this._callbacks.destroy('server exited');
}
private handleError(error: any) {
this._onError.fire(error);
this._callbacks.destroy('server errored');
}
private dispatchMessage(message: Proto.Message) {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message as Proto.Response);
break;
case 'event':
const event = message as Proto.Event;
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq;
const p = this._callbacks.fetch(seq);
if (p) {
this._tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
p.onSuccess(undefined);
}
} else {
this._tracer.traceEvent(event);
this._onEvent.fire(event);
}
break;
default:
throw new Error(`Unknown message type ${message.type} received`);
}
} finally {
this.sendNextRequests();
}
}
private tryCancelRequest(seq: number, command: string): boolean {
try {
if (this._requestQueue.tryCancelPendingRequest(seq)) {
this._tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
return true;
}
if (this._cancellationPipeName) {
this._tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
try {
fs.writeFileSync(this._cancellationPipeName + seq, '');
} catch {
// noop
}
return true;
}
this._tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
return false;
} finally {
const callback = this.fetchCallback(seq);
if (callback) {
callback.onSuccess(new CancelledResponse(`Cancelled request ${seq} - ${command}`));
}
}
}
private dispatchResponse(response: Proto.Response) {
const callback = this.fetchCallback(response.request_seq);
if (!callback) {
return;
}
this._tracer.traceResponse(response, callback.startTime);
if (response.success) {
callback.onSuccess(response);
} else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(new NoContentResponse());
} else {
callback.onError(response);
}
}
public executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: vscode.CancellationToken, expectsResult: boolean }): Promise<any> {
const request = this._requestQueue.createRequest(command, args);
const requestInfo: RequestItem = {
request: request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync
};
let result: Promise<any>;
if (executeInfo.expectsResult) {
let wasCancelled = false;
result = new Promise<any>((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
wasCancelled = true;
this.tryCancelRequest(request.seq, command);
});
}
}).catch((err: any) => {
if (!wasCancelled) {
this._logger.error(`'${command}' request failed with error.`, err);
const properties = this.parseErrorText(err && err.message, command);
/* __GDPR__
"languageServiceErrorResponse" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"stack" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"errortext" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"${include}": [
"${TypeScriptCommonProperties}"
]
}
*/
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties);
}
throw err;
});
} else {
result = Promise.resolve(null);
}
this._requestQueue.push(requestInfo);
this.sendNextRequests();
return result;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private parseErrorText(errorText: string | undefined, command: string) {
const properties: ObjectMap<string> = Object.create(null);
properties['command'] = command;
if (errorText) {
properties['errorText'] = errorText;
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
properties['message'] = prefixFreeErrorText.substring(0, newlineIndex);
properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1);
}
}
}
return properties;
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.shift();
if (item) {
this.sendRequest(item);
}
}
}
private sendRequest(requestItem: RequestItem): void {
const serverRequest = requestItem.request;
this._tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq);
}
try {
this.write(serverRequest);
} catch (err) {
const callback = this.fetchCallback(serverRequest.seq);
if (callback) {
callback.onError(err);
}
}
}
private fetchCallback(seq: number) {
const callback = this._callbacks.fetch(seq);
if (!callback) {
return undefined;
}
this._pendingResponses.delete(seq);
return callback;
}
}
| handleExit | identifier_name |
server.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as Proto from './protocol';
import { CancelledResponse, NoContentResponse, ServerResponse } from './typescriptService';
import API from './utils/api';
import { TsServerLogLevel, TypeScriptServiceConfiguration } from './utils/configuration';
import { Disposable } from './utils/dispose';
import * as electron from './utils/electron';
import LogDirectoryProvider from './utils/logDirectoryProvider';
import Logger from './utils/logger';
import { TypeScriptPluginPathsProvider } from './utils/pluginPathsProvider';
import { TypeScriptServerPlugin } from './utils/plugins';
import TelemetryReporter from './utils/telemetry';
import Tracer from './utils/tracer';
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider';
import { Reader } from './utils/wireProtocol';
interface CallbackItem<R> {
readonly onSuccess: (value: R) => void;
readonly onError: (err: any) => void;
readonly startTime: number;
readonly isAsync: boolean;
}
class CallbackMap<R extends Proto.Response> {
private readonly _callbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
private readonly _asyncCallbacks = new Map<number, CallbackItem<ServerResponse<R> | undefined>>();
public destroy(cause: string): void {
const cancellation = new CancelledResponse(cause);
for (const callback of this._callbacks.values()) {
callback.onSuccess(cancellation);
}
this._callbacks.clear();
for (const callback of this._asyncCallbacks.values()) {
callback.onSuccess(cancellation);
}
this._asyncCallbacks.clear();
}
public add(seq: number, callback: CallbackItem<ServerResponse<R> | undefined>, isAsync: boolean) {
if (isAsync) {
this._asyncCallbacks.set(seq, callback);
} else {
this._callbacks.set(seq, callback);
}
}
public fetch(seq: number): CallbackItem<ServerResponse<R> | undefined> | undefined {
const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
this.delete(seq);
return callback;
}
private delete(seq: number) {
if (!this._callbacks.delete(seq)) {
this._asyncCallbacks.delete(seq);
}
}
}
interface RequestItem {
readonly request: Proto.Request;
readonly expectsResponse: boolean;
readonly isAsync: boolean;
}
class RequestQueue {
private readonly queue: RequestItem[] = [];
private sequenceNumber: number = 0;
public get length(): number {
return this.queue.length;
}
public push(item: RequestItem): void |
public shift(): RequestItem | undefined {
return this.queue.shift();
}
public tryCancelPendingRequest(seq: number): boolean {
for (let i = 0; i < this.queue.length; i++) {
if (this.queue[i].request.seq === seq) {
this.queue.splice(i, 1);
return true;
}
}
return false;
}
public createRequest(command: string, args: any): Proto.Request {
return {
seq: this.sequenceNumber++,
type: 'request',
command: command,
arguments: args
};
}
}
export class TypeScriptServerSpawner {
public constructor(
private readonly _versionProvider: TypeScriptVersionProvider,
private readonly _logDirectoryProvider: LogDirectoryProvider,
private readonly _pluginPathsProvider: TypeScriptPluginPathsProvider,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) { }
public spawn(
version: TypeScriptVersion,
configuration: TypeScriptServiceConfiguration,
plugins: ReadonlyArray<TypeScriptServerPlugin>
): TypeScriptServer {
const apiVersion = version.version || API.defaultVersion;
const { args, cancellationPipeName, tsServerLogFile } = this.getTsServerArgs(configuration, version, plugins);
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
if (tsServerLogFile) {
this._logger.info(`TSServer log file: ${tsServerLogFile}`);
} else {
this._logger.error('Could not create TSServer log directory');
}
}
this._logger.info('Forking TSServer');
const childProcess = electron.fork(version.tsServerPath, args, this.getForkOptions());
this._logger.info('Started TSServer');
return new TypeScriptServer(childProcess, tsServerLogFile, cancellationPipeName, this._logger, this._telemetryReporter, this._tracer);
}
private getForkOptions() {
const debugPort = TypeScriptServerSpawner.getDebugPort();
const tsServerForkOptions: electron.IForkOptions = {
execArgv: debugPort ? [`--inspect=${debugPort}`] : [],
};
return tsServerForkOptions;
}
private getTsServerArgs(
configuration: TypeScriptServiceConfiguration,
currentVersion: TypeScriptVersion,
plugins: ReadonlyArray<TypeScriptServerPlugin>,
): { args: string[], cancellationPipeName: string | undefined, tsServerLogFile: string | undefined } {
const args: string[] = [];
let cancellationPipeName: string | undefined = undefined;
let tsServerLogFile: string | undefined = undefined;
const apiVersion = currentVersion.version || API.defaultVersion;
if (apiVersion.gte(API.v206)) {
if (apiVersion.gte(API.v250)) {
args.push('--useInferredProjectPerProjectRoot');
} else {
args.push('--useSingleInferredProject');
}
if (configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition');
}
}
if (apiVersion.gte(API.v208)) {
args.push('--enableTelemetry');
}
if (apiVersion.gte(API.v222)) {
cancellationPipeName = electron.getTempFile('tscancellation');
args.push('--cancellationPipeName', cancellationPipeName + '*');
}
if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) {
const logDir = this._logDirectoryProvider.getNewLogDirectory();
if (logDir) {
tsServerLogFile = path.join(logDir, `tsserver.log`);
args.push('--logVerbosity', TsServerLogLevel.toString(configuration.tsServerLogLevel));
args.push('--logFile', tsServerLogFile);
}
}
if (apiVersion.gte(API.v230)) {
const pluginPaths = this._pluginPathsProvider.getPluginPaths();
if (plugins.length) {
args.push('--globalPlugins', plugins.map(x => x.name).join(','));
if (currentVersion.path === this._versionProvider.defaultVersion.path) {
pluginPaths.push(...plugins.map(x => x.path));
}
}
if (pluginPaths.length !== 0) {
args.push('--pluginProbeLocations', pluginPaths.join(','));
}
}
if (apiVersion.gte(API.v234)) {
if (configuration.npmLocation) {
args.push('--npmLocation', `"${configuration.npmLocation}"`);
}
}
if (apiVersion.gte(API.v260)) {
args.push('--locale', TypeScriptServerSpawner.getTsLocale(configuration));
}
if (apiVersion.gte(API.v291)) {
args.push('--noGetErrOnBackgroundUpdate');
}
return { args, cancellationPipeName, tsServerLogFile };
}
private static getDebugPort(): number | undefined {
const value = process.env['TSS_DEBUG'];
if (value) {
const port = parseInt(value);
if (!isNaN(port)) {
return port;
}
}
return undefined;
}
private static isLoggingEnabled(apiVersion: API, configuration: TypeScriptServiceConfiguration) {
return apiVersion.gte(API.v222) &&
configuration.tsServerLogLevel !== TsServerLogLevel.Off;
}
private static getTsLocale(configuration: TypeScriptServiceConfiguration): string {
return configuration.locale
? configuration.locale
: vscode.env.language;
}
}
export class TypeScriptServer extends Disposable {
private readonly _reader: Reader<Proto.Response>;
private readonly _requestQueue = new RequestQueue();
private readonly _callbacks = new CallbackMap<Proto.Response>();
private readonly _pendingResponses = new Set<number>();
constructor(
private readonly _childProcess: cp.ChildProcess,
private readonly _tsServerLogFile: string | undefined,
private readonly _cancellationPipeName: string | undefined,
private readonly _logger: Logger,
private readonly _telemetryReporter: TelemetryReporter,
private readonly _tracer: Tracer,
) {
super();
this._reader = new Reader<Proto.Response>(this._childProcess.stdout);
this._reader.onData(msg => this.dispatchMessage(msg));
this._childProcess.on('exit', code => this.handleExit(code));
this._childProcess.on('error', error => this.handleError(error));
}
private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>());
public readonly onEvent = this._onEvent.event;
private readonly _onExit = this._register(new vscode.EventEmitter<any>());
public readonly onExit = this._onExit.event;
private readonly _onError = this._register(new vscode.EventEmitter<any>());
public readonly onError = this._onError.event;
public get onReaderError() { return this._reader.onError; }
public get tsServerLogFile() { return this._tsServerLogFile; }
public write(serverRequest: Proto.Request) {
this._childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
}
public dispose() {
super.dispose();
this._callbacks.destroy('server disposed');
this._pendingResponses.clear();
}
public kill() {
this._childProcess.kill();
}
private handleExit(error: any) {
this._onExit.fire(error);
this._callbacks.destroy('server exited');
}
private handleError(error: any) {
this._onError.fire(error);
this._callbacks.destroy('server errored');
}
private dispatchMessage(message: Proto.Message) {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message as Proto.Response);
break;
case 'event':
const event = message as Proto.Event;
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq;
const p = this._callbacks.fetch(seq);
if (p) {
this._tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
p.onSuccess(undefined);
}
} else {
this._tracer.traceEvent(event);
this._onEvent.fire(event);
}
break;
default:
throw new Error(`Unknown message type ${message.type} received`);
}
} finally {
this.sendNextRequests();
}
}
private tryCancelRequest(seq: number, command: string): boolean {
try {
if (this._requestQueue.tryCancelPendingRequest(seq)) {
this._tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
return true;
}
if (this._cancellationPipeName) {
this._tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
try {
fs.writeFileSync(this._cancellationPipeName + seq, '');
} catch {
// noop
}
return true;
}
this._tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
return false;
} finally {
const callback = this.fetchCallback(seq);
if (callback) {
callback.onSuccess(new CancelledResponse(`Cancelled request ${seq} - ${command}`));
}
}
}
private dispatchResponse(response: Proto.Response) {
const callback = this.fetchCallback(response.request_seq);
if (!callback) {
return;
}
this._tracer.traceResponse(response, callback.startTime);
if (response.success) {
callback.onSuccess(response);
} else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(new NoContentResponse());
} else {
callback.onError(response);
}
}
public executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: vscode.CancellationToken, expectsResult: boolean }): Promise<any> {
const request = this._requestQueue.createRequest(command, args);
const requestInfo: RequestItem = {
request: request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync
};
let result: Promise<any>;
if (executeInfo.expectsResult) {
let wasCancelled = false;
result = new Promise<any>((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
wasCancelled = true;
this.tryCancelRequest(request.seq, command);
});
}
}).catch((err: any) => {
if (!wasCancelled) {
this._logger.error(`'${command}' request failed with error.`, err);
const properties = this.parseErrorText(err && err.message, command);
/* __GDPR__
"languageServiceErrorResponse" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"stack" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"errortext" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
"${include}": [
"${TypeScriptCommonProperties}"
]
}
*/
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties);
}
throw err;
});
} else {
result = Promise.resolve(null);
}
this._requestQueue.push(requestInfo);
this.sendNextRequests();
return result;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private parseErrorText(errorText: string | undefined, command: string) {
const properties: ObjectMap<string> = Object.create(null);
properties['command'] = command;
if (errorText) {
properties['errorText'] = errorText;
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
properties['message'] = prefixFreeErrorText.substring(0, newlineIndex);
properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1);
}
}
}
return properties;
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.shift();
if (item) {
this.sendRequest(item);
}
}
}
private sendRequest(requestItem: RequestItem): void {
const serverRequest = requestItem.request;
this._tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq);
}
try {
this.write(serverRequest);
} catch (err) {
const callback = this.fetchCallback(serverRequest.seq);
if (callback) {
callback.onError(err);
}
}
}
private fetchCallback(seq: number) {
const callback = this._callbacks.fetch(seq);
if (!callback) {
return undefined;
}
this._pendingResponses.delete(seq);
return callback;
}
}
| {
this.queue.push(item);
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(int_uint)]
extern crate devtools_traits;
extern crate geom;
extern crate libc;
extern crate msg;
extern crate net;
extern crate util;
extern crate url;
// This module contains traits in script used generically
// in the rest of Servo.
// The traits are here instead of in script so
// that these modules won't have to depend on script.
use devtools_traits::DevtoolsControlChan;
use libc::c_void;
use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData};
use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers};
use msg::constellation_msg::PipelineExitType;
use msg::compositor_msg::ScriptListener;
use net::image_cache_task::ImageCacheTask;
use net::resource_task::ResourceTask;
use net::storage_task::StorageTask;
use util::smallvec::SmallVec1;
use std::any::Any;
use std::sync::mpsc::{Sender, Receiver};
use geom::point::Point2D;
use geom::rect::Rect;
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
pub struct | {
pub containing_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: Box<Any+Send>, // opaque reference to a LayoutChannel
pub load_data: LoadData,
}
/// Messages sent from the constellation to the script task
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, PipelineExitType),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script that reflow is finished.
ReflowComplete(PipelineId, uint),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, String, Option<String>),
}
unsafe impl Send for ConstellationControlMsg {
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
ResizeEvent(WindowSizeData),
ReflowEvent(SmallVec1<UntrustedNodeAddress>),
ClickEvent(uint, Point2D<f32>),
MouseDownEvent(uint, Point2D<f32>),
MouseUpEvent(uint, Point2D<f32>),
MouseMoveEvent(Point2D<f32>),
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>));
/// Encapsulates external communication with the script task.
#[derive(Clone)]
pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>);
pub trait ScriptTaskFactory {
fn create<C>(_phantom: Option<&mut Self>,
id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_msg: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: Option<WindowSizeData>,
load_data: LoadData)
where C: ScriptListener + Send;
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any+Send>;
}
| NewLayoutInfo | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(int_uint)]
extern crate devtools_traits;
extern crate geom;
extern crate libc;
extern crate msg;
extern crate net;
extern crate util;
extern crate url;
// This module contains traits in script used generically
// in the rest of Servo.
// The traits are here instead of in script so
// that these modules won't have to depend on script.
use devtools_traits::DevtoolsControlChan;
use libc::c_void;
use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData};
use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers};
use msg::constellation_msg::PipelineExitType;
use msg::compositor_msg::ScriptListener;
use net::image_cache_task::ImageCacheTask;
use net::resource_task::ResourceTask;
use net::storage_task::StorageTask;
use util::smallvec::SmallVec1; |
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
pub struct NewLayoutInfo {
pub containing_pipeline_id: PipelineId,
pub new_pipeline_id: PipelineId,
pub subpage_id: SubpageId,
pub layout_chan: Box<Any+Send>, // opaque reference to a LayoutChannel
pub load_data: LoadData,
}
/// Messages sent from the constellation to the script task
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, PipelineExitType),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script that reflow is finished.
ReflowComplete(PipelineId, uint),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, String, Option<String>),
}
unsafe impl Send for ConstellationControlMsg {
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
ResizeEvent(WindowSizeData),
ReflowEvent(SmallVec1<UntrustedNodeAddress>),
ClickEvent(uint, Point2D<f32>),
MouseDownEvent(uint, Point2D<f32>),
MouseUpEvent(uint, Point2D<f32>),
MouseMoveEvent(Point2D<f32>),
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>));
/// Encapsulates external communication with the script task.
#[derive(Clone)]
pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>);
pub trait ScriptTaskFactory {
fn create<C>(_phantom: Option<&mut Self>,
id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
compositor: C,
layout_chan: &OpaqueScriptLayoutChannel,
control_chan: ScriptControlChan,
control_port: Receiver<ConstellationControlMsg>,
constellation_msg: ConstellationChan,
failure_msg: Failure,
resource_task: ResourceTask,
storage_task: StorageTask,
image_cache_task: ImageCacheTask,
devtools_chan: Option<DevtoolsControlChan>,
window_size: Option<WindowSizeData>,
load_data: LoadData)
where C: ScriptListener + Send;
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any+Send>;
} | use std::any::Any;
use std::sync::mpsc::{Sender, Receiver};
use geom::point::Point2D;
use geom::rect::Rect; | random_line_split |
test_decorators.py | # Copyright 2013 IBM Corp
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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.
import uuid
import testtools
from tempest.lib import base as test
from tempest.lib import decorators
from tempest.tests.lib import base
class TestSkipBecauseDecorator(base.TestCase):
def _test_skip_because_helper(self, expected_to_skip=True,
**decorator_args):
class TestFoo(test.BaseTestCase):
_interface = 'json'
@decorators.skip_because(**decorator_args)
def test_bar(self):
return 0
t = TestFoo('test_bar')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException, t.test_bar)
else:
# assert that test_bar returned 0
self.assertEqual(TestFoo('test_bar').test_bar(), 0)
def test_skip_because_bug(self):
self._test_skip_because_helper(bug='12345')
def test_skip_because_bug_and_condition_true(self):
self._test_skip_because_helper(bug='12348', condition=True)
def test_skip_because_bug_and_condition_false(self):
self._test_skip_because_helper(expected_to_skip=False,
bug='12349', condition=False)
def test_skip_because_bug_without_bug_never_skips(self):
"""Never skip without a bug parameter."""
self._test_skip_because_helper(expected_to_skip=False,
condition=True)
self._test_skip_because_helper(expected_to_skip=False)
def test_skip_because_invalid_bug_number(self):
"""Raise ValueError if with an invalid bug number"""
self.assertRaises(ValueError, self._test_skip_because_helper,
bug='critical_bug')
class TestIdempotentIdDecorator(base.TestCase):
def _test_helper(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
"""Docstring"""
pass
return foo
def _test_helper_without_doc(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
pass
return foo
def test_positive(self):
_id = str(uuid.uuid4())
foo = self._test_helper(_id)
self.assertIn('id-%s' % _id, getattr(foo, '__testtools_attrs'))
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_positive_without_doc(self):
_id = str(uuid.uuid4())
foo = self._test_helper_without_doc(_id)
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_idempotent_id_not_str(self):
_id = 42
self.assertRaises(TypeError, self._test_helper, _id)
def test_idempotent_id_not_valid_uuid(self):
_id = '42'
self.assertRaises(ValueError, self._test_helper, _id)
class TestSkipUnlessAttrDecorator(base.TestCase):
def _test_skip_unless_attr(self, attr, expected_to_skip=True):
class TestFoo(test.BaseTestCase):
expected_attr = not expected_to_skip
@decorators.skip_unless_attr(attr)
def test_foo(self):
pass
t = TestFoo('test_foo')
if expected_to_skip:
|
else:
try:
t.test_foo()
except Exception:
raise testtools.TestCase.failureException()
def test_skip_attr_does_not_exist(self):
self._test_skip_unless_attr('unexpected_attr')
def test_skip_attr_false(self):
self._test_skip_unless_attr('expected_attr')
def test_no_skip_for_attr_exist_and_true(self):
self._test_skip_unless_attr('expected_attr', expected_to_skip=False)
| self.assertRaises(testtools.TestCase.skipException,
t.test_foo()) | conditional_block |
test_decorators.py | # Copyright 2013 IBM Corp
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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.
import uuid
import testtools
from tempest.lib import base as test
from tempest.lib import decorators
from tempest.tests.lib import base
class TestSkipBecauseDecorator(base.TestCase):
def _test_skip_because_helper(self, expected_to_skip=True,
**decorator_args):
class TestFoo(test.BaseTestCase):
_interface = 'json'
@decorators.skip_because(**decorator_args)
def test_bar(self):
return 0
t = TestFoo('test_bar')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException, t.test_bar)
else:
# assert that test_bar returned 0
self.assertEqual(TestFoo('test_bar').test_bar(), 0)
def test_skip_because_bug(self):
self._test_skip_because_helper(bug='12345')
def test_skip_because_bug_and_condition_true(self):
self._test_skip_because_helper(bug='12348', condition=True)
def test_skip_because_bug_and_condition_false(self):
self._test_skip_because_helper(expected_to_skip=False,
bug='12349', condition=False)
def test_skip_because_bug_without_bug_never_skips(self):
"""Never skip without a bug parameter."""
self._test_skip_because_helper(expected_to_skip=False,
condition=True)
self._test_skip_because_helper(expected_to_skip=False)
def test_skip_because_invalid_bug_number(self):
"""Raise ValueError if with an invalid bug number"""
self.assertRaises(ValueError, self._test_skip_because_helper,
bug='critical_bug')
class TestIdempotentIdDecorator(base.TestCase):
def _test_helper(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
"""Docstring"""
pass
return foo
def _test_helper_without_doc(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
pass
return foo
def test_positive(self):
_id = str(uuid.uuid4())
foo = self._test_helper(_id)
self.assertIn('id-%s' % _id, getattr(foo, '__testtools_attrs'))
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_positive_without_doc(self):
_id = str(uuid.uuid4())
foo = self._test_helper_without_doc(_id)
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_idempotent_id_not_str(self):
_id = 42
self.assertRaises(TypeError, self._test_helper, _id)
def test_idempotent_id_not_valid_uuid(self):
_id = '42'
self.assertRaises(ValueError, self._test_helper, _id)
class TestSkipUnlessAttrDecorator(base.TestCase):
def _test_skip_unless_attr(self, attr, expected_to_skip=True):
class TestFoo(test.BaseTestCase):
|
t = TestFoo('test_foo')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException,
t.test_foo())
else:
try:
t.test_foo()
except Exception:
raise testtools.TestCase.failureException()
def test_skip_attr_does_not_exist(self):
self._test_skip_unless_attr('unexpected_attr')
def test_skip_attr_false(self):
self._test_skip_unless_attr('expected_attr')
def test_no_skip_for_attr_exist_and_true(self):
self._test_skip_unless_attr('expected_attr', expected_to_skip=False)
| expected_attr = not expected_to_skip
@decorators.skip_unless_attr(attr)
def test_foo(self):
pass | identifier_body |
test_decorators.py | # Copyright 2013 IBM Corp
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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.
import uuid
import testtools
from tempest.lib import base as test
from tempest.lib import decorators
from tempest.tests.lib import base
class TestSkipBecauseDecorator(base.TestCase):
def _test_skip_because_helper(self, expected_to_skip=True,
**decorator_args):
class TestFoo(test.BaseTestCase):
_interface = 'json'
@decorators.skip_because(**decorator_args)
def test_bar(self):
return 0
t = TestFoo('test_bar')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException, t.test_bar)
else:
# assert that test_bar returned 0
self.assertEqual(TestFoo('test_bar').test_bar(), 0)
def test_skip_because_bug(self):
self._test_skip_because_helper(bug='12345')
def test_skip_because_bug_and_condition_true(self):
self._test_skip_because_helper(bug='12348', condition=True)
def test_skip_because_bug_and_condition_false(self):
self._test_skip_because_helper(expected_to_skip=False,
bug='12349', condition=False)
def | (self):
"""Never skip without a bug parameter."""
self._test_skip_because_helper(expected_to_skip=False,
condition=True)
self._test_skip_because_helper(expected_to_skip=False)
def test_skip_because_invalid_bug_number(self):
"""Raise ValueError if with an invalid bug number"""
self.assertRaises(ValueError, self._test_skip_because_helper,
bug='critical_bug')
class TestIdempotentIdDecorator(base.TestCase):
def _test_helper(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
"""Docstring"""
pass
return foo
def _test_helper_without_doc(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
pass
return foo
def test_positive(self):
_id = str(uuid.uuid4())
foo = self._test_helper(_id)
self.assertIn('id-%s' % _id, getattr(foo, '__testtools_attrs'))
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_positive_without_doc(self):
_id = str(uuid.uuid4())
foo = self._test_helper_without_doc(_id)
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_idempotent_id_not_str(self):
_id = 42
self.assertRaises(TypeError, self._test_helper, _id)
def test_idempotent_id_not_valid_uuid(self):
_id = '42'
self.assertRaises(ValueError, self._test_helper, _id)
class TestSkipUnlessAttrDecorator(base.TestCase):
def _test_skip_unless_attr(self, attr, expected_to_skip=True):
class TestFoo(test.BaseTestCase):
expected_attr = not expected_to_skip
@decorators.skip_unless_attr(attr)
def test_foo(self):
pass
t = TestFoo('test_foo')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException,
t.test_foo())
else:
try:
t.test_foo()
except Exception:
raise testtools.TestCase.failureException()
def test_skip_attr_does_not_exist(self):
self._test_skip_unless_attr('unexpected_attr')
def test_skip_attr_false(self):
self._test_skip_unless_attr('expected_attr')
def test_no_skip_for_attr_exist_and_true(self):
self._test_skip_unless_attr('expected_attr', expected_to_skip=False)
| test_skip_because_bug_without_bug_never_skips | identifier_name |
test_decorators.py | # Copyright 2013 IBM Corp
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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.
import uuid
import testtools
from tempest.lib import base as test | class TestSkipBecauseDecorator(base.TestCase):
def _test_skip_because_helper(self, expected_to_skip=True,
**decorator_args):
class TestFoo(test.BaseTestCase):
_interface = 'json'
@decorators.skip_because(**decorator_args)
def test_bar(self):
return 0
t = TestFoo('test_bar')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException, t.test_bar)
else:
# assert that test_bar returned 0
self.assertEqual(TestFoo('test_bar').test_bar(), 0)
def test_skip_because_bug(self):
self._test_skip_because_helper(bug='12345')
def test_skip_because_bug_and_condition_true(self):
self._test_skip_because_helper(bug='12348', condition=True)
def test_skip_because_bug_and_condition_false(self):
self._test_skip_because_helper(expected_to_skip=False,
bug='12349', condition=False)
def test_skip_because_bug_without_bug_never_skips(self):
"""Never skip without a bug parameter."""
self._test_skip_because_helper(expected_to_skip=False,
condition=True)
self._test_skip_because_helper(expected_to_skip=False)
def test_skip_because_invalid_bug_number(self):
"""Raise ValueError if with an invalid bug number"""
self.assertRaises(ValueError, self._test_skip_because_helper,
bug='critical_bug')
class TestIdempotentIdDecorator(base.TestCase):
def _test_helper(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
"""Docstring"""
pass
return foo
def _test_helper_without_doc(self, _id, **decorator_args):
@decorators.idempotent_id(_id)
def foo():
pass
return foo
def test_positive(self):
_id = str(uuid.uuid4())
foo = self._test_helper(_id)
self.assertIn('id-%s' % _id, getattr(foo, '__testtools_attrs'))
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_positive_without_doc(self):
_id = str(uuid.uuid4())
foo = self._test_helper_without_doc(_id)
self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id))
def test_idempotent_id_not_str(self):
_id = 42
self.assertRaises(TypeError, self._test_helper, _id)
def test_idempotent_id_not_valid_uuid(self):
_id = '42'
self.assertRaises(ValueError, self._test_helper, _id)
class TestSkipUnlessAttrDecorator(base.TestCase):
def _test_skip_unless_attr(self, attr, expected_to_skip=True):
class TestFoo(test.BaseTestCase):
expected_attr = not expected_to_skip
@decorators.skip_unless_attr(attr)
def test_foo(self):
pass
t = TestFoo('test_foo')
if expected_to_skip:
self.assertRaises(testtools.TestCase.skipException,
t.test_foo())
else:
try:
t.test_foo()
except Exception:
raise testtools.TestCase.failureException()
def test_skip_attr_does_not_exist(self):
self._test_skip_unless_attr('unexpected_attr')
def test_skip_attr_false(self):
self._test_skip_unless_attr('expected_attr')
def test_no_skip_for_attr_exist_and_true(self):
self._test_skip_unless_attr('expected_attr', expected_to_skip=False) | from tempest.lib import decorators
from tempest.tests.lib import base
| random_line_split |
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
use std::sync;
fn assert_both<T: Sync + Send>() {}
fn | () {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
}
| main | identifier_name |
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
use std::sync;
fn assert_both<T: Sync + Send>() {}
fn main() | {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
} | identifier_body | |
std-sync-right-kind-impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(static_mutex, static_rwlock, static_condvar)]
#![feature(arc_weak, semaphore)]
|
fn assert_both<T: Sync + Send>() {}
fn main() {
assert_both::<sync::StaticMutex>();
assert_both::<sync::StaticCondvar>();
assert_both::<sync::StaticRwLock>();
assert_both::<sync::Mutex<()>>();
assert_both::<sync::Condvar>();
assert_both::<sync::RwLock<()>>();
assert_both::<sync::Semaphore>();
assert_both::<sync::Barrier>();
assert_both::<sync::Arc<()>>();
assert_both::<sync::Weak<()>>();
assert_both::<sync::Once>();
} | use std::sync; | random_line_split |
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
| use arena::TypedArena;
#[cfg(not(test))]
fn main() {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} | random_line_split | |
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
use arena::TypedArena;
#[cfg(not(test))]
fn | () {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
}
| main | identifier_name |
arena_storage_pool.rs | // Implements http://rosettacode.org/wiki/Arena_storage_pool
#![feature(rustc_private)]
extern crate arena;
use arena::TypedArena;
#[cfg(not(test))]
fn main() | {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} | identifier_body | |
common.rs | pub const SYS_DEBUG: usize = 0;
// Linux compatible
pub const SYS_BRK: usize = 45;
pub const SYS_CHDIR: usize = 12;
pub const SYS_CLOSE: usize = 6;
pub const SYS_CLONE: usize = 120;
pub const CLONE_VM: usize = 0x100;
pub const CLONE_FS: usize = 0x200;
pub const CLONE_FILES: usize = 0x400;
pub const SYS_CLOCK_GETTIME: usize = 265;
pub const CLOCK_REALTIME: usize = 0;
pub const CLOCK_MONOTONIC: usize = 1;
pub const SYS_DUP: usize = 41;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1;
pub const SYS_FPATH: usize = 3001;
pub const SYS_FSTAT: usize = 28;
pub const SYS_FSYNC: usize = 118;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_LINK: usize = 9;
pub const SYS_LSEEK: usize = 19;
pub const SEEK_SET: usize = 0;
pub const SEEK_CUR: usize = 1;
pub const SEEK_END: usize = 2;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const O_RDONLY: usize = 0;
pub const O_WRONLY: usize = 1;
pub const O_RDWR: usize = 2;
pub const O_NONBLOCK: usize = 4;
pub const O_APPEND: usize = 8;
pub const O_SHLOCK: usize = 0x10;
pub const O_EXLOCK: usize = 0x20;
pub const O_ASYNC: usize = 0x40;
pub const O_FSYNC: usize = 0x80;
pub const O_CREAT: usize = 0x200;
pub const O_TRUNC: usize = 0x400;
pub const O_EXCL: usize = 0x800;
pub const SYS_READ: usize = 3;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;
// Rust Memory
pub const SYS_ALLOC: usize = 1000;
pub const SYS_REALLOC: usize = 1001;
pub const SYS_REALLOC_INPLACE: usize = 1002;
pub const SYS_UNALLOC: usize = 1003;
// Structures
#[repr(packed)]
pub struct | {
pub tv_sec: i64,
pub tv_nsec: i32,
}
| TimeSpec | identifier_name |
common.rs | pub const SYS_DEBUG: usize = 0;
// Linux compatible
pub const SYS_BRK: usize = 45;
pub const SYS_CHDIR: usize = 12; | pub const SYS_CLOCK_GETTIME: usize = 265;
pub const CLOCK_REALTIME: usize = 0;
pub const CLOCK_MONOTONIC: usize = 1;
pub const SYS_DUP: usize = 41;
pub const SYS_EXECVE: usize = 11;
pub const SYS_EXIT: usize = 1;
pub const SYS_FPATH: usize = 3001;
pub const SYS_FSTAT: usize = 28;
pub const SYS_FSYNC: usize = 118;
pub const SYS_FTRUNCATE: usize = 93;
pub const SYS_LINK: usize = 9;
pub const SYS_LSEEK: usize = 19;
pub const SEEK_SET: usize = 0;
pub const SEEK_CUR: usize = 1;
pub const SEEK_END: usize = 2;
pub const SYS_MKDIR: usize = 39;
pub const SYS_NANOSLEEP: usize = 162;
pub const SYS_OPEN: usize = 5;
pub const O_RDONLY: usize = 0;
pub const O_WRONLY: usize = 1;
pub const O_RDWR: usize = 2;
pub const O_NONBLOCK: usize = 4;
pub const O_APPEND: usize = 8;
pub const O_SHLOCK: usize = 0x10;
pub const O_EXLOCK: usize = 0x20;
pub const O_ASYNC: usize = 0x40;
pub const O_FSYNC: usize = 0x80;
pub const O_CREAT: usize = 0x200;
pub const O_TRUNC: usize = 0x400;
pub const O_EXCL: usize = 0x800;
pub const SYS_READ: usize = 3;
pub const SYS_UNLINK: usize = 10;
pub const SYS_WRITE: usize = 4;
pub const SYS_YIELD: usize = 158;
// Rust Memory
pub const SYS_ALLOC: usize = 1000;
pub const SYS_REALLOC: usize = 1001;
pub const SYS_REALLOC_INPLACE: usize = 1002;
pub const SYS_UNALLOC: usize = 1003;
// Structures
#[repr(packed)]
pub struct TimeSpec {
pub tv_sec: i64,
pub tv_nsec: i32,
} | pub const SYS_CLOSE: usize = 6;
pub const SYS_CLONE: usize = 120;
pub const CLONE_VM: usize = 0x100;
pub const CLONE_FS: usize = 0x200;
pub const CLONE_FILES: usize = 0x400; | random_line_split |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn row_len(&mut self) -> ImageResult<usize> {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
}
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> { |
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
} | let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
}; | random_line_split |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn row_len(&mut self) -> ImageResult<usize> |
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> {
let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
};
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
}
| {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
} | identifier_body |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// Create a new decoder that decodes from the stream ```r```
pub fn new(r: R) -> JPEGDecoder<R> {
JPEGDecoder {
decoder: jpeg_decoder::Decoder::new(r),
metadata: None,
}
}
fn metadata(&mut self) -> ImageResult<jpeg_decoder::ImageInfo> {
match self.metadata {
Some(metadata) => Ok(metadata),
None => {
try!(self.decoder.read_info());
let mut metadata = self.decoder.info().unwrap();
// We convert CMYK data to RGB before returning it to the user.
if metadata.pixel_format == jpeg_decoder::PixelFormat::CMYK32 {
metadata.pixel_format = jpeg_decoder::PixelFormat::RGB24;
}
self.metadata = Some(metadata);
Ok(metadata)
},
}
}
}
impl<R: Read> ImageDecoder for JPEGDecoder<R> {
fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((metadata.width as u32, metadata.height as u32))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn | (&mut self) -> ImageResult<usize> {
let metadata = try!(self.metadata());
Ok(metadata.width as usize * color::num_components(metadata.pixel_format.into()))
}
fn read_scanline(&mut self, _buf: &mut [u8]) -> ImageResult<u32> {
unimplemented!();
}
fn read_image(&mut self) -> ImageResult<DecodingResult> {
let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
};
Ok(DecodingResult::U8(data))
}
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = pixel[0] as f32 / 255.0;
let m = pixel[1] as f32 / 255.0;
let y = pixel[2] as f32 / 255.0;
let k = pixel[3] as f32 / 255.0;
// CMYK -> CMY
let c = c * (1.0 - k) + k;
let m = m * (1.0 - k) + k;
let y = y * (1.0 - k) + k;
// CMY -> RGB
let r = (1.0 - c) * 255.0;
let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0;
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
L8 => ColorType::Gray(8),
RGB24 => ColorType::RGB(8),
CMYK32 => panic!(),
}
}
}
impl From<jpeg_decoder::Error> for ImageError {
fn from(err: jpeg_decoder::Error) -> ImageError {
use self::jpeg_decoder::Error::*;
match err {
Format(desc) => ImageError::FormatError(desc),
Unsupported(desc) => ImageError::UnsupportedError(format!("{:?}", desc)),
Io(err) => ImageError::IoError(err),
Internal(err) => ImageError::FormatError(err.description().to_owned()),
}
}
}
| row_len | identifier_name |
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_quux<T:Quux>(t: &T) -> &Quux |
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
}
fn main() {
}
| {
t
} | identifier_body |
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_quux<T:Quux>(t: &T) -> &Quux {
t
}
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
} | fn main() {
} | random_line_split | |
object-safety-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that we correctly prevent users from making trait objects
// from traits with generic methods, unless `where Self : Sized` is
// present.
trait Bar {
fn bar<T>(&self, t: T);
}
trait Quux {
fn bar<T>(&self, t: T)
where Self : Sized;
}
fn make_bar<T:Bar>(t: &T) -> &Bar {
t
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn make_bar_explicit<T:Bar>(t: &T) -> &Bar {
t as &Bar
//~^ ERROR `Bar` is not object-safe
//~| NOTE method `bar` has generic type parameters
}
fn | <T:Quux>(t: &T) -> &Quux {
t
}
fn make_quux_explicit<T:Quux>(t: &T) -> &Quux {
t as &Quux
}
fn main() {
}
| make_quux | identifier_name |
Coordinate.js | import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'
/**
@internal
*/
class Coordinate {
/**
@param {Array} path the address of a property, such as ['text_1', 'content']
@param {int} offset the position in the property
*/
constructor(path, offset) {
// HACK: to allow this class be inherited but without calling this ctor
if (arguments[0] === 'SKIP') return
if (arguments.length === 1) {
let data = arguments[0]
this.path = data.path
this.offset = data.offset
} else {
this.path = path
this.offset = offset
}
if (!isArray(this.path)) {
throw new Error('Invalid arguments: path should be an array.')
}
if (!isNumber(this.offset) || this.offset < 0) {
throw new Error('Invalid arguments: offset must be a positive number.')
}
}
equals(other) {
return (other === this ||
(isArrayEqual(other.path, this.path) && other.offset === this.offset) )
}
withCharPos(offset) {
return new Coordinate(this.path, offset)
}
getNodeId() {
return this.path[0]
}
getPath() {
return this.path
}
getOffset() |
toJSON() {
return {
path: this.path.slice(),
offset: this.offset
}
}
toString() {
return "(" + this.path.join('.') + ", " + this.offset + ")"
}
isPropertyCoordinate() {
return this.path.length > 1
}
isNodeCoordinate() {
return this.path.length === 1
}
hasSamePath(other) {
return isArrayEqual(this.path, other.path)
}
}
Coordinate.prototype._isCoordinate = true
export default Coordinate
| {
return this.offset
} | identifier_body |
Coordinate.js | import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'
/**
@internal
*/
class Coordinate {
/**
@param {Array} path the address of a property, such as ['text_1', 'content']
@param {int} offset the position in the property
*/
constructor(path, offset) {
// HACK: to allow this class be inherited but without calling this ctor
if (arguments[0] === 'SKIP') return
if (arguments.length === 1) {
let data = arguments[0]
this.path = data.path
this.offset = data.offset
} else {
this.path = path
this.offset = offset
}
if (!isArray(this.path)) {
throw new Error('Invalid arguments: path should be an array.')
}
if (!isNumber(this.offset) || this.offset < 0) {
throw new Error('Invalid arguments: offset must be a positive number.')
}
}
equals(other) {
return (other === this ||
(isArrayEqual(other.path, this.path) && other.offset === this.offset) )
}
withCharPos(offset) {
return new Coordinate(this.path, offset)
}
| () {
return this.path[0]
}
getPath() {
return this.path
}
getOffset() {
return this.offset
}
toJSON() {
return {
path: this.path.slice(),
offset: this.offset
}
}
toString() {
return "(" + this.path.join('.') + ", " + this.offset + ")"
}
isPropertyCoordinate() {
return this.path.length > 1
}
isNodeCoordinate() {
return this.path.length === 1
}
hasSamePath(other) {
return isArrayEqual(this.path, other.path)
}
}
Coordinate.prototype._isCoordinate = true
export default Coordinate
| getNodeId | identifier_name |
Coordinate.js | import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'
/**
@internal
*/
class Coordinate {
/**
@param {Array} path the address of a property, such as ['text_1', 'content']
@param {int} offset the position in the property
*/
constructor(path, offset) {
// HACK: to allow this class be inherited but without calling this ctor
if (arguments[0] === 'SKIP') return
if (arguments.length === 1) {
let data = arguments[0]
this.path = data.path
this.offset = data.offset
} else {
this.path = path
this.offset = offset
}
if (!isArray(this.path)) {
throw new Error('Invalid arguments: path should be an array.')
}
if (!isNumber(this.offset) || this.offset < 0) {
throw new Error('Invalid arguments: offset must be a positive number.')
}
}
equals(other) {
return (other === this ||
(isArrayEqual(other.path, this.path) && other.offset === this.offset) )
}
withCharPos(offset) {
return new Coordinate(this.path, offset)
}
getNodeId() {
return this.path[0]
}
getPath() {
return this.path
}
getOffset() {
return this.offset
}
toJSON() {
return {
path: this.path.slice(),
offset: this.offset
}
}
toString() {
return "(" + this.path.join('.') + ", " + this.offset + ")"
}
isPropertyCoordinate() {
return this.path.length > 1 | }
isNodeCoordinate() {
return this.path.length === 1
}
hasSamePath(other) {
return isArrayEqual(this.path, other.path)
}
}
Coordinate.prototype._isCoordinate = true
export default Coordinate | random_line_split | |
Coordinate.js | import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'
/**
@internal
*/
class Coordinate {
/**
@param {Array} path the address of a property, such as ['text_1', 'content']
@param {int} offset the position in the property
*/
constructor(path, offset) {
// HACK: to allow this class be inherited but without calling this ctor
if (arguments[0] === 'SKIP') return
if (arguments.length === 1) {
let data = arguments[0]
this.path = data.path
this.offset = data.offset
} else {
this.path = path
this.offset = offset
}
if (!isArray(this.path)) |
if (!isNumber(this.offset) || this.offset < 0) {
throw new Error('Invalid arguments: offset must be a positive number.')
}
}
equals(other) {
return (other === this ||
(isArrayEqual(other.path, this.path) && other.offset === this.offset) )
}
withCharPos(offset) {
return new Coordinate(this.path, offset)
}
getNodeId() {
return this.path[0]
}
getPath() {
return this.path
}
getOffset() {
return this.offset
}
toJSON() {
return {
path: this.path.slice(),
offset: this.offset
}
}
toString() {
return "(" + this.path.join('.') + ", " + this.offset + ")"
}
isPropertyCoordinate() {
return this.path.length > 1
}
isNodeCoordinate() {
return this.path.length === 1
}
hasSamePath(other) {
return isArrayEqual(this.path, other.path)
}
}
Coordinate.prototype._isCoordinate = true
export default Coordinate
| {
throw new Error('Invalid arguments: path should be an array.')
} | conditional_block |
NewObjectSample.ts | /**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Class: NewObjectSample
module Shumway.AVMX.AS.flash.sampler {
import notImplemented = Shumway.Debug.notImplemented;
export class NewObjectSample extends flash.sampler.Sample {
// Called whenever the class is initialized.
static classInitializer: any = null;
// List of static symbols to link.
static classSymbols: string [] = null; // [];
// List of instance symbols to link.
static instanceSymbols: string [] = null; // [];
| constructor () {
super();
}
// JS -> AS Bindings
id: number = undefined;
type: ASClass = undefined;
// AS -> JS Bindings
// _size: number;
get object(): any {
notImplemented("public flash.sampler.NewObjectSample::get object"); return;
// return this._object;
}
get size(): number {
notImplemented("public flash.sampler.NewObjectSample::get size"); return;
// return this._size;
}
}
} | random_line_split | |
NewObjectSample.ts | /**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Class: NewObjectSample
module Shumway.AVMX.AS.flash.sampler {
import notImplemented = Shumway.Debug.notImplemented;
export class | extends flash.sampler.Sample {
// Called whenever the class is initialized.
static classInitializer: any = null;
// List of static symbols to link.
static classSymbols: string [] = null; // [];
// List of instance symbols to link.
static instanceSymbols: string [] = null; // [];
constructor () {
super();
}
// JS -> AS Bindings
id: number = undefined;
type: ASClass = undefined;
// AS -> JS Bindings
// _size: number;
get object(): any {
notImplemented("public flash.sampler.NewObjectSample::get object"); return;
// return this._object;
}
get size(): number {
notImplemented("public flash.sampler.NewObjectSample::get size"); return;
// return this._size;
}
}
}
| NewObjectSample | identifier_name |
signon.py | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
if __name__ == "__main__":
|
# version
__id__ = "$Id: signon.py,v 1.1.1.1 2005/03/08 16:13:57 aivazis Exp $"
# End of file
| import pulse
from pulse import pulse as pulsemodule
print "copyright information:"
print " ", pulse.copyright()
print " ", pulsemodule.copyright()
print
print "module information:"
print " file:", pulsemodule.__file__
print " doc:", pulsemodule.__doc__
print " contents:", dir(pulsemodule) | conditional_block |
signon.py | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved |
if __name__ == "__main__":
import pulse
from pulse import pulse as pulsemodule
print "copyright information:"
print " ", pulse.copyright()
print " ", pulsemodule.copyright()
print
print "module information:"
print " file:", pulsemodule.__file__
print " doc:", pulsemodule.__doc__
print " contents:", dir(pulsemodule)
# version
__id__ = "$Id: signon.py,v 1.1.1.1 2005/03/08 16:13:57 aivazis Exp $"
# End of file | #
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# | random_line_split |
sigmajs-tests.ts | /// <reference path="sigmajs.d.ts"/>
namespace SigmaJsTests {
var container = document.createElement("sigma");
var s = new sigma({
settings: {
autoResize: true,
autoRescale: true
}
});
s.settings({
maxNodeSize: 10
});
s.settings("maxNodeSize");
s.addRenderer({
type: 'canvas',
container: container
});
s.bind('clickNode', (e) => {
s.refresh();
});
sigma.canvas.edges['def'] = function() {};
sigma.svg.nodes['def'] = {create: (obj: SigmaJs.Node) => { return new Element(); },
update: (obj: SigmaJs.Node) => { return; }};
sigma.svg.edges['def'] = {create: (obj: SigmaJs.Edge) => { return new Element(); },
update: (obj: SigmaJs.Edge) => { return; }};
sigma.svg.edges.labels['def'] = {create: (obj: SigmaJs.Edge) => { return new Element(); },
update: (obj: SigmaJs.Edge) => { return; }};
var N = 100;
var E = 500;
// Generate a random graph:
for (var i = 0; i < N; i++) {
s.graph.addNode({
id: 'n' + i,
label: 'Node ' + i,
x: Math.random(),
y: Math.random(),
size: Math.random(),
color: '#666'
});
}
for (var j = 0; j < E; j++) {
s.graph.addEdge({
id: 'e' + j,
source: 'n' + Math.floor(Math.random() * N),
target: 'n' + Math.floor(Math.random() * N),
size: Math.random(), | }
sigma.plugins.dragNodes(s, s.renderers[0]);
s.renderers[0].resize();
s.refresh();
sigma.parsers.json('myGraph.json', s, () => {
s.refresh();
});
sigma.parsers.gexf('myGraph.gexf', s, () => {
s.refresh();
});
s.configForceAtlas2({
worker: true
});
s.isForceAtlas2Running();
s.killForceAtlas2();
s.startForceAtlas2();
s.stopForceAtlas2();
s.cameras[0].goTo({
angle: 0,
x: 100,
y: 100,
ratio: 1
});
} | color: '#ccc'
}); | random_line_split |
sigmajs-tests.ts | /// <reference path="sigmajs.d.ts"/>
namespace SigmaJsTests {
var container = document.createElement("sigma");
var s = new sigma({
settings: {
autoResize: true,
autoRescale: true
}
});
s.settings({
maxNodeSize: 10
});
s.settings("maxNodeSize");
s.addRenderer({
type: 'canvas',
container: container
});
s.bind('clickNode', (e) => {
s.refresh();
});
sigma.canvas.edges['def'] = function() {};
sigma.svg.nodes['def'] = {create: (obj: SigmaJs.Node) => { return new Element(); },
update: (obj: SigmaJs.Node) => { return; }};
sigma.svg.edges['def'] = {create: (obj: SigmaJs.Edge) => { return new Element(); },
update: (obj: SigmaJs.Edge) => { return; }};
sigma.svg.edges.labels['def'] = {create: (obj: SigmaJs.Edge) => { return new Element(); },
update: (obj: SigmaJs.Edge) => { return; }};
var N = 100;
var E = 500;
// Generate a random graph:
for (var i = 0; i < N; i++) {
s.graph.addNode({
id: 'n' + i,
label: 'Node ' + i,
x: Math.random(),
y: Math.random(),
size: Math.random(),
color: '#666'
});
}
for (var j = 0; j < E; j++) |
sigma.plugins.dragNodes(s, s.renderers[0]);
s.renderers[0].resize();
s.refresh();
sigma.parsers.json('myGraph.json', s, () => {
s.refresh();
});
sigma.parsers.gexf('myGraph.gexf', s, () => {
s.refresh();
});
s.configForceAtlas2({
worker: true
});
s.isForceAtlas2Running();
s.killForceAtlas2();
s.startForceAtlas2();
s.stopForceAtlas2();
s.cameras[0].goTo({
angle: 0,
x: 100,
y: 100,
ratio: 1
});
}
| {
s.graph.addEdge({
id: 'e' + j,
source: 'n' + Math.floor(Math.random() * N),
target: 'n' + Math.floor(Math.random() * N),
size: Math.random(),
color: '#ccc'
});
} | conditional_block |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data processing."""
homepage = "https://github.com/casacore/casacore"
url = "https://github.com/casacore/casacore/archive/v2.4.1.tar.gz"
maintainers = ['mpokorny']
version('3.4.0', sha256='31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1')
version('3.3.0', sha256='3a714644b908ef6e81489b792cc9b80f6d8267a275e15d38a42a6a5137d39d3d')
version('3.2.0', sha256='ae5d3786cb6dfdd7ebc5eecc0c724ff02bbf6929720bc23be43a027978e79a5f')
version('3.1.2', sha256='ac94f4246412eb45d503f1019cabe2bb04e3861e1f3254b832d9b1164ea5f281')
version('3.1.1', sha256='85d2b17d856592fb206b17e0a344a29330650a4269c80b87f8abb3eaf3dadad4')
version('3.1.0', sha256='a6adf2d77ad0d6f32995b1e297fd88d31ded9c3e0bb8f28966d7b35a969f7897')
version('3.0.0', sha256='6f0e68fd77b5c96299f7583a03a53a90980ec347bff9dfb4c0abb0e2933e6bcb')
version('2.4.1', sha256='58eccc875053b2c6fe44fe53b6463030ef169597ec29926936f18d27b5087d63')
depends_on('cmake@3.7.1:', type='build')
variant('openmp', default=False, description='Build OpenMP support')
variant('shared', default=True, description='Build shared libraries')
variant('readline', default=True, description='Build readline support')
# see note below about the reason for disabling the "sofa" variant
# variant('sofa', default=False, description='Build SOFA support')
variant('adios2', default=False, description='Build ADIOS2 support')
variant('fftpack', default=False, description='Build FFTPack')
variant('hdf5', default=False, description='Build HDF5 support')
variant('python', default=False, description='Build python support')
# Force dependency on readline in v3.2 and earlier. Although the
# presence of readline is tested in CMakeLists.txt, and casacore
# can be built without it, there's no way to control that
# dependency at build time; since many systems come with readline,
# it's better to explicitly depend on it here always.
depends_on('readline', when='@:3.2.0')
depends_on('readline', when='+readline')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('cfitsio')
depends_on('wcslib@4.20:+cfitsio')
depends_on('fftw@3.0.0: precision=float,double', when='@3.4.0:')
depends_on('fftw@3.0.0: precision=float,double', when='~fftpack')
# SOFA dependency suffers the same problem in CMakeLists.txt as readline;
# force a dependency when building unit tests
depends_on('sofa-c', type='test')
depends_on('hdf5', when='+hdf5')
depends_on('adios2+mpi', when='+adios2')
depends_on('mpi', when='+adios2')
depends_on('python@2.6:', when='+python')
depends_on('boost+python', when='+python')
depends_on('py-numpy', when='+python')
def | (self):
args = []
spec = self.spec
args.append(self.define_from_variant('ENABLE_SHARED', 'shared'))
args.append(self.define_from_variant('USE_OPENMP', 'openmp'))
args.append(self.define_from_variant('USE_READLINE', 'readline'))
args.append(self.define_from_variant('USE_HDF5', 'hdf5'))
args.append(self.define_from_variant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3.4.0 and later, we
# always require FFTW3 dependency with the optional addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
args.append('-DBUILD_FFTPACK_DEPRECATED=YES')
args.append(self.define('USE_FFTW3', True))
else:
args.append(self.define('USE_FFTW3', spec.satisfies('~fftpack')))
# Python2 and Python3 binding
if spec.satisfies('~python'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=NO'])
elif spec.satisfies('^python@3.0.0:'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=YES'])
else:
args.extend(['-DBUILD_PYTHON=YES', '-DBUILD_PYTHON3=NO'])
args.append('-DBUILD_TESTING=OFF')
return args
def patch(self):
# Rely on CMake ability to find hdf5, available since CMake 3.7.X
os.remove('cmake/FindHDF5.cmake')
| cmake_args | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data processing."""
homepage = "https://github.com/casacore/casacore"
url = "https://github.com/casacore/casacore/archive/v2.4.1.tar.gz"
maintainers = ['mpokorny']
version('3.4.0', sha256='31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1')
version('3.3.0', sha256='3a714644b908ef6e81489b792cc9b80f6d8267a275e15d38a42a6a5137d39d3d')
version('3.2.0', sha256='ae5d3786cb6dfdd7ebc5eecc0c724ff02bbf6929720bc23be43a027978e79a5f')
version('3.1.2', sha256='ac94f4246412eb45d503f1019cabe2bb04e3861e1f3254b832d9b1164ea5f281')
version('3.1.1', sha256='85d2b17d856592fb206b17e0a344a29330650a4269c80b87f8abb3eaf3dadad4')
version('3.1.0', sha256='a6adf2d77ad0d6f32995b1e297fd88d31ded9c3e0bb8f28966d7b35a969f7897')
version('3.0.0', sha256='6f0e68fd77b5c96299f7583a03a53a90980ec347bff9dfb4c0abb0e2933e6bcb')
version('2.4.1', sha256='58eccc875053b2c6fe44fe53b6463030ef169597ec29926936f18d27b5087d63')
depends_on('cmake@3.7.1:', type='build')
variant('openmp', default=False, description='Build OpenMP support')
variant('shared', default=True, description='Build shared libraries')
variant('readline', default=True, description='Build readline support')
# see note below about the reason for disabling the "sofa" variant
# variant('sofa', default=False, description='Build SOFA support')
variant('adios2', default=False, description='Build ADIOS2 support')
variant('fftpack', default=False, description='Build FFTPack')
variant('hdf5', default=False, description='Build HDF5 support')
variant('python', default=False, description='Build python support')
# Force dependency on readline in v3.2 and earlier. Although the
# presence of readline is tested in CMakeLists.txt, and casacore
# can be built without it, there's no way to control that
# dependency at build time; since many systems come with readline,
# it's better to explicitly depend on it here always.
depends_on('readline', when='@:3.2.0')
depends_on('readline', when='+readline')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('cfitsio')
depends_on('wcslib@4.20:+cfitsio')
depends_on('fftw@3.0.0: precision=float,double', when='@3.4.0:')
depends_on('fftw@3.0.0: precision=float,double', when='~fftpack')
# SOFA dependency suffers the same problem in CMakeLists.txt as readline;
# force a dependency when building unit tests
depends_on('sofa-c', type='test')
depends_on('hdf5', when='+hdf5')
depends_on('adios2+mpi', when='+adios2')
depends_on('mpi', when='+adios2')
depends_on('python@2.6:', when='+python')
depends_on('boost+python', when='+python')
depends_on('py-numpy', when='+python')
def cmake_args(self):
|
def patch(self):
# Rely on CMake ability to find hdf5, available since CMake 3.7.X
os.remove('cmake/FindHDF5.cmake')
| args = []
spec = self.spec
args.append(self.define_from_variant('ENABLE_SHARED', 'shared'))
args.append(self.define_from_variant('USE_OPENMP', 'openmp'))
args.append(self.define_from_variant('USE_READLINE', 'readline'))
args.append(self.define_from_variant('USE_HDF5', 'hdf5'))
args.append(self.define_from_variant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3.4.0 and later, we
# always require FFTW3 dependency with the optional addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
args.append('-DBUILD_FFTPACK_DEPRECATED=YES')
args.append(self.define('USE_FFTW3', True))
else:
args.append(self.define('USE_FFTW3', spec.satisfies('~fftpack')))
# Python2 and Python3 binding
if spec.satisfies('~python'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=NO'])
elif spec.satisfies('^python@3.0.0:'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=YES'])
else:
args.extend(['-DBUILD_PYTHON=YES', '-DBUILD_PYTHON3=NO'])
args.append('-DBUILD_TESTING=OFF')
return args | identifier_body |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data processing."""
homepage = "https://github.com/casacore/casacore"
url = "https://github.com/casacore/casacore/archive/v2.4.1.tar.gz"
maintainers = ['mpokorny']
version('3.4.0', sha256='31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1')
version('3.3.0', sha256='3a714644b908ef6e81489b792cc9b80f6d8267a275e15d38a42a6a5137d39d3d')
version('3.2.0', sha256='ae5d3786cb6dfdd7ebc5eecc0c724ff02bbf6929720bc23be43a027978e79a5f')
version('3.1.2', sha256='ac94f4246412eb45d503f1019cabe2bb04e3861e1f3254b832d9b1164ea5f281')
version('3.1.1', sha256='85d2b17d856592fb206b17e0a344a29330650a4269c80b87f8abb3eaf3dadad4')
version('3.1.0', sha256='a6adf2d77ad0d6f32995b1e297fd88d31ded9c3e0bb8f28966d7b35a969f7897')
version('3.0.0', sha256='6f0e68fd77b5c96299f7583a03a53a90980ec347bff9dfb4c0abb0e2933e6bcb')
version('2.4.1', sha256='58eccc875053b2c6fe44fe53b6463030ef169597ec29926936f18d27b5087d63')
depends_on('cmake@3.7.1:', type='build')
variant('openmp', default=False, description='Build OpenMP support')
variant('shared', default=True, description='Build shared libraries')
variant('readline', default=True, description='Build readline support')
# see note below about the reason for disabling the "sofa" variant
# variant('sofa', default=False, description='Build SOFA support')
variant('adios2', default=False, description='Build ADIOS2 support')
variant('fftpack', default=False, description='Build FFTPack')
variant('hdf5', default=False, description='Build HDF5 support')
variant('python', default=False, description='Build python support')
# Force dependency on readline in v3.2 and earlier. Although the
# presence of readline is tested in CMakeLists.txt, and casacore
# can be built without it, there's no way to control that
# dependency at build time; since many systems come with readline,
# it's better to explicitly depend on it here always.
depends_on('readline', when='@:3.2.0')
depends_on('readline', when='+readline')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('cfitsio')
depends_on('wcslib@4.20:+cfitsio')
depends_on('fftw@3.0.0: precision=float,double', when='@3.4.0:')
depends_on('fftw@3.0.0: precision=float,double', when='~fftpack')
# SOFA dependency suffers the same problem in CMakeLists.txt as readline;
# force a dependency when building unit tests
depends_on('sofa-c', type='test')
depends_on('hdf5', when='+hdf5')
depends_on('adios2+mpi', when='+adios2')
depends_on('mpi', when='+adios2')
depends_on('python@2.6:', when='+python')
depends_on('boost+python', when='+python')
depends_on('py-numpy', when='+python')
| args = []
spec = self.spec
args.append(self.define_from_variant('ENABLE_SHARED', 'shared'))
args.append(self.define_from_variant('USE_OPENMP', 'openmp'))
args.append(self.define_from_variant('USE_READLINE', 'readline'))
args.append(self.define_from_variant('USE_HDF5', 'hdf5'))
args.append(self.define_from_variant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3.4.0 and later, we
# always require FFTW3 dependency with the optional addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
args.append('-DBUILD_FFTPACK_DEPRECATED=YES')
args.append(self.define('USE_FFTW3', True))
else:
args.append(self.define('USE_FFTW3', spec.satisfies('~fftpack')))
# Python2 and Python3 binding
if spec.satisfies('~python'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=NO'])
elif spec.satisfies('^python@3.0.0:'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=YES'])
else:
args.extend(['-DBUILD_PYTHON=YES', '-DBUILD_PYTHON3=NO'])
args.append('-DBUILD_TESTING=OFF')
return args
def patch(self):
# Rely on CMake ability to find hdf5, available since CMake 3.7.X
os.remove('cmake/FindHDF5.cmake') | def cmake_args(self): | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Casacore(CMakePackage):
"""A suite of c++ libraries for radio astronomy data processing."""
homepage = "https://github.com/casacore/casacore"
url = "https://github.com/casacore/casacore/archive/v2.4.1.tar.gz"
maintainers = ['mpokorny']
version('3.4.0', sha256='31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1')
version('3.3.0', sha256='3a714644b908ef6e81489b792cc9b80f6d8267a275e15d38a42a6a5137d39d3d')
version('3.2.0', sha256='ae5d3786cb6dfdd7ebc5eecc0c724ff02bbf6929720bc23be43a027978e79a5f')
version('3.1.2', sha256='ac94f4246412eb45d503f1019cabe2bb04e3861e1f3254b832d9b1164ea5f281')
version('3.1.1', sha256='85d2b17d856592fb206b17e0a344a29330650a4269c80b87f8abb3eaf3dadad4')
version('3.1.0', sha256='a6adf2d77ad0d6f32995b1e297fd88d31ded9c3e0bb8f28966d7b35a969f7897')
version('3.0.0', sha256='6f0e68fd77b5c96299f7583a03a53a90980ec347bff9dfb4c0abb0e2933e6bcb')
version('2.4.1', sha256='58eccc875053b2c6fe44fe53b6463030ef169597ec29926936f18d27b5087d63')
depends_on('cmake@3.7.1:', type='build')
variant('openmp', default=False, description='Build OpenMP support')
variant('shared', default=True, description='Build shared libraries')
variant('readline', default=True, description='Build readline support')
# see note below about the reason for disabling the "sofa" variant
# variant('sofa', default=False, description='Build SOFA support')
variant('adios2', default=False, description='Build ADIOS2 support')
variant('fftpack', default=False, description='Build FFTPack')
variant('hdf5', default=False, description='Build HDF5 support')
variant('python', default=False, description='Build python support')
# Force dependency on readline in v3.2 and earlier. Although the
# presence of readline is tested in CMakeLists.txt, and casacore
# can be built without it, there's no way to control that
# dependency at build time; since many systems come with readline,
# it's better to explicitly depend on it here always.
depends_on('readline', when='@:3.2.0')
depends_on('readline', when='+readline')
depends_on('flex', type='build')
depends_on('bison', type='build')
depends_on('blas')
depends_on('lapack')
depends_on('cfitsio')
depends_on('wcslib@4.20:+cfitsio')
depends_on('fftw@3.0.0: precision=float,double', when='@3.4.0:')
depends_on('fftw@3.0.0: precision=float,double', when='~fftpack')
# SOFA dependency suffers the same problem in CMakeLists.txt as readline;
# force a dependency when building unit tests
depends_on('sofa-c', type='test')
depends_on('hdf5', when='+hdf5')
depends_on('adios2+mpi', when='+adios2')
depends_on('mpi', when='+adios2')
depends_on('python@2.6:', when='+python')
depends_on('boost+python', when='+python')
depends_on('py-numpy', when='+python')
def cmake_args(self):
args = []
spec = self.spec
args.append(self.define_from_variant('ENABLE_SHARED', 'shared'))
args.append(self.define_from_variant('USE_OPENMP', 'openmp'))
args.append(self.define_from_variant('USE_READLINE', 'readline'))
args.append(self.define_from_variant('USE_HDF5', 'hdf5'))
args.append(self.define_from_variant('USE_ADIOS2', 'adios2'))
args.append(self.define_from_variant('USE_MPI', 'adios2'))
if spec.satisfies('+adios2'):
args.append(self.define('ENABLE_TABLELOCKING', False))
# fftw3 is required by casacore starting with v3.4.0, but the
# old fftpack is still available. For v3.4.0 and later, we
# always require FFTW3 dependency with the optional addition
# of FFTPack. In older casacore versions, only one of FFTW3 or
# FFTPack can be selected.
if spec.satisfies('@3.4.0:'):
if spec.satisfies('+fftpack'):
|
args.append(self.define('USE_FFTW3', True))
else:
args.append(self.define('USE_FFTW3', spec.satisfies('~fftpack')))
# Python2 and Python3 binding
if spec.satisfies('~python'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=NO'])
elif spec.satisfies('^python@3.0.0:'):
args.extend(['-DBUILD_PYTHON=NO', '-DBUILD_PYTHON3=YES'])
else:
args.extend(['-DBUILD_PYTHON=YES', '-DBUILD_PYTHON3=NO'])
args.append('-DBUILD_TESTING=OFF')
return args
def patch(self):
# Rely on CMake ability to find hdf5, available since CMake 3.7.X
os.remove('cmake/FindHDF5.cmake')
| args.append('-DBUILD_FFTPACK_DEPRECATED=YES') | conditional_block |
store.component.ts | import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { LocalDataSource } from 'ng2-smart-table';
import { LocalStorageService, LocalStorage, SessionStorageService } from 'ng2-webstorage';
import { Router, RouterModule } from '@angular/router';
@Component({
selector: 'store',
styleUrls: ['./store.scss'],
templateUrl: './store.html'
})
export class Store implements OnInit {
public codigo;
public aux$;
public items: FirebaseListObservable<any>;
public aux: boolean = false;
public showAccount = [];
public objectInfo: Object;
query: string = '';
settings = {
actions: {
add: false,
edit: false,
delete: false
},
noDataMessage: 'No hay registros almacenados',
columns: {
id: {
title: 'Codigo',
type: 'string',
sort: true
},
name: {
title: 'Nombre',
type: 'string'
},
type: {
title: 'Tipo',
type: 'string'
},
price: {
title: 'Precio',
type: 'string'
},
status: {
title: 'Estado',
type: 'string'
}
}
};
source: LocalDataSource = new LocalDataSource();
users: FirebaseListObservable<any>; | public af: AngularFire,
public localSt: LocalStorageService,
public route: Router) {
this.users = af.database.list('/user/');
this.clients = af.database.list('/client/');
this.items = af.database.list('/buy/');
this.productos = af.database.list('/product/');
this.loadOn();
}
ngOnInit() {
// Validate local session storage if there is an user
if (this.localSt.retrieve('user')) {
this.users.subscribe((user: any[]) => {
user.map((e) => {
let passwordString: string = e.password.toString();
if ((this.localSt.retrieve('user').email === e.email) &&
(this.localSt.retrieve('user').password === passwordString)) {
this.aux = true;
}
});
if (this.aux) {
// this.route.navigate(['/pages/home']);
}
else {
this.localSt.clear();
this.route.navigate(['/login']);
}
});
}
else {
this.route.navigate(['/login']);
}
}
public loadOn() {
this.aux$ = this.productos.subscribe( (products) => {
console.log(products);
products.map((data) => {
console.log(data);
let aux: string = '';
if (data.available === true) {
aux = 'habilitado';
}
else {
aux = 'deshabilitado';
}
let prod = {
id: data.id.toString(),
name: data.name,
type: data.type,
price: data.price,
status: aux
};
this.showAccount.push(prod);
});
this.source.load(this.showAccount);
this.aux$.unsubscribe();
});
}
public restaurarProd(codigo) {
// this.saveFB(codigo.toString());
}
public saveFB(codigo: string): void {
let compra: Object = {
available : true,
id: codigo,
name: 'Aceite ST 15W40',
price: 15000,
type: 'Producto'
};
this.af.database.list('/product/').push(compra);
this.route.navigate(['pages/store']);
// this.productos.push(compra);
}
} | clients: FirebaseListObservable<any>;
productos: FirebaseListObservable<any>;
constructor( | random_line_split |
store.component.ts | import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { LocalDataSource } from 'ng2-smart-table';
import { LocalStorageService, LocalStorage, SessionStorageService } from 'ng2-webstorage';
import { Router, RouterModule } from '@angular/router';
@Component({
selector: 'store',
styleUrls: ['./store.scss'],
templateUrl: './store.html'
})
export class Store implements OnInit {
public codigo;
public aux$;
public items: FirebaseListObservable<any>;
public aux: boolean = false;
public showAccount = [];
public objectInfo: Object;
query: string = '';
settings = {
actions: {
add: false,
edit: false,
delete: false
},
noDataMessage: 'No hay registros almacenados',
columns: {
id: {
title: 'Codigo',
type: 'string',
sort: true
},
name: {
title: 'Nombre',
type: 'string'
},
type: {
title: 'Tipo',
type: 'string'
},
price: {
title: 'Precio',
type: 'string'
},
status: {
title: 'Estado',
type: 'string'
}
}
};
source: LocalDataSource = new LocalDataSource();
users: FirebaseListObservable<any>;
clients: FirebaseListObservable<any>;
productos: FirebaseListObservable<any>;
constructor(
public af: AngularFire,
public localSt: LocalStorageService,
public route: Router) {
this.users = af.database.list('/user/');
this.clients = af.database.list('/client/');
this.items = af.database.list('/buy/');
this.productos = af.database.list('/product/');
this.loadOn();
}
ngOnInit() {
// Validate local session storage if there is an user
if (this.localSt.retrieve('user')) {
this.users.subscribe((user: any[]) => {
user.map((e) => {
let passwordString: string = e.password.toString();
if ((this.localSt.retrieve('user').email === e.email) &&
(this.localSt.retrieve('user').password === passwordString)) {
this.aux = true;
}
});
if (this.aux) {
// this.route.navigate(['/pages/home']);
}
else {
this.localSt.clear();
this.route.navigate(['/login']);
}
});
}
else {
this.route.navigate(['/login']);
}
}
public loadOn() {
this.aux$ = this.productos.subscribe( (products) => {
console.log(products);
products.map((data) => {
console.log(data);
let aux: string = '';
if (data.available === true) {
aux = 'habilitado';
}
else {
aux = 'deshabilitado';
}
let prod = {
id: data.id.toString(),
name: data.name,
type: data.type,
price: data.price,
status: aux
};
this.showAccount.push(prod);
});
this.source.load(this.showAccount);
this.aux$.unsubscribe();
});
}
public | (codigo) {
// this.saveFB(codigo.toString());
}
public saveFB(codigo: string): void {
let compra: Object = {
available : true,
id: codigo,
name: 'Aceite ST 15W40',
price: 15000,
type: 'Producto'
};
this.af.database.list('/product/').push(compra);
this.route.navigate(['pages/store']);
// this.productos.push(compra);
}
}
| restaurarProd | identifier_name |
store.component.ts | import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { LocalDataSource } from 'ng2-smart-table';
import { LocalStorageService, LocalStorage, SessionStorageService } from 'ng2-webstorage';
import { Router, RouterModule } from '@angular/router';
@Component({
selector: 'store',
styleUrls: ['./store.scss'],
templateUrl: './store.html'
})
export class Store implements OnInit {
public codigo;
public aux$;
public items: FirebaseListObservable<any>;
public aux: boolean = false;
public showAccount = [];
public objectInfo: Object;
query: string = '';
settings = {
actions: {
add: false,
edit: false,
delete: false
},
noDataMessage: 'No hay registros almacenados',
columns: {
id: {
title: 'Codigo',
type: 'string',
sort: true
},
name: {
title: 'Nombre',
type: 'string'
},
type: {
title: 'Tipo',
type: 'string'
},
price: {
title: 'Precio',
type: 'string'
},
status: {
title: 'Estado',
type: 'string'
}
}
};
source: LocalDataSource = new LocalDataSource();
users: FirebaseListObservable<any>;
clients: FirebaseListObservable<any>;
productos: FirebaseListObservable<any>;
constructor(
public af: AngularFire,
public localSt: LocalStorageService,
public route: Router) {
this.users = af.database.list('/user/');
this.clients = af.database.list('/client/');
this.items = af.database.list('/buy/');
this.productos = af.database.list('/product/');
this.loadOn();
}
ngOnInit() {
// Validate local session storage if there is an user
if (this.localSt.retrieve('user')) {
this.users.subscribe((user: any[]) => {
user.map((e) => {
let passwordString: string = e.password.toString();
if ((this.localSt.retrieve('user').email === e.email) &&
(this.localSt.retrieve('user').password === passwordString)) {
this.aux = true;
}
});
if (this.aux) {
// this.route.navigate(['/pages/home']);
}
else {
this.localSt.clear();
this.route.navigate(['/login']);
}
});
}
else {
this.route.navigate(['/login']);
}
}
public loadOn() {
this.aux$ = this.productos.subscribe( (products) => {
console.log(products);
products.map((data) => {
console.log(data);
let aux: string = '';
if (data.available === true) {
aux = 'habilitado';
}
else |
let prod = {
id: data.id.toString(),
name: data.name,
type: data.type,
price: data.price,
status: aux
};
this.showAccount.push(prod);
});
this.source.load(this.showAccount);
this.aux$.unsubscribe();
});
}
public restaurarProd(codigo) {
// this.saveFB(codigo.toString());
}
public saveFB(codigo: string): void {
let compra: Object = {
available : true,
id: codigo,
name: 'Aceite ST 15W40',
price: 15000,
type: 'Producto'
};
this.af.database.list('/product/').push(compra);
this.route.navigate(['pages/store']);
// this.productos.push(compra);
}
}
| {
aux = 'deshabilitado';
} | conditional_block |
store.component.ts | import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { LocalDataSource } from 'ng2-smart-table';
import { LocalStorageService, LocalStorage, SessionStorageService } from 'ng2-webstorage';
import { Router, RouterModule } from '@angular/router';
@Component({
selector: 'store',
styleUrls: ['./store.scss'],
templateUrl: './store.html'
})
export class Store implements OnInit {
public codigo;
public aux$;
public items: FirebaseListObservable<any>;
public aux: boolean = false;
public showAccount = [];
public objectInfo: Object;
query: string = '';
settings = {
actions: {
add: false,
edit: false,
delete: false
},
noDataMessage: 'No hay registros almacenados',
columns: {
id: {
title: 'Codigo',
type: 'string',
sort: true
},
name: {
title: 'Nombre',
type: 'string'
},
type: {
title: 'Tipo',
type: 'string'
},
price: {
title: 'Precio',
type: 'string'
},
status: {
title: 'Estado',
type: 'string'
}
}
};
source: LocalDataSource = new LocalDataSource();
users: FirebaseListObservable<any>;
clients: FirebaseListObservable<any>;
productos: FirebaseListObservable<any>;
constructor(
public af: AngularFire,
public localSt: LocalStorageService,
public route: Router) {
this.users = af.database.list('/user/');
this.clients = af.database.list('/client/');
this.items = af.database.list('/buy/');
this.productos = af.database.list('/product/');
this.loadOn();
}
ngOnInit() |
public loadOn() {
this.aux$ = this.productos.subscribe( (products) => {
console.log(products);
products.map((data) => {
console.log(data);
let aux: string = '';
if (data.available === true) {
aux = 'habilitado';
}
else {
aux = 'deshabilitado';
}
let prod = {
id: data.id.toString(),
name: data.name,
type: data.type,
price: data.price,
status: aux
};
this.showAccount.push(prod);
});
this.source.load(this.showAccount);
this.aux$.unsubscribe();
});
}
public restaurarProd(codigo) {
// this.saveFB(codigo.toString());
}
public saveFB(codigo: string): void {
let compra: Object = {
available : true,
id: codigo,
name: 'Aceite ST 15W40',
price: 15000,
type: 'Producto'
};
this.af.database.list('/product/').push(compra);
this.route.navigate(['pages/store']);
// this.productos.push(compra);
}
}
| {
// Validate local session storage if there is an user
if (this.localSt.retrieve('user')) {
this.users.subscribe((user: any[]) => {
user.map((e) => {
let passwordString: string = e.password.toString();
if ((this.localSt.retrieve('user').email === e.email) &&
(this.localSt.retrieve('user').password === passwordString)) {
this.aux = true;
}
});
if (this.aux) {
// this.route.navigate(['/pages/home']);
}
else {
this.localSt.clear();
this.route.navigate(['/login']);
}
});
}
else {
this.route.navigate(['/login']);
}
} | identifier_body |
command_line.py | """
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_line/
"""
import logging
import subprocess
from blumate.components.switch import SwitchDevice
from blumate.const import CONF_VALUE_TEMPLATE
from blumate.helpers import template
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Find and return switches controlled by shell commands."""
switches = config.get('switches', {})
devices = []
for dev_name, properties in switches.items():
devices.append(
CommandSwitch(
hass,
properties.get('name', dev_name),
properties.get('oncmd', 'true'),
properties.get('offcmd', 'true'),
properties.get('statecmd', False),
properties.get(CONF_VALUE_TEMPLATE, False)))
add_devices_callback(devices)
# pylint: disable=too-many-instance-attributes
class CommandSwitch(SwitchDevice):
"""Representation a switch that can be toggled using shell commands."""
# pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off,
command_state, value_template):
"""Initialize the switch."""
self._hass = hass
self._name = name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_state
self._value_template = value_template
@staticmethod
def _switch(command):
"""Execute the actual commands."""
_LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0)
if not success:
_LOGGER.error('Command failed: %s', command)
return success
@staticmethod
def _query_state_value(command):
"""Execute state command for return value."""
_LOGGER.info('Running state command: %s', command)
try:
return_value = subprocess.check_output(command, shell=True)
return return_value.strip().decode('utf-8')
except subprocess.CalledProcessError:
_LOGGER.error('Command failed: %s', command)
@staticmethod
def _query_state_code(command):
"""Execute state command for return code."""
_LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0
@property
def should_poll(self):
"""Only poll if we have state command."""
return self._command_state is not None
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._command_state is False
def _query_state(self):
"""Query for state."""
if not self._command_state:
_LOGGER.error('No state command specified')
return
if self._value_template:
return CommandSwitch._query_state_value(self._command_state)
return CommandSwitch._query_state_code(self._command_state)
def update(self):
|
def turn_on(self, **kwargs):
"""Turn the device on."""
if (CommandSwitch._switch(self._command_on) and
not self._command_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
if (CommandSwitch._switch(self._command_off) and
not self._command_state):
self._state = False
self.update_ha_state()
| """Update device state."""
if self._command_state:
payload = str(self._query_state())
if self._value_template:
payload = template.render_with_possible_json_value(
self._hass, self._value_template, payload)
self._state = (payload.lower() == "true") | identifier_body |
command_line.py | """
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_line/
"""
import logging
import subprocess
from blumate.components.switch import SwitchDevice
from blumate.const import CONF_VALUE_TEMPLATE
from blumate.helpers import template
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Find and return switches controlled by shell commands."""
switches = config.get('switches', {})
devices = []
for dev_name, properties in switches.items():
devices.append(
CommandSwitch(
hass,
properties.get('name', dev_name),
properties.get('oncmd', 'true'),
properties.get('offcmd', 'true'),
properties.get('statecmd', False),
properties.get(CONF_VALUE_TEMPLATE, False)))
add_devices_callback(devices)
# pylint: disable=too-many-instance-attributes
class CommandSwitch(SwitchDevice):
"""Representation a switch that can be toggled using shell commands."""
# pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off,
command_state, value_template):
"""Initialize the switch."""
self._hass = hass
self._name = name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_state
self._value_template = value_template
@staticmethod
def _switch(command):
"""Execute the actual commands."""
_LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0)
if not success:
_LOGGER.error('Command failed: %s', command)
return success
@staticmethod
def _query_state_value(command):
"""Execute state command for return value."""
_LOGGER.info('Running state command: %s', command)
try:
return_value = subprocess.check_output(command, shell=True)
return return_value.strip().decode('utf-8')
except subprocess.CalledProcessError:
_LOGGER.error('Command failed: %s', command)
@staticmethod
def _query_state_code(command):
"""Execute state command for return code."""
_LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0
@property
def | (self):
"""Only poll if we have state command."""
return self._command_state is not None
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._command_state is False
def _query_state(self):
"""Query for state."""
if not self._command_state:
_LOGGER.error('No state command specified')
return
if self._value_template:
return CommandSwitch._query_state_value(self._command_state)
return CommandSwitch._query_state_code(self._command_state)
def update(self):
"""Update device state."""
if self._command_state:
payload = str(self._query_state())
if self._value_template:
payload = template.render_with_possible_json_value(
self._hass, self._value_template, payload)
self._state = (payload.lower() == "true")
def turn_on(self, **kwargs):
"""Turn the device on."""
if (CommandSwitch._switch(self._command_on) and
not self._command_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
if (CommandSwitch._switch(self._command_off) and
not self._command_state):
self._state = False
self.update_ha_state()
| should_poll | identifier_name |
command_line.py | """
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_line/
"""
import logging
import subprocess
from blumate.components.switch import SwitchDevice
from blumate.const import CONF_VALUE_TEMPLATE
from blumate.helpers import template
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Find and return switches controlled by shell commands."""
switches = config.get('switches', {})
devices = []
for dev_name, properties in switches.items():
|
add_devices_callback(devices)
# pylint: disable=too-many-instance-attributes
class CommandSwitch(SwitchDevice):
"""Representation a switch that can be toggled using shell commands."""
# pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off,
command_state, value_template):
"""Initialize the switch."""
self._hass = hass
self._name = name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_state
self._value_template = value_template
@staticmethod
def _switch(command):
"""Execute the actual commands."""
_LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0)
if not success:
_LOGGER.error('Command failed: %s', command)
return success
@staticmethod
def _query_state_value(command):
"""Execute state command for return value."""
_LOGGER.info('Running state command: %s', command)
try:
return_value = subprocess.check_output(command, shell=True)
return return_value.strip().decode('utf-8')
except subprocess.CalledProcessError:
_LOGGER.error('Command failed: %s', command)
@staticmethod
def _query_state_code(command):
"""Execute state command for return code."""
_LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0
@property
def should_poll(self):
"""Only poll if we have state command."""
return self._command_state is not None
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._command_state is False
def _query_state(self):
"""Query for state."""
if not self._command_state:
_LOGGER.error('No state command specified')
return
if self._value_template:
return CommandSwitch._query_state_value(self._command_state)
return CommandSwitch._query_state_code(self._command_state)
def update(self):
"""Update device state."""
if self._command_state:
payload = str(self._query_state())
if self._value_template:
payload = template.render_with_possible_json_value(
self._hass, self._value_template, payload)
self._state = (payload.lower() == "true")
def turn_on(self, **kwargs):
"""Turn the device on."""
if (CommandSwitch._switch(self._command_on) and
not self._command_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
if (CommandSwitch._switch(self._command_off) and
not self._command_state):
self._state = False
self.update_ha_state()
| devices.append(
CommandSwitch(
hass,
properties.get('name', dev_name),
properties.get('oncmd', 'true'),
properties.get('offcmd', 'true'),
properties.get('statecmd', False),
properties.get(CONF_VALUE_TEMPLATE, False))) | conditional_block |
command_line.py | """
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_line/
"""
import logging
import subprocess
from blumate.components.switch import SwitchDevice
from blumate.const import CONF_VALUE_TEMPLATE
from blumate.helpers import template
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Find and return switches controlled by shell commands."""
switches = config.get('switches', {})
devices = []
for dev_name, properties in switches.items():
devices.append(
CommandSwitch(
hass,
properties.get('name', dev_name),
properties.get('oncmd', 'true'),
properties.get('offcmd', 'true'),
properties.get('statecmd', False),
properties.get(CONF_VALUE_TEMPLATE, False)))
add_devices_callback(devices)
# pylint: disable=too-many-instance-attributes
class CommandSwitch(SwitchDevice):
"""Representation a switch that can be toggled using shell commands.""" | self._hass = hass
self._name = name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_state
self._value_template = value_template
@staticmethod
def _switch(command):
"""Execute the actual commands."""
_LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0)
if not success:
_LOGGER.error('Command failed: %s', command)
return success
@staticmethod
def _query_state_value(command):
"""Execute state command for return value."""
_LOGGER.info('Running state command: %s', command)
try:
return_value = subprocess.check_output(command, shell=True)
return return_value.strip().decode('utf-8')
except subprocess.CalledProcessError:
_LOGGER.error('Command failed: %s', command)
@staticmethod
def _query_state_code(command):
"""Execute state command for return code."""
_LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0
@property
def should_poll(self):
"""Only poll if we have state command."""
return self._command_state is not None
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._command_state is False
def _query_state(self):
"""Query for state."""
if not self._command_state:
_LOGGER.error('No state command specified')
return
if self._value_template:
return CommandSwitch._query_state_value(self._command_state)
return CommandSwitch._query_state_code(self._command_state)
def update(self):
"""Update device state."""
if self._command_state:
payload = str(self._query_state())
if self._value_template:
payload = template.render_with_possible_json_value(
self._hass, self._value_template, payload)
self._state = (payload.lower() == "true")
def turn_on(self, **kwargs):
"""Turn the device on."""
if (CommandSwitch._switch(self._command_on) and
not self._command_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
if (CommandSwitch._switch(self._command_off) and
not self._command_state):
self._state = False
self.update_ha_state() |
# pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off,
command_state, value_template):
"""Initialize the switch.""" | random_line_split |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if !self.states.is_empty() {
self.states.pop();
}
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if !state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if !self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn | (&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| shape_manager | identifier_name |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() { | }
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if !state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if !self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
} | state.stop();
}
if !self.states.is_empty() {
self.states.pop(); | random_line_split |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if !self.states.is_empty() {
self.states.pop();
}
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if !state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if !self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef |
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| {
self.drs_manager.clone()
} | identifier_body |
game.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use dat::{EmpiresDb, EmpiresDbRef};
use media::{self, MediaRef};
use resource::{DrsManager, DrsManagerRef, GameDir, ShapeManager, ShapeManagerRef, ShapeMetadataStore,
ShapeMetadataStoreRef};
use super::state::GameState;
use time;
use types::Fixed;
const WINDOW_TITLE: &'static str = "OpenAOE";
const WINDOW_WIDTH: u32 = 1024;
const WINDOW_HEIGHT: u32 = 768;
pub struct Game {
game_dir: GameDir,
drs_manager: DrsManagerRef,
shape_manager: ShapeManagerRef,
shape_metadata: ShapeMetadataStoreRef,
empires: EmpiresDbRef,
media: MediaRef,
states: Vec<Box<GameState>>,
}
impl Game {
pub fn new(game_data_dir: &str) -> Game {
let game_dir = GameDir::new(game_data_dir).unwrap_or_else(|err| {
unrecoverable!("{}", err);
});
let drs_manager = DrsManager::new(&game_dir);
if let Err(err) = drs_manager.borrow_mut().preload() {
unrecoverable!("Failed to preload DRS archives: {}", err);
}
let shape_manager = ShapeManager::new(drs_manager.clone()).unwrap_or_else(|err| {
unrecoverable!("Failed to initialize the shape manager: {}", err);
});
let shape_metadata = ShapeMetadataStoreRef::new(ShapeMetadataStore::load(&*drs_manager.borrow()));
let empires_dat_location = game_dir.find_file("data/empires.dat").unwrap();
let empires = EmpiresDbRef::new(EmpiresDb::read_from_file(empires_dat_location)
.unwrap_or_else(|err| {
unrecoverable!("Failed to load empires.dat: {}", err);
}));
let media = media::create_media(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE).unwrap_or_else(|err| {
unrecoverable!("Failed to create media window: {}", err);
});
Game {
game_dir: game_dir,
drs_manager: drs_manager,
shape_manager: shape_manager,
shape_metadata: shape_metadata,
empires: empires,
media: media,
states: Vec::new(),
}
}
pub fn push_state(&mut self, mut state: Box<GameState>) {
if let Some(mut prev_state) = self.current_state() {
prev_state.stop();
}
state.start();
self.states.push(state);
}
pub fn game_loop(&mut self) {
let time_step_nanos = 1000000000 / 60u64;
let time_step_seconds = Fixed::from(1) / Fixed::from(60);
let mut accumulator: u64 = 0;
let mut last_time = time::precise_time_ns();
while self.media.borrow().is_open() {
self.media.borrow_mut().update();
self.media.borrow_mut().renderer().present();
let new_time = time::precise_time_ns();
accumulator += new_time - last_time;
last_time = new_time;
while accumulator >= time_step_nanos {
self.media.borrow_mut().update_input();
self.update(time_step_seconds);
accumulator -= time_step_nanos;
}
let lerp = Fixed::from(accumulator as f64 / time_step_nanos as f64);
if let Some(state) = self.current_state() {
state.render(lerp);
}
}
}
fn pop_state(&mut self) {
if let Some(state) = self.current_state() {
state.stop();
}
if !self.states.is_empty() |
}
fn update(&mut self, time_step: Fixed) -> bool {
let mut pop_required = false;
let result = if let Some(state) = self.current_state() {
if !state.update(time_step) {
pop_required = true;
false
} else {
true
}
} else {
false
};
if pop_required {
self.pop_state();
}
result
}
fn current_state<'a>(&'a mut self) -> Option<&'a mut GameState> {
if !self.states.is_empty() {
let index = self.states.len() - 1; // satisfy the borrow checker
Some(&mut *self.states[index])
} else {
None
}
}
pub fn game_dir<'a>(&'a self) -> &'a GameDir {
&self.game_dir
}
pub fn drs_manager(&self) -> DrsManagerRef {
self.drs_manager.clone()
}
pub fn shape_manager(&self) -> ShapeManagerRef {
self.shape_manager.clone()
}
pub fn shape_metadata(&self) -> ShapeMetadataStoreRef {
self.shape_metadata.clone()
}
pub fn empires_db(&self) -> EmpiresDbRef {
self.empires.clone()
}
pub fn media(&self) -> MediaRef {
self.media.clone()
}
}
| {
self.states.pop();
} | conditional_block |
mocks.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="_references.ts"/>
module powerbitests.mocks {
import SQExprBuilder = powerbi.data.SQExprBuilder;
import defaultVisualHostServices = powerbi.visuals.defaultVisualHostServices;
import SelectableDataPoint = powerbi.visuals.SelectableDataPoint;
import ISelectionHandler = powerbi.visuals.ISelectionHandler;
import DefaultVisualHostServices = powerbi.visuals.DefaultVisualHostServices;
export class TelemetryCallbackMock {
public static callbackCalls: number = 0;
public target() {
TelemetryCallbackMock.callbackCalls++;
}
};
export class AppInsightsV2Mock {
public trackPageViewTimes: number = 0;
public trackEventTimes: number = 0;
public trackEventLastActivityName: string = null;
public trackEventLastAdditionalData: any = {
id: null,
start: null,
end: null,
isInternalUser: null,
userId: null,
category: null,
sessionId: null,
client: null,
build: null,
cluster: null,
};
public trackPageView(): void {
this.trackPageViewTimes++;
}
public trackEvent(activityName: string, additionalData: any): void {
this.trackEventTimes++;
this.trackEventLastActivityName = activityName;
this.trackEventLastAdditionalData = additionalData;
}
}
export var DefaultLoggerMockType: number = 1;
export class MockTimerPromiseFactory implements jsCommon.ITimerPromiseFactory {
public deferred: JQueryDeferred<void>;
public create(delayInMs: number): jsCommon.IRejectablePromise {
if (!this.deferred) {
this.deferred = $.Deferred<void>();
}
return this.deferred;
}
public resolveCurrent(): void {
expect(this.deferred).toBeDefined();
// Note: we need to read the current deferred field into a local var and null out the member before
// we call resolve, just in case one of timer callbacks recursively creates another timer.
var deferred = this.deferred;
this.deferred = undefined;
deferred.resolve();
}
public reject(): void {
expect(this.deferred).toBeDefined();
// Note: we need to read the current deferred field into a local var and null out the member before
// we call reject, just in case one of timer callbacks recursively creates another timer.
var deferred = this.deferred;
this.deferred = undefined;
deferred.reject();
}
public expectNoTimers(): void {
expect(this.deferred).not.toBeDefined();
}
public hasPendingTimers(): boolean {
return !!this.deferred;
}
}
export function createVisualHostServices(): powerbi.IVisualHostServices {
return new DefaultVisualHostServices();
}
export class MockTraceListener implements jsCommon.ITraceListener {
public trace: jsCommon.TraceItem;
public logTrace(trace: jsCommon.TraceItem): void {
this.trace = trace;
}
}
export function dataViewScopeIdentity(fakeValue: string | number | boolean | Date): powerbi.DataViewScopeIdentity {
var expr = constExpr(fakeValue);
return powerbi.data.createDataViewScopeIdentity(expr);
}
export function dataViewScopeIdentityWithEquality(keyExpr: powerbi.data.SQExpr, fakeValue: string | number | boolean | Date): powerbi.DataViewScopeIdentity {
return powerbi.data.createDataViewScopeIdentity(
powerbi.data.SQExprBuilder.equal(
keyExpr,
constExpr(fakeValue)));
}
function constExpr(fakeValue: string | number | boolean | Date): powerbi.data.SQExpr {
if (fakeValue === null)
return SQExprBuilder.nullConstant();
if (fakeValue === true || fakeValue === false)
return SQExprBuilder.boolean(<boolean>fakeValue);
if (typeof (fakeValue) === 'number')
return powerbi.data.SQExprBuilder.double(<number>fakeValue);
if (fakeValue instanceof Date)
return powerbi.data.SQExprBuilder.dateTime(<Date>fakeValue);
return powerbi.data.SQExprBuilder.text(<string>fakeValue);
}
export class MockVisualWarning implements powerbi.IVisualWarning {
public static Message: string = 'Warning';
// Allow 'code' to be modified for testing.
public code: string = 'MockVisualWarning';
public getMessages(resourceProvider: jsCommon.IStringResourceProvider): powerbi.IVisualErrorMessage {
var details: powerbi.IVisualErrorMessage = {
message: MockVisualWarning.Message,
title: 'key',
detail: 'val',
};
return details;
}
}
export function setLocale(): void {
powerbi.visuals.DefaultVisualHostServices.initialize();
}
export function getLocalizedString(stringId: string): string {
return defaultVisualHostServices.getLocalizedString(stringId);
}
export class MockGeocoder implements powerbi.IGeocoder {
private callNumber = 0;
private resultList: powerbi.IGeocodeCoordinate[] = [
{ longitude: 90, latitude: -45 },
{ longitude: 90, latitude: 45 },
{ longitude: -90, latitude: -45 },
{ longitude: -90, latitude: 45 },
{ longitude: 0, latitude: 0 },
{ longitude: 45, latitude: -45 },
{ longitude: 45, latitude: 45 },
{ longitude: -45, latitude: -45 },
{ longitude: -45, latitude: 45 },
];
/** With the way our tests run, these values won't be consistent, so you shouldn't validate actual lat/long or pixel lcoations */
public geocode(query: string, category?: string): any {
var resultIndex = this.callNumber++ % this.resultList.length;
var deferred = $.Deferred();
deferred.resolve(this.resultList[resultIndex]);
return deferred;
}
public geocodeBoundary(latitude: number, longitude: number, category: string, levelOfDetail?: number, maxGeoData?: number): any {
// Only the absoluteString is actually used for drawing, but a few other aspects of the geoshape result are checked for simple things like existence and length
var result = {
locations: [{
absoluteString: "84387.1,182914 84397.3,182914 84401.3,182914 84400.9,182898 84417.4,182898 84421.3,182885 84417.4,182877 84418.2,182865 84387.2,182865 84387.1,182914", // A valid map string taken from a piece of Redmond's path
absolute: [84387.1, 182914, 84397.3, 182914, 84401.3, 182914, 84400.9, 182898, 84417.4, 182898, 84421.3, 182885, 84417.4, 182877, 84418.2, 182865, 84387.2, 182865, 84387.1, 182914],
geographic: [undefined, undefined, undefined], // This needs to be an array with length > 2 for checks in map; contents aren't used.
absoluteBounds: {
width: 34.2,
height: 49,
},
}]
};
var deferred = $.Deferred();
deferred.resolve(result);
return deferred;
}
}
export class MockMapControl {
private element;
private width;
private height;
private centerX;
private centerY;
constructor(element: HTMLElement, width: number, height: number) {
this.element = element;
this.width = width;
this.height = height;
this.centerX = width / 2;
this.centerY = height / 2;
}
public getRootElement(): Node {
return this.element;
}
public | (): number {
return this.width;
}
public getHeight(): number {
return this.height;
}
public tryLocationToPixel(location) {
var result;
if (location.length) {
// It's an array of locations; iterate through the array
result = [];
for (var i = 0, ilen = location.length; i < ilen; i++) {
result.push(this.tryLocationToPixelSingle(location[i]));
}
}
else {
// It's just a single location
result = this.tryLocationToPixelSingle(location);
}
return result;
}
private tryLocationToPixelSingle(location: powerbi.IGeocodeCoordinate) {
var centerX = this.centerX;
var centerY = this.centerY;
// Use a really dumb projection with no sort of zooming/panning
return { x: centerX * (location.longitude / 180), y: centerY * (location.latitude / 90) };
}
public setView(viewOptions): void {
// No op placeholder; we don't need to bother with zoom/pan for mocking. Spies can confirm anything about params we care about
}
}
// Mocks for Microsoft's Bing Maps API; implements select methods in the interface for test purposes
// Declared separately from Microsoft.Maps to avoid collision with the declaration in Microsoft.Maps.d.ts
export module MockMaps {
export function loadModule(moduleKey: string, options?: { callback: () => void; }): void {
if (options && options.callback)
options.callback();
}
export class LocationRect {
constructor(center: Location, width: number, height: number) {
this.center = center;
this.width = width;
this.height = height;
}
public center: Location;
public height: number;
public width: number;
public static fromCorners(northwest: Location, southeast: Location): LocationRect {
var centerLat = (northwest.latitude + southeast.latitude) / 2;
var centerLong = (northwest.longitude + southeast.longitude) / 2;
return new LocationRect(
new Location(centerLat, centerLong),
southeast.longitude - northwest.longitude,
northwest.latitude - southeast.latitude);
}
public static fromEdges(north: number, west: number, south: number, east: number, altitude: number, altitudeReference: AltitudeReference): LocationRect {
var centerLat = (north + south) / 2;
var centerLong = (east + west) / 2;
return new LocationRect(
new Location(centerLat, centerLong),
east - west,
north - south);
}
public getNorthwest(): Location {
return new Location(this.center.latitude - this.height / 2, this.center.longitude - this.width / 2);
}
public getSoutheast(): Location {
return new Location(this.center.latitude + this.height / 2, this.center.longitude + this.width / 2);
}
}
export class Location {
constructor(latitude: number, longitude: number, altitude?: number, altitudeReference?: AltitudeReference) {
this.latitude = latitude;
this.longitude = longitude;
this.x = longitude;
this.y = latitude;
}
public latitude: number;
public longitude: number;
public x: number;
public y: number;
}
export class AltitudeReference {
}
export class MapTypeId {
public static road: string = 'r';
}
export module Events {
export function addHandler(target: any, eventName: string, handler: any) { }
}
}
export class MockBehavior implements powerbi.visuals.IInteractiveBehavior {
private selectableDataPoints: SelectableDataPoint[];
private selectionHandler: ISelectionHandler;
private filterPropertyId: powerbi.DataViewObjectPropertyIdentifier;
constructor(selectableDataPoints: SelectableDataPoint[], filterPropertyId: powerbi.DataViewObjectPropertyIdentifier) {
this.selectableDataPoints = selectableDataPoints;
this.filterPropertyId = filterPropertyId;
}
public bindEvents(options: any, selectionHandler: ISelectionHandler): void {
this.selectionHandler = selectionHandler;
}
public renderSelection(hasSelection: boolean): void {
// Stub method to spy on
}
public selectIndex(index: number, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(this.selectableDataPoints[index], !!multiSelect);
}
public select(datapoint: SelectableDataPoint, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(datapoint, !!multiSelect);
}
public clear(): void {
this.selectionHandler.handleClearSelection();
}
public selectIndexAndPersist(index: number, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(this.selectableDataPoints[index], !!multiSelect);
this.selectionHandler.persistSelectionFilter(this.filterPropertyId);
}
public verifyCleared(): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
if (selectableDataPoints[i].selected)
return false;
}
return true;
}
public verifySingleSelectedAt(index: number): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
let dataPoint = selectableDataPoints[i];
if (i === index) {
if (!dataPoint.selected)
return false;
}
else if (dataPoint.selected)
return false;
}
return true;
}
public verifySelectionState(selectionState: boolean[]): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
if (selectableDataPoints[i].selected !== selectionState[i])
return false;
}
return true;
}
public selections(): boolean[] {
let selectableDataPoints = this.selectableDataPoints;
let selections: boolean[] = [];
for (let dataPoint of selectableDataPoints) {
selections.push(!!dataPoint.selected);
}
return selections;
}
}
export class FilterAnalyzerMock implements powerbi.AnalyzedFilter {
public filter: powerbi.data.SemanticFilter;
public defaultValue: powerbi.DefaultValueDefinition;
public isNotFilter: boolean;
public selectedIdentities: powerbi.DataViewScopeIdentity[];
private fieldSQExprs: powerbi.data.SQExpr[];
private container: powerbi.data.FilterValueScopeIdsContainer;
public constructor(filter: powerbi.data.SemanticFilter, fieldSQExprs: powerbi.data.SQExpr[]) {
this.filter = filter;
this.fieldSQExprs = fieldSQExprs;
if (this.filter)
this.container = powerbi.data.SQExprConverter.asScopeIdsContainer(this.filter, this.fieldSQExprs);
else
this.container = { isNot: false, scopeIds: [] };
this.isNotFilter = this.container && this.container.isNot;
this.selectedIdentities = this.container && this.container.scopeIds;
}
public hasDefaultFilterOverride(): boolean {
return false;
}
}
} | getWidth | identifier_name |
mocks.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="_references.ts"/>
module powerbitests.mocks {
import SQExprBuilder = powerbi.data.SQExprBuilder;
import defaultVisualHostServices = powerbi.visuals.defaultVisualHostServices;
import SelectableDataPoint = powerbi.visuals.SelectableDataPoint;
import ISelectionHandler = powerbi.visuals.ISelectionHandler; |
public target() {
TelemetryCallbackMock.callbackCalls++;
}
};
export class AppInsightsV2Mock {
public trackPageViewTimes: number = 0;
public trackEventTimes: number = 0;
public trackEventLastActivityName: string = null;
public trackEventLastAdditionalData: any = {
id: null,
start: null,
end: null,
isInternalUser: null,
userId: null,
category: null,
sessionId: null,
client: null,
build: null,
cluster: null,
};
public trackPageView(): void {
this.trackPageViewTimes++;
}
public trackEvent(activityName: string, additionalData: any): void {
this.trackEventTimes++;
this.trackEventLastActivityName = activityName;
this.trackEventLastAdditionalData = additionalData;
}
}
export var DefaultLoggerMockType: number = 1;
export class MockTimerPromiseFactory implements jsCommon.ITimerPromiseFactory {
public deferred: JQueryDeferred<void>;
public create(delayInMs: number): jsCommon.IRejectablePromise {
if (!this.deferred) {
this.deferred = $.Deferred<void>();
}
return this.deferred;
}
public resolveCurrent(): void {
expect(this.deferred).toBeDefined();
// Note: we need to read the current deferred field into a local var and null out the member before
// we call resolve, just in case one of timer callbacks recursively creates another timer.
var deferred = this.deferred;
this.deferred = undefined;
deferred.resolve();
}
public reject(): void {
expect(this.deferred).toBeDefined();
// Note: we need to read the current deferred field into a local var and null out the member before
// we call reject, just in case one of timer callbacks recursively creates another timer.
var deferred = this.deferred;
this.deferred = undefined;
deferred.reject();
}
public expectNoTimers(): void {
expect(this.deferred).not.toBeDefined();
}
public hasPendingTimers(): boolean {
return !!this.deferred;
}
}
export function createVisualHostServices(): powerbi.IVisualHostServices {
return new DefaultVisualHostServices();
}
export class MockTraceListener implements jsCommon.ITraceListener {
public trace: jsCommon.TraceItem;
public logTrace(trace: jsCommon.TraceItem): void {
this.trace = trace;
}
}
export function dataViewScopeIdentity(fakeValue: string | number | boolean | Date): powerbi.DataViewScopeIdentity {
var expr = constExpr(fakeValue);
return powerbi.data.createDataViewScopeIdentity(expr);
}
export function dataViewScopeIdentityWithEquality(keyExpr: powerbi.data.SQExpr, fakeValue: string | number | boolean | Date): powerbi.DataViewScopeIdentity {
return powerbi.data.createDataViewScopeIdentity(
powerbi.data.SQExprBuilder.equal(
keyExpr,
constExpr(fakeValue)));
}
function constExpr(fakeValue: string | number | boolean | Date): powerbi.data.SQExpr {
if (fakeValue === null)
return SQExprBuilder.nullConstant();
if (fakeValue === true || fakeValue === false)
return SQExprBuilder.boolean(<boolean>fakeValue);
if (typeof (fakeValue) === 'number')
return powerbi.data.SQExprBuilder.double(<number>fakeValue);
if (fakeValue instanceof Date)
return powerbi.data.SQExprBuilder.dateTime(<Date>fakeValue);
return powerbi.data.SQExprBuilder.text(<string>fakeValue);
}
export class MockVisualWarning implements powerbi.IVisualWarning {
public static Message: string = 'Warning';
// Allow 'code' to be modified for testing.
public code: string = 'MockVisualWarning';
public getMessages(resourceProvider: jsCommon.IStringResourceProvider): powerbi.IVisualErrorMessage {
var details: powerbi.IVisualErrorMessage = {
message: MockVisualWarning.Message,
title: 'key',
detail: 'val',
};
return details;
}
}
export function setLocale(): void {
powerbi.visuals.DefaultVisualHostServices.initialize();
}
export function getLocalizedString(stringId: string): string {
return defaultVisualHostServices.getLocalizedString(stringId);
}
export class MockGeocoder implements powerbi.IGeocoder {
private callNumber = 0;
private resultList: powerbi.IGeocodeCoordinate[] = [
{ longitude: 90, latitude: -45 },
{ longitude: 90, latitude: 45 },
{ longitude: -90, latitude: -45 },
{ longitude: -90, latitude: 45 },
{ longitude: 0, latitude: 0 },
{ longitude: 45, latitude: -45 },
{ longitude: 45, latitude: 45 },
{ longitude: -45, latitude: -45 },
{ longitude: -45, latitude: 45 },
];
/** With the way our tests run, these values won't be consistent, so you shouldn't validate actual lat/long or pixel lcoations */
public geocode(query: string, category?: string): any {
var resultIndex = this.callNumber++ % this.resultList.length;
var deferred = $.Deferred();
deferred.resolve(this.resultList[resultIndex]);
return deferred;
}
public geocodeBoundary(latitude: number, longitude: number, category: string, levelOfDetail?: number, maxGeoData?: number): any {
// Only the absoluteString is actually used for drawing, but a few other aspects of the geoshape result are checked for simple things like existence and length
var result = {
locations: [{
absoluteString: "84387.1,182914 84397.3,182914 84401.3,182914 84400.9,182898 84417.4,182898 84421.3,182885 84417.4,182877 84418.2,182865 84387.2,182865 84387.1,182914", // A valid map string taken from a piece of Redmond's path
absolute: [84387.1, 182914, 84397.3, 182914, 84401.3, 182914, 84400.9, 182898, 84417.4, 182898, 84421.3, 182885, 84417.4, 182877, 84418.2, 182865, 84387.2, 182865, 84387.1, 182914],
geographic: [undefined, undefined, undefined], // This needs to be an array with length > 2 for checks in map; contents aren't used.
absoluteBounds: {
width: 34.2,
height: 49,
},
}]
};
var deferred = $.Deferred();
deferred.resolve(result);
return deferred;
}
}
export class MockMapControl {
private element;
private width;
private height;
private centerX;
private centerY;
constructor(element: HTMLElement, width: number, height: number) {
this.element = element;
this.width = width;
this.height = height;
this.centerX = width / 2;
this.centerY = height / 2;
}
public getRootElement(): Node {
return this.element;
}
public getWidth(): number {
return this.width;
}
public getHeight(): number {
return this.height;
}
public tryLocationToPixel(location) {
var result;
if (location.length) {
// It's an array of locations; iterate through the array
result = [];
for (var i = 0, ilen = location.length; i < ilen; i++) {
result.push(this.tryLocationToPixelSingle(location[i]));
}
}
else {
// It's just a single location
result = this.tryLocationToPixelSingle(location);
}
return result;
}
private tryLocationToPixelSingle(location: powerbi.IGeocodeCoordinate) {
var centerX = this.centerX;
var centerY = this.centerY;
// Use a really dumb projection with no sort of zooming/panning
return { x: centerX * (location.longitude / 180), y: centerY * (location.latitude / 90) };
}
public setView(viewOptions): void {
// No op placeholder; we don't need to bother with zoom/pan for mocking. Spies can confirm anything about params we care about
}
}
// Mocks for Microsoft's Bing Maps API; implements select methods in the interface for test purposes
// Declared separately from Microsoft.Maps to avoid collision with the declaration in Microsoft.Maps.d.ts
export module MockMaps {
export function loadModule(moduleKey: string, options?: { callback: () => void; }): void {
if (options && options.callback)
options.callback();
}
export class LocationRect {
constructor(center: Location, width: number, height: number) {
this.center = center;
this.width = width;
this.height = height;
}
public center: Location;
public height: number;
public width: number;
public static fromCorners(northwest: Location, southeast: Location): LocationRect {
var centerLat = (northwest.latitude + southeast.latitude) / 2;
var centerLong = (northwest.longitude + southeast.longitude) / 2;
return new LocationRect(
new Location(centerLat, centerLong),
southeast.longitude - northwest.longitude,
northwest.latitude - southeast.latitude);
}
public static fromEdges(north: number, west: number, south: number, east: number, altitude: number, altitudeReference: AltitudeReference): LocationRect {
var centerLat = (north + south) / 2;
var centerLong = (east + west) / 2;
return new LocationRect(
new Location(centerLat, centerLong),
east - west,
north - south);
}
public getNorthwest(): Location {
return new Location(this.center.latitude - this.height / 2, this.center.longitude - this.width / 2);
}
public getSoutheast(): Location {
return new Location(this.center.latitude + this.height / 2, this.center.longitude + this.width / 2);
}
}
export class Location {
constructor(latitude: number, longitude: number, altitude?: number, altitudeReference?: AltitudeReference) {
this.latitude = latitude;
this.longitude = longitude;
this.x = longitude;
this.y = latitude;
}
public latitude: number;
public longitude: number;
public x: number;
public y: number;
}
export class AltitudeReference {
}
export class MapTypeId {
public static road: string = 'r';
}
export module Events {
export function addHandler(target: any, eventName: string, handler: any) { }
}
}
export class MockBehavior implements powerbi.visuals.IInteractiveBehavior {
private selectableDataPoints: SelectableDataPoint[];
private selectionHandler: ISelectionHandler;
private filterPropertyId: powerbi.DataViewObjectPropertyIdentifier;
constructor(selectableDataPoints: SelectableDataPoint[], filterPropertyId: powerbi.DataViewObjectPropertyIdentifier) {
this.selectableDataPoints = selectableDataPoints;
this.filterPropertyId = filterPropertyId;
}
public bindEvents(options: any, selectionHandler: ISelectionHandler): void {
this.selectionHandler = selectionHandler;
}
public renderSelection(hasSelection: boolean): void {
// Stub method to spy on
}
public selectIndex(index: number, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(this.selectableDataPoints[index], !!multiSelect);
}
public select(datapoint: SelectableDataPoint, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(datapoint, !!multiSelect);
}
public clear(): void {
this.selectionHandler.handleClearSelection();
}
public selectIndexAndPersist(index: number, multiSelect?: boolean): void {
this.selectionHandler.handleSelection(this.selectableDataPoints[index], !!multiSelect);
this.selectionHandler.persistSelectionFilter(this.filterPropertyId);
}
public verifyCleared(): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
if (selectableDataPoints[i].selected)
return false;
}
return true;
}
public verifySingleSelectedAt(index: number): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
let dataPoint = selectableDataPoints[i];
if (i === index) {
if (!dataPoint.selected)
return false;
}
else if (dataPoint.selected)
return false;
}
return true;
}
public verifySelectionState(selectionState: boolean[]): boolean {
let selectableDataPoints = this.selectableDataPoints;
for (let i = 0, ilen = selectableDataPoints.length; i < ilen; i++) {
if (selectableDataPoints[i].selected !== selectionState[i])
return false;
}
return true;
}
public selections(): boolean[] {
let selectableDataPoints = this.selectableDataPoints;
let selections: boolean[] = [];
for (let dataPoint of selectableDataPoints) {
selections.push(!!dataPoint.selected);
}
return selections;
}
}
export class FilterAnalyzerMock implements powerbi.AnalyzedFilter {
public filter: powerbi.data.SemanticFilter;
public defaultValue: powerbi.DefaultValueDefinition;
public isNotFilter: boolean;
public selectedIdentities: powerbi.DataViewScopeIdentity[];
private fieldSQExprs: powerbi.data.SQExpr[];
private container: powerbi.data.FilterValueScopeIdsContainer;
public constructor(filter: powerbi.data.SemanticFilter, fieldSQExprs: powerbi.data.SQExpr[]) {
this.filter = filter;
this.fieldSQExprs = fieldSQExprs;
if (this.filter)
this.container = powerbi.data.SQExprConverter.asScopeIdsContainer(this.filter, this.fieldSQExprs);
else
this.container = { isNot: false, scopeIds: [] };
this.isNotFilter = this.container && this.container.isNot;
this.selectedIdentities = this.container && this.container.scopeIds;
}
public hasDefaultFilterOverride(): boolean {
return false;
}
}
} | import DefaultVisualHostServices = powerbi.visuals.DefaultVisualHostServices;
export class TelemetryCallbackMock {
public static callbackCalls: number = 0; | random_line_split |
jmx.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
from ducktape.cluster.remoteaccount import RemoteCommandError
from ducktape.utils.util import wait_until
class JmxMixin(object):
"""This mixin helps existing service subclasses start JmxTool on their worker nodes and collect jmx stats.
A couple things worth noting:
- this is not a service in its own right.
- we assume the service using JmxMixin also uses KafkaPathResolverMixin
"""
def __init__(self, num_nodes, jmx_object_names=None, jmx_attributes=None):
self.jmx_object_names = jmx_object_names
self.jmx_attributes = jmx_attributes or []
self.jmx_port = 9192
self.started = [False] * num_nodes
self.jmx_stats = [{} for x in range(num_nodes)]
self.maximum_jmx_value = {} # map from object_attribute_name to maximum value observed over time
self.average_jmx_value = {} # map from object_attribute_name to average value observed over time
self.jmx_tool_log = "/mnt/jmx_tool.log"
self.jmx_tool_err_log = "/mnt/jmx_tool.err.log"
def clean_node(self, node):
node.account.kill_process("jmx", clean_shutdown=False, allow_fail=True)
node.account.ssh("rm -rf %s" % self.jmx_tool_log, allow_fail=False)
def start_jmx_tool(self, idx, node):
if self.jmx_object_names is None:
self.logger.debug("%s: Not starting jmx tool because no jmx objects are defined" % node.account)
return
if self.started[idx-1]:
self.logger.debug("%s: jmx tool has been started already on this node" % node.account)
return
cmd = "%s kafka.tools.JmxTool " % self.path.script("kafka-run-class.sh", node)
cmd += "--reporting-interval 1000 --jmx-url service:jmx:rmi:///jndi/rmi://127.0.0.1:%d/jmxrmi" % self.jmx_port
for jmx_object_name in self.jmx_object_names:
cmd += " --object-name %s" % jmx_object_name
for jmx_attribute in self.jmx_attributes:
cmd += " --attributes %s" % jmx_attribute
cmd += " 1>> %s" % self.jmx_tool_log
cmd += " 2>> %s &" % self.jmx_tool_err_log
self.logger.debug("%s: Start JmxTool %d command: %s" % (node.account, idx, cmd))
node.account.ssh(cmd, allow_fail=False)
wait_until(lambda: self._jmx_has_output(node), timeout_sec=10, backoff_sec=.5, err_msg="%s: Jmx tool took too long to start" % node.account)
self.started[idx-1] = True
def _jmx_has_output(self, node):
"""Helper used as a proxy to determine whether jmx is running by that jmx_tool_log contains output."""
try:
node.account.ssh("test -z \"$(cat %s)\"" % self.jmx_tool_log, allow_fail=False)
return False
except RemoteCommandError:
return True
def read_jmx_output(self, idx, node):
|
def read_jmx_output_all_nodes(self):
for node in self.nodes:
self.read_jmx_output(self.idx(node), node)
| if not self.started[idx-1]:
return
object_attribute_names = []
cmd = "cat %s" % self.jmx_tool_log
self.logger.debug("Read jmx output %d command: %s", idx, cmd)
lines = [line for line in node.account.ssh_capture(cmd, allow_fail=False)]
assert len(lines) > 1, "There don't appear to be any samples in the jmx tool log: %s" % lines
for line in lines:
if "time" in line:
object_attribute_names = line.strip()[1:-1].split("\",\"")[1:]
continue
stats = [float(field) for field in line.split(',')]
time_sec = int(stats[0]/1000)
self.jmx_stats[idx-1][time_sec] = {name: stats[i+1] for i, name in enumerate(object_attribute_names)}
# do not calculate average and maximum of jmx stats until we have read output from all nodes
# If the service is multithreaded, this means that the results will be aggregated only when the last
# service finishes
if any(len(time_to_stats) == 0 for time_to_stats in self.jmx_stats):
return
start_time_sec = min([min(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
end_time_sec = max([max(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
for name in object_attribute_names:
aggregates_per_time = []
for time_sec in xrange(start_time_sec, end_time_sec + 1):
# assume that value is 0 if it is not read by jmx tool at the given time. This is appropriate for metrics such as bandwidth
values_per_node = [time_to_stats.get(time_sec, {}).get(name, 0) for time_to_stats in self.jmx_stats]
# assume that value is aggregated across nodes by sum. This is appropriate for metrics such as bandwidth
aggregates_per_time.append(sum(values_per_node))
self.average_jmx_value[name] = sum(aggregates_per_time) / len(aggregates_per_time)
self.maximum_jmx_value[name] = max(aggregates_per_time) | identifier_body |
jmx.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
from ducktape.cluster.remoteaccount import RemoteCommandError
from ducktape.utils.util import wait_until
class JmxMixin(object):
"""This mixin helps existing service subclasses start JmxTool on their worker nodes and collect jmx stats.
A couple things worth noting:
- this is not a service in its own right.
- we assume the service using JmxMixin also uses KafkaPathResolverMixin
"""
def | (self, num_nodes, jmx_object_names=None, jmx_attributes=None):
self.jmx_object_names = jmx_object_names
self.jmx_attributes = jmx_attributes or []
self.jmx_port = 9192
self.started = [False] * num_nodes
self.jmx_stats = [{} for x in range(num_nodes)]
self.maximum_jmx_value = {} # map from object_attribute_name to maximum value observed over time
self.average_jmx_value = {} # map from object_attribute_name to average value observed over time
self.jmx_tool_log = "/mnt/jmx_tool.log"
self.jmx_tool_err_log = "/mnt/jmx_tool.err.log"
def clean_node(self, node):
node.account.kill_process("jmx", clean_shutdown=False, allow_fail=True)
node.account.ssh("rm -rf %s" % self.jmx_tool_log, allow_fail=False)
def start_jmx_tool(self, idx, node):
if self.jmx_object_names is None:
self.logger.debug("%s: Not starting jmx tool because no jmx objects are defined" % node.account)
return
if self.started[idx-1]:
self.logger.debug("%s: jmx tool has been started already on this node" % node.account)
return
cmd = "%s kafka.tools.JmxTool " % self.path.script("kafka-run-class.sh", node)
cmd += "--reporting-interval 1000 --jmx-url service:jmx:rmi:///jndi/rmi://127.0.0.1:%d/jmxrmi" % self.jmx_port
for jmx_object_name in self.jmx_object_names:
cmd += " --object-name %s" % jmx_object_name
for jmx_attribute in self.jmx_attributes:
cmd += " --attributes %s" % jmx_attribute
cmd += " 1>> %s" % self.jmx_tool_log
cmd += " 2>> %s &" % self.jmx_tool_err_log
self.logger.debug("%s: Start JmxTool %d command: %s" % (node.account, idx, cmd))
node.account.ssh(cmd, allow_fail=False)
wait_until(lambda: self._jmx_has_output(node), timeout_sec=10, backoff_sec=.5, err_msg="%s: Jmx tool took too long to start" % node.account)
self.started[idx-1] = True
def _jmx_has_output(self, node):
"""Helper used as a proxy to determine whether jmx is running by that jmx_tool_log contains output."""
try:
node.account.ssh("test -z \"$(cat %s)\"" % self.jmx_tool_log, allow_fail=False)
return False
except RemoteCommandError:
return True
def read_jmx_output(self, idx, node):
if not self.started[idx-1]:
return
object_attribute_names = []
cmd = "cat %s" % self.jmx_tool_log
self.logger.debug("Read jmx output %d command: %s", idx, cmd)
lines = [line for line in node.account.ssh_capture(cmd, allow_fail=False)]
assert len(lines) > 1, "There don't appear to be any samples in the jmx tool log: %s" % lines
for line in lines:
if "time" in line:
object_attribute_names = line.strip()[1:-1].split("\",\"")[1:]
continue
stats = [float(field) for field in line.split(',')]
time_sec = int(stats[0]/1000)
self.jmx_stats[idx-1][time_sec] = {name: stats[i+1] for i, name in enumerate(object_attribute_names)}
# do not calculate average and maximum of jmx stats until we have read output from all nodes
# If the service is multithreaded, this means that the results will be aggregated only when the last
# service finishes
if any(len(time_to_stats) == 0 for time_to_stats in self.jmx_stats):
return
start_time_sec = min([min(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
end_time_sec = max([max(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
for name in object_attribute_names:
aggregates_per_time = []
for time_sec in xrange(start_time_sec, end_time_sec + 1):
# assume that value is 0 if it is not read by jmx tool at the given time. This is appropriate for metrics such as bandwidth
values_per_node = [time_to_stats.get(time_sec, {}).get(name, 0) for time_to_stats in self.jmx_stats]
# assume that value is aggregated across nodes by sum. This is appropriate for metrics such as bandwidth
aggregates_per_time.append(sum(values_per_node))
self.average_jmx_value[name] = sum(aggregates_per_time) / len(aggregates_per_time)
self.maximum_jmx_value[name] = max(aggregates_per_time)
def read_jmx_output_all_nodes(self):
for node in self.nodes:
self.read_jmx_output(self.idx(node), node)
| __init__ | identifier_name |
jmx.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
from ducktape.cluster.remoteaccount import RemoteCommandError
from ducktape.utils.util import wait_until
class JmxMixin(object):
"""This mixin helps existing service subclasses start JmxTool on their worker nodes and collect jmx stats.
A couple things worth noting:
- this is not a service in its own right.
- we assume the service using JmxMixin also uses KafkaPathResolverMixin
"""
def __init__(self, num_nodes, jmx_object_names=None, jmx_attributes=None):
self.jmx_object_names = jmx_object_names
self.jmx_attributes = jmx_attributes or []
self.jmx_port = 9192
self.started = [False] * num_nodes
self.jmx_stats = [{} for x in range(num_nodes)]
self.maximum_jmx_value = {} # map from object_attribute_name to maximum value observed over time
self.average_jmx_value = {} # map from object_attribute_name to average value observed over time
self.jmx_tool_log = "/mnt/jmx_tool.log"
self.jmx_tool_err_log = "/mnt/jmx_tool.err.log"
def clean_node(self, node):
node.account.kill_process("jmx", clean_shutdown=False, allow_fail=True)
node.account.ssh("rm -rf %s" % self.jmx_tool_log, allow_fail=False)
def start_jmx_tool(self, idx, node):
if self.jmx_object_names is None:
self.logger.debug("%s: Not starting jmx tool because no jmx objects are defined" % node.account)
return
if self.started[idx-1]:
self.logger.debug("%s: jmx tool has been started already on this node" % node.account)
return
cmd = "%s kafka.tools.JmxTool " % self.path.script("kafka-run-class.sh", node)
cmd += "--reporting-interval 1000 --jmx-url service:jmx:rmi:///jndi/rmi://127.0.0.1:%d/jmxrmi" % self.jmx_port
for jmx_object_name in self.jmx_object_names:
cmd += " --object-name %s" % jmx_object_name
for jmx_attribute in self.jmx_attributes:
cmd += " --attributes %s" % jmx_attribute
cmd += " 1>> %s" % self.jmx_tool_log
cmd += " 2>> %s &" % self.jmx_tool_err_log
self.logger.debug("%s: Start JmxTool %d command: %s" % (node.account, idx, cmd))
node.account.ssh(cmd, allow_fail=False)
wait_until(lambda: self._jmx_has_output(node), timeout_sec=10, backoff_sec=.5, err_msg="%s: Jmx tool took too long to start" % node.account)
self.started[idx-1] = True
def _jmx_has_output(self, node):
"""Helper used as a proxy to determine whether jmx is running by that jmx_tool_log contains output."""
try:
node.account.ssh("test -z \"$(cat %s)\"" % self.jmx_tool_log, allow_fail=False)
return False
except RemoteCommandError:
return True
def read_jmx_output(self, idx, node):
if not self.started[idx-1]:
return
object_attribute_names = [] | assert len(lines) > 1, "There don't appear to be any samples in the jmx tool log: %s" % lines
for line in lines:
if "time" in line:
object_attribute_names = line.strip()[1:-1].split("\",\"")[1:]
continue
stats = [float(field) for field in line.split(',')]
time_sec = int(stats[0]/1000)
self.jmx_stats[idx-1][time_sec] = {name: stats[i+1] for i, name in enumerate(object_attribute_names)}
# do not calculate average and maximum of jmx stats until we have read output from all nodes
# If the service is multithreaded, this means that the results will be aggregated only when the last
# service finishes
if any(len(time_to_stats) == 0 for time_to_stats in self.jmx_stats):
return
start_time_sec = min([min(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
end_time_sec = max([max(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
for name in object_attribute_names:
aggregates_per_time = []
for time_sec in xrange(start_time_sec, end_time_sec + 1):
# assume that value is 0 if it is not read by jmx tool at the given time. This is appropriate for metrics such as bandwidth
values_per_node = [time_to_stats.get(time_sec, {}).get(name, 0) for time_to_stats in self.jmx_stats]
# assume that value is aggregated across nodes by sum. This is appropriate for metrics such as bandwidth
aggregates_per_time.append(sum(values_per_node))
self.average_jmx_value[name] = sum(aggregates_per_time) / len(aggregates_per_time)
self.maximum_jmx_value[name] = max(aggregates_per_time)
def read_jmx_output_all_nodes(self):
for node in self.nodes:
self.read_jmx_output(self.idx(node), node) |
cmd = "cat %s" % self.jmx_tool_log
self.logger.debug("Read jmx output %d command: %s", idx, cmd)
lines = [line for line in node.account.ssh_capture(cmd, allow_fail=False)] | random_line_split |
jmx.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
from ducktape.cluster.remoteaccount import RemoteCommandError
from ducktape.utils.util import wait_until
class JmxMixin(object):
"""This mixin helps existing service subclasses start JmxTool on their worker nodes and collect jmx stats.
A couple things worth noting:
- this is not a service in its own right.
- we assume the service using JmxMixin also uses KafkaPathResolverMixin
"""
def __init__(self, num_nodes, jmx_object_names=None, jmx_attributes=None):
self.jmx_object_names = jmx_object_names
self.jmx_attributes = jmx_attributes or []
self.jmx_port = 9192
self.started = [False] * num_nodes
self.jmx_stats = [{} for x in range(num_nodes)]
self.maximum_jmx_value = {} # map from object_attribute_name to maximum value observed over time
self.average_jmx_value = {} # map from object_attribute_name to average value observed over time
self.jmx_tool_log = "/mnt/jmx_tool.log"
self.jmx_tool_err_log = "/mnt/jmx_tool.err.log"
def clean_node(self, node):
node.account.kill_process("jmx", clean_shutdown=False, allow_fail=True)
node.account.ssh("rm -rf %s" % self.jmx_tool_log, allow_fail=False)
def start_jmx_tool(self, idx, node):
if self.jmx_object_names is None:
self.logger.debug("%s: Not starting jmx tool because no jmx objects are defined" % node.account)
return
if self.started[idx-1]:
self.logger.debug("%s: jmx tool has been started already on this node" % node.account)
return
cmd = "%s kafka.tools.JmxTool " % self.path.script("kafka-run-class.sh", node)
cmd += "--reporting-interval 1000 --jmx-url service:jmx:rmi:///jndi/rmi://127.0.0.1:%d/jmxrmi" % self.jmx_port
for jmx_object_name in self.jmx_object_names:
cmd += " --object-name %s" % jmx_object_name
for jmx_attribute in self.jmx_attributes:
cmd += " --attributes %s" % jmx_attribute
cmd += " 1>> %s" % self.jmx_tool_log
cmd += " 2>> %s &" % self.jmx_tool_err_log
self.logger.debug("%s: Start JmxTool %d command: %s" % (node.account, idx, cmd))
node.account.ssh(cmd, allow_fail=False)
wait_until(lambda: self._jmx_has_output(node), timeout_sec=10, backoff_sec=.5, err_msg="%s: Jmx tool took too long to start" % node.account)
self.started[idx-1] = True
def _jmx_has_output(self, node):
"""Helper used as a proxy to determine whether jmx is running by that jmx_tool_log contains output."""
try:
node.account.ssh("test -z \"$(cat %s)\"" % self.jmx_tool_log, allow_fail=False)
return False
except RemoteCommandError:
return True
def read_jmx_output(self, idx, node):
if not self.started[idx-1]:
return
object_attribute_names = []
cmd = "cat %s" % self.jmx_tool_log
self.logger.debug("Read jmx output %d command: %s", idx, cmd)
lines = [line for line in node.account.ssh_capture(cmd, allow_fail=False)]
assert len(lines) > 1, "There don't appear to be any samples in the jmx tool log: %s" % lines
for line in lines:
if "time" in line:
|
stats = [float(field) for field in line.split(',')]
time_sec = int(stats[0]/1000)
self.jmx_stats[idx-1][time_sec] = {name: stats[i+1] for i, name in enumerate(object_attribute_names)}
# do not calculate average and maximum of jmx stats until we have read output from all nodes
# If the service is multithreaded, this means that the results will be aggregated only when the last
# service finishes
if any(len(time_to_stats) == 0 for time_to_stats in self.jmx_stats):
return
start_time_sec = min([min(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
end_time_sec = max([max(time_to_stats.keys()) for time_to_stats in self.jmx_stats])
for name in object_attribute_names:
aggregates_per_time = []
for time_sec in xrange(start_time_sec, end_time_sec + 1):
# assume that value is 0 if it is not read by jmx tool at the given time. This is appropriate for metrics such as bandwidth
values_per_node = [time_to_stats.get(time_sec, {}).get(name, 0) for time_to_stats in self.jmx_stats]
# assume that value is aggregated across nodes by sum. This is appropriate for metrics such as bandwidth
aggregates_per_time.append(sum(values_per_node))
self.average_jmx_value[name] = sum(aggregates_per_time) / len(aggregates_per_time)
self.maximum_jmx_value[name] = max(aggregates_per_time)
def read_jmx_output_all_nodes(self):
for node in self.nodes:
self.read_jmx_output(self.idx(node), node)
| object_attribute_names = line.strip()[1:-1].split("\",\"")[1:]
continue | conditional_block |
presets-logic.ts | import { presets } from '../../config/presets';
import { Subscription } from 'rxjs';
import { Actions, nextActionFromMsg } from '../../../Shared/actions/actions';
import { IControlPresetMsg, IModifierOptions } from '../../../Shared/actions/types';
export abstract class PresetLogic {
readonly modifierOptions: IModifierOptions;
title: string = this.constructor.name;
state = false;
modifier = 127; // Important; otherwise it will send noteOff
protected subscriptions: Subscription[] = [];
| (modifier: number) {
this.modifier = modifier;
this._stopPreset();
this._startPreset();
this.state = true;
nextActionFromMsg(Actions.presetState(getPresetState()));
}
stopPreset() {
// Unsubscribe and reset array
this.subscriptions.forEach(sub => sub.unsubscribe());
this.subscriptions = [];
this._stopPreset();
this.state = false;
nextActionFromMsg(Actions.presetState(getPresetState()));
}
addSub(sub: Subscription) {
this.subscriptions.push(sub);
}
protected abstract _startPreset(): void;
protected abstract _stopPreset(): void;
}
export const presetChange = (preset: PresetLogic, modifier: number, state: boolean) => {
return Actions.presetChange({
preset: +Object.getOwnPropertyNames(presets).find(presetNote => presets[presetNote].title === preset.title),
modifier,
state,
});
};
export function getPresetState(): IControlPresetMsg[] {
return Object.getOwnPropertyNames(presets).map(presetNr => {
const {modifier, modifierOptions: config, title, state} = presets[presetNr];
return {
// preset key is a string, but send it as number
preset: +presetNr,
modifier,
state,
title,
config,
} as IControlPresetMsg;
});
}
| startPreset | identifier_name |
presets-logic.ts | import { presets } from '../../config/presets';
import { Subscription } from 'rxjs';
import { Actions, nextActionFromMsg } from '../../../Shared/actions/actions';
import { IControlPresetMsg, IModifierOptions } from '../../../Shared/actions/types';
export abstract class PresetLogic {
readonly modifierOptions: IModifierOptions;
title: string = this.constructor.name;
state = false;
modifier = 127; // Important; otherwise it will send noteOff
protected subscriptions: Subscription[] = [];
startPreset(modifier: number) {
this.modifier = modifier;
this._stopPreset();
this._startPreset();
this.state = true;
nextActionFromMsg(Actions.presetState(getPresetState()));
}
stopPreset() {
// Unsubscribe and reset array
this.subscriptions.forEach(sub => sub.unsubscribe());
this.subscriptions = [];
this._stopPreset();
this.state = false;
nextActionFromMsg(Actions.presetState(getPresetState()));
}
addSub(sub: Subscription) {
this.subscriptions.push(sub);
}
protected abstract _startPreset(): void;
protected abstract _stopPreset(): void;
}
export const presetChange = (preset: PresetLogic, modifier: number, state: boolean) => {
return Actions.presetChange({
preset: +Object.getOwnPropertyNames(presets).find(presetNote => presets[presetNote].title === preset.title),
modifier,
state,
});
};
export function getPresetState(): IControlPresetMsg[] {
return Object.getOwnPropertyNames(presets).map(presetNr => {
const {modifier, modifierOptions: config, title, state} = presets[presetNr];
return {
// preset key is a string, but send it as number | state,
title,
config,
} as IControlPresetMsg;
});
} | preset: +presetNr,
modifier, | random_line_split |
presets-logic.ts | import { presets } from '../../config/presets';
import { Subscription } from 'rxjs';
import { Actions, nextActionFromMsg } from '../../../Shared/actions/actions';
import { IControlPresetMsg, IModifierOptions } from '../../../Shared/actions/types';
export abstract class PresetLogic {
readonly modifierOptions: IModifierOptions;
title: string = this.constructor.name;
state = false;
modifier = 127; // Important; otherwise it will send noteOff
protected subscriptions: Subscription[] = [];
startPreset(modifier: number) {
this.modifier = modifier;
this._stopPreset();
this._startPreset();
this.state = true;
nextActionFromMsg(Actions.presetState(getPresetState()));
}
stopPreset() |
addSub(sub: Subscription) {
this.subscriptions.push(sub);
}
protected abstract _startPreset(): void;
protected abstract _stopPreset(): void;
}
export const presetChange = (preset: PresetLogic, modifier: number, state: boolean) => {
return Actions.presetChange({
preset: +Object.getOwnPropertyNames(presets).find(presetNote => presets[presetNote].title === preset.title),
modifier,
state,
});
};
export function getPresetState(): IControlPresetMsg[] {
return Object.getOwnPropertyNames(presets).map(presetNr => {
const {modifier, modifierOptions: config, title, state} = presets[presetNr];
return {
// preset key is a string, but send it as number
preset: +presetNr,
modifier,
state,
title,
config,
} as IControlPresetMsg;
});
}
| {
// Unsubscribe and reset array
this.subscriptions.forEach(sub => sub.unsubscribe());
this.subscriptions = [];
this._stopPreset();
this.state = false;
nextActionFromMsg(Actions.presetState(getPresetState()));
} | identifier_body |
Verniana-Jules Verne Studies.js | {
"translatorID":"cdf8269c-86b9-4039-9bc4-9d998c67740e",
"translatorType":4,
"label":"Verniana-Jules Verne Studies",
"creator":"Michael Berkowitz",
"target":"http://jv.gilead.org.il/studies/",
"minVersion":"1.0.0b4.r5",
"maxVersion":"",
"priority":100,
"inRepository":true,
"lastUpdated":"2008-05-21 19:15:00"
}
function detectWeb(doc, url) {
if (url.match(/article\/view/)) {
return "journalArticle";
} else if (url.match(/(issue|advancedResults)/)) {
return "multiple";
}
}
function prepNos(link) {
if (link.match(/\d+\/\d+$/)) {
var nos = link.match(/\d+\/\d+$/)[0];
} else {
var nos = link.match(/\d+$/)[0] + '/0';
}
return 'http://jv.gilead.org.il/studies/index.php/studies/rt/captureCite/' + nos + '/RefManCitationPlugin';
}
function doWeb(doc, url) {
var n = doc.documentElement.namespaceURI;
var ns = n ? function(prefix) {
if (prefix == 'x') return n; else return null;
} : null;
var arts = new Array();
if (detectWeb(doc, url) == "multiple") {
var items = new Object();
var xpath = '//tr[td/a[2]]';
if (url.match(/issue/)) {
var titlex = './td[1]';
var linkx = './td[2]/a[contains(text(), "HTML")]';
} else if (url.match(/advanced/)) {
var titlex = './td[2]';
var linkx = './td[3]/a[contains(text(), "HTML")]';
}
var results = doc.evaluate(xpath, doc, ns, XPathResult.ANY_TYPE, null);
var result;
while (result = results.iterateNext()) {
var title = Zotero.Utilities.trimInternal(doc.evaluate(titlex, result, ns, XPathResult.ANY_TYPE, null).iterateNext().textContent);
var link = doc.evaluate(linkx, result, ns, XPathResult.ANY_TYPE, null).iterateNext().href;
items[link] = title;
}
items = Zotero.selectItems(items);
for (var i in items) {
arts.push(prepNos(i));
}
} else {
arts = [prepNos(url)];
}
Zotero.Utilities.HTTP.doGet(arts, function(text) {
var translator = Zotero.loadTranslator("import");
translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
translator.setString(text);
translator.setHandler("itemDone", function(obj, item) {
var auts = new Array();
for each (var aut in item.creators) {
auts.push(Zotero.Utilities.cleanAuthor(aut.lastName, "author"));
}
item.creators = auts;
item.attachments = [{url:item.url, title:"Verniana Snapshot", mimeType:"text/html"}]; | var bits = item.publicationTitle.split(/;/);
item.publicationTitle = bits[0];
var voliss = bits[1].match(/Vol\s+(\d+)\s+\((\d+)\)/);
item.volume = voliss[1];
item.date = voliss[2];
item.complete();
});
translator.translate();
});
Zotero.wait();
} | random_line_split | |
Verniana-Jules Verne Studies.js | {
"translatorID":"cdf8269c-86b9-4039-9bc4-9d998c67740e",
"translatorType":4,
"label":"Verniana-Jules Verne Studies",
"creator":"Michael Berkowitz",
"target":"http://jv.gilead.org.il/studies/",
"minVersion":"1.0.0b4.r5",
"maxVersion":"",
"priority":100,
"inRepository":true,
"lastUpdated":"2008-05-21 19:15:00"
}
function detectWeb(doc, url) {
if (url.match(/article\/view/)) {
return "journalArticle";
} else if (url.match(/(issue|advancedResults)/)) {
return "multiple";
}
}
function prepNos(link) {
if (link.match(/\d+\/\d+$/)) {
var nos = link.match(/\d+\/\d+$/)[0];
} else {
var nos = link.match(/\d+$/)[0] + '/0';
}
return 'http://jv.gilead.org.il/studies/index.php/studies/rt/captureCite/' + nos + '/RefManCitationPlugin';
}
function doWeb(doc, url) | {
var n = doc.documentElement.namespaceURI;
var ns = n ? function(prefix) {
if (prefix == 'x') return n; else return null;
} : null;
var arts = new Array();
if (detectWeb(doc, url) == "multiple") {
var items = new Object();
var xpath = '//tr[td/a[2]]';
if (url.match(/issue/)) {
var titlex = './td[1]';
var linkx = './td[2]/a[contains(text(), "HTML")]';
} else if (url.match(/advanced/)) {
var titlex = './td[2]';
var linkx = './td[3]/a[contains(text(), "HTML")]';
}
var results = doc.evaluate(xpath, doc, ns, XPathResult.ANY_TYPE, null);
var result;
while (result = results.iterateNext()) {
var title = Zotero.Utilities.trimInternal(doc.evaluate(titlex, result, ns, XPathResult.ANY_TYPE, null).iterateNext().textContent);
var link = doc.evaluate(linkx, result, ns, XPathResult.ANY_TYPE, null).iterateNext().href;
items[link] = title;
}
items = Zotero.selectItems(items);
for (var i in items) {
arts.push(prepNos(i));
}
} else {
arts = [prepNos(url)];
}
Zotero.Utilities.HTTP.doGet(arts, function(text) {
var translator = Zotero.loadTranslator("import");
translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
translator.setString(text);
translator.setHandler("itemDone", function(obj, item) {
var auts = new Array();
for each (var aut in item.creators) {
auts.push(Zotero.Utilities.cleanAuthor(aut.lastName, "author"));
}
item.creators = auts;
item.attachments = [{url:item.url, title:"Verniana Snapshot", mimeType:"text/html"}];
var bits = item.publicationTitle.split(/;/);
item.publicationTitle = bits[0];
var voliss = bits[1].match(/Vol\s+(\d+)\s+\((\d+)\)/);
item.volume = voliss[1];
item.date = voliss[2];
item.complete();
});
translator.translate();
});
Zotero.wait();
} | identifier_body | |
Verniana-Jules Verne Studies.js | {
"translatorID":"cdf8269c-86b9-4039-9bc4-9d998c67740e",
"translatorType":4,
"label":"Verniana-Jules Verne Studies",
"creator":"Michael Berkowitz",
"target":"http://jv.gilead.org.il/studies/",
"minVersion":"1.0.0b4.r5",
"maxVersion":"",
"priority":100,
"inRepository":true,
"lastUpdated":"2008-05-21 19:15:00"
}
function detectWeb(doc, url) {
if (url.match(/article\/view/)) {
return "journalArticle";
} else if (url.match(/(issue|advancedResults)/)) {
return "multiple";
}
}
function | (link) {
if (link.match(/\d+\/\d+$/)) {
var nos = link.match(/\d+\/\d+$/)[0];
} else {
var nos = link.match(/\d+$/)[0] + '/0';
}
return 'http://jv.gilead.org.il/studies/index.php/studies/rt/captureCite/' + nos + '/RefManCitationPlugin';
}
function doWeb(doc, url) {
var n = doc.documentElement.namespaceURI;
var ns = n ? function(prefix) {
if (prefix == 'x') return n; else return null;
} : null;
var arts = new Array();
if (detectWeb(doc, url) == "multiple") {
var items = new Object();
var xpath = '//tr[td/a[2]]';
if (url.match(/issue/)) {
var titlex = './td[1]';
var linkx = './td[2]/a[contains(text(), "HTML")]';
} else if (url.match(/advanced/)) {
var titlex = './td[2]';
var linkx = './td[3]/a[contains(text(), "HTML")]';
}
var results = doc.evaluate(xpath, doc, ns, XPathResult.ANY_TYPE, null);
var result;
while (result = results.iterateNext()) {
var title = Zotero.Utilities.trimInternal(doc.evaluate(titlex, result, ns, XPathResult.ANY_TYPE, null).iterateNext().textContent);
var link = doc.evaluate(linkx, result, ns, XPathResult.ANY_TYPE, null).iterateNext().href;
items[link] = title;
}
items = Zotero.selectItems(items);
for (var i in items) {
arts.push(prepNos(i));
}
} else {
arts = [prepNos(url)];
}
Zotero.Utilities.HTTP.doGet(arts, function(text) {
var translator = Zotero.loadTranslator("import");
translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
translator.setString(text);
translator.setHandler("itemDone", function(obj, item) {
var auts = new Array();
for each (var aut in item.creators) {
auts.push(Zotero.Utilities.cleanAuthor(aut.lastName, "author"));
}
item.creators = auts;
item.attachments = [{url:item.url, title:"Verniana Snapshot", mimeType:"text/html"}];
var bits = item.publicationTitle.split(/;/);
item.publicationTitle = bits[0];
var voliss = bits[1].match(/Vol\s+(\d+)\s+\((\d+)\)/);
item.volume = voliss[1];
item.date = voliss[2];
item.complete();
});
translator.translate();
});
Zotero.wait();
} | prepNos | identifier_name |
misc.py | from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
# to avoid out of memory
def argsort(x):
xp = cuda.get_array_module(x)
i = np.argsort(cuda.to_cpu(x))
if xp is np:
return i
else:
return cuda.to_gpu(i)
# to avoid out of memory
def choice(x, size):
xp = cuda.get_array_module(x) | else:
return cuda.to_gpu(y)
def scale_img(img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale | y = np.random.choice(cuda.to_cpu(x), size, replace=False)
if xp is np:
return y | random_line_split |
misc.py | from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
# to avoid out of memory
def argsort(x):
xp = cuda.get_array_module(x)
i = np.argsort(cuda.to_cpu(x))
if xp is np:
return i
else:
|
# to avoid out of memory
def choice(x, size):
xp = cuda.get_array_module(x)
y = np.random.choice(cuda.to_cpu(x), size, replace=False)
if xp is np:
return y
else:
return cuda.to_gpu(y)
def scale_img(img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale
| return cuda.to_gpu(i) | conditional_block |
misc.py | from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
|
# to avoid out of memory
def argsort(x):
xp = cuda.get_array_module(x)
i = np.argsort(cuda.to_cpu(x))
if xp is np:
return i
else:
return cuda.to_gpu(i)
# to avoid out of memory
def choice(x, size):
xp = cuda.get_array_module(x)
y = np.random.choice(cuda.to_cpu(x), size, replace=False)
if xp is np:
return y
else:
return cuda.to_gpu(y)
def scale_img(img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale
| return F.huber_loss(x, t, beta, reduce='no') / beta | identifier_body |
misc.py | from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
# to avoid out of memory
def argsort(x):
xp = cuda.get_array_module(x)
i = np.argsort(cuda.to_cpu(x))
if xp is np:
return i
else:
return cuda.to_gpu(i)
# to avoid out of memory
def choice(x, size):
xp = cuda.get_array_module(x)
y = np.random.choice(cuda.to_cpu(x), size, replace=False)
if xp is np:
return y
else:
return cuda.to_gpu(y)
def | (img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale
| scale_img | identifier_name |
order-details.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { OrderService } from "../../Services/order.service";
@Component({
selector: 'page-order-details',
templateUrl: 'order-details.html',
})
export class OrderDetailsPage {
OrderService: any;
idorder;
ordertime;
deliverytime;
totalPrice;
totalprice;
constructor(public orderService:OrderService,public navCtrl: NavController, public navParams: NavParams) {
this.idorder = navParams.get("idorder");
this.ordertime = navParams.get("ordertime");
this.deliverytime = navParams.get("deliverytime");
this.totalprice = navParams.get("totalprice");
this.listorderdetails();
}
ionViewDidLoad() {
// console.log('ionViewDidLoad OrderDetailsPage');
// console.log("shimaa "+this.Orderdetails);
// console.log("aya"+this.orderdetails);
}
backBtn() {
this.navCtrl.pop();
}
| this.orderService.getorderdetails(this.idorder).subscribe(data => {
console.log("hiii "+JSON.stringify(data));
this.orderdetails=data
},
(err) => console.log(`errror ${err}`)
)
}
get Orderdetails(){
return this.orderdetails;
}
} | orderdetails:any=[];
listorderdetails(){ | random_line_split |
order-details.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { OrderService } from "../../Services/order.service";
@Component({
selector: 'page-order-details',
templateUrl: 'order-details.html',
})
export class OrderDetailsPage {
OrderService: any;
idorder;
ordertime;
deliverytime;
totalPrice;
totalprice;
| (public orderService:OrderService,public navCtrl: NavController, public navParams: NavParams) {
this.idorder = navParams.get("idorder");
this.ordertime = navParams.get("ordertime");
this.deliverytime = navParams.get("deliverytime");
this.totalprice = navParams.get("totalprice");
this.listorderdetails();
}
ionViewDidLoad() {
// console.log('ionViewDidLoad OrderDetailsPage');
// console.log("shimaa "+this.Orderdetails);
// console.log("aya"+this.orderdetails);
}
backBtn() {
this.navCtrl.pop();
}
orderdetails:any=[];
listorderdetails(){
this.orderService.getorderdetails(this.idorder).subscribe(data => {
console.log("hiii "+JSON.stringify(data));
this.orderdetails=data
},
(err) => console.log(`errror ${err}`)
)
}
get Orderdetails(){
return this.orderdetails;
}
}
| constructor | identifier_name |
order-details.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { OrderService } from "../../Services/order.service";
@Component({
selector: 'page-order-details',
templateUrl: 'order-details.html',
})
export class OrderDetailsPage {
OrderService: any;
idorder;
ordertime;
deliverytime;
totalPrice;
totalprice;
constructor(public orderService:OrderService,public navCtrl: NavController, public navParams: NavParams) |
ionViewDidLoad() {
// console.log('ionViewDidLoad OrderDetailsPage');
// console.log("shimaa "+this.Orderdetails);
// console.log("aya"+this.orderdetails);
}
backBtn() {
this.navCtrl.pop();
}
orderdetails:any=[];
listorderdetails(){
this.orderService.getorderdetails(this.idorder).subscribe(data => {
console.log("hiii "+JSON.stringify(data));
this.orderdetails=data
},
(err) => console.log(`errror ${err}`)
)
}
get Orderdetails(){
return this.orderdetails;
}
}
| {
this.idorder = navParams.get("idorder");
this.ordertime = navParams.get("ordertime");
this.deliverytime = navParams.get("deliverytime");
this.totalprice = navParams.get("totalprice");
this.listorderdetails();
} | identifier_body |
regions-static-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct closure_box<'a> {
cl: 'a ||,
}
fn box_it<'r>(x: 'r ||) -> closure_box<'r> {
closure_box {cl: x}
}
fn call_static_closure(cl: closure_box<'static>) {
(cl.cl)();
}
pub fn main() {
let cl_box = box_it(|| println!("Hello, world!"));
call_static_closure(cl_box);
} | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
regions-static-closure.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct closure_box<'a> {
cl: 'a ||,
}
fn box_it<'r>(x: 'r ||) -> closure_box<'r> {
closure_box {cl: x}
}
fn call_static_closure(cl: closure_box<'static>) {
(cl.cl)();
}
pub fn | () {
let cl_box = box_it(|| println!("Hello, world!"));
call_static_closure(cl_box);
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.