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
RootItem.js
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss'; import ChildItem from './ChildItem'; /** * This React component expect the following input properties: * - model: * Expect a LokkupTable instance that you want to render and edit. * - item: * Root of the tree * - layer: * Layer id. */ export default class CompositePipelineWidgetRootItem extends React.Component { constructor(props) { super(props); this.state = { dropDown: false, }; // Bind callback this.toggleVisibility = this.toggleVisibility.bind(this); this.toggleDropDown = this.toggleDropDown.bind(this); this.updateColorBy = this.updateColorBy.bind(this); this.toggleEditMode = this.toggleEditMode.bind(this); this.updateOpacity = this.updateOpacity.bind(this); } toggleVisibility() { this.props.model.toggleLayerVisible(this.props.layer); } toggleDropDown()
updateColorBy(event) { this.props.model.setActiveColor( this.props.layer, event.target.dataset.color ); this.toggleDropDown(); } toggleEditMode() { this.props.model.toggleEditMode(this.props.layer); } updateOpacity(e) { this.props.model.setOpacity(this.props.layer, e.target.value); this.forceUpdate(); } render() { const model = this.props.model; const layer = this.props.layer; const visible = model.isLayerVisible(this.props.layer); const children = this.props.item.children || []; const inEditMode = this.props.model.isLayerInEditMode(this.props.layer); const hasChildren = children.length > 0; const hasOpacity = model.hasOpacity(); const hasDropDown = this.props.model.getColor(this.props.layer).length > 1; const editButton = hasChildren ? ( <i className={inEditMode ? style.editButtonOn : style.editButtonOff} onClick={this.toggleEditMode} /> ) : ( '' ); return ( <div className={style.section}> <div className={style.item}> <div className={style.label}>{this.props.item.name}</div> <div className={style.actions}> {editButton} <i className={ visible ? style.visibleButtonOn : style.visibleButtonOff } onClick={this.toggleVisibility} /> <i className={ hasDropDown ? style.dropDownButtonOn : style.dropDownButtonOff } onClick={this.toggleDropDown} /> <div onClick={this.updateColorBy} className={this.state.dropDown ? style.menu : style.hidden} > {model.getColor(layer).map((color) => ( <div key={color} data-color={color} className={ model.isActiveColor(layer, color) ? style.selectedMenuItem : style.menuItem } > {model.getColorToLabel(color)} </div> ))} </div> </div> </div> <div className={hasOpacity && !hasChildren ? style.item : style.hidden}> <input className={style.opacity} type="range" min="0" max="100" value={model.getOpacity(layer)} onChange={this.updateOpacity} /> </div> <div className={style.children}> {children.map((item, idx) => ( <ChildItem key={idx} item={item} layer={item.ids.join('')} model={model} /> ))} </div> </div> ); } } CompositePipelineWidgetRootItem.propTypes = { item: PropTypes.object, layer: PropTypes.string, model: PropTypes.object, }; CompositePipelineWidgetRootItem.defaultProps = { item: undefined, layer: undefined, model: undefined, };
{ if (this.props.model.getColor(this.props.layer).length > 1) { this.setState({ dropDown: !this.state.dropDown, }); } }
identifier_body
svh-a-change-type-arg.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. //! The `svh-a-*.rs` files are all deviations from the base file //! svh-a-base.rs with some difference (usually in `fn foo`) that //! should not affect the strict version hash (SVH) computation //! (#14132). #![crate_name = "a"] use std::marker::MarkerTrait; macro_rules! three { () => { 3 } } pub trait U : MarkerTrait {} pub trait V : MarkerTrait {} impl U for () {} impl V for () {} static A_CONSTANT : int = 2; pub fn foo<T:U>(_: i32) -> int { 3 } pub fn an_unused_name() -> int {
4 }
random_line_split
svh-a-change-type-arg.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. //! The `svh-a-*.rs` files are all deviations from the base file //! svh-a-base.rs with some difference (usually in `fn foo`) that //! should not affect the strict version hash (SVH) computation //! (#14132). #![crate_name = "a"] use std::marker::MarkerTrait; macro_rules! three { () => { 3 } } pub trait U : MarkerTrait {} pub trait V : MarkerTrait {} impl U for () {} impl V for () {} static A_CONSTANT : int = 2; pub fn foo<T:U>(_: i32) -> int { 3 } pub fn an_unused_name() -> int
{ 4 }
identifier_body
svh-a-change-type-arg.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. //! The `svh-a-*.rs` files are all deviations from the base file //! svh-a-base.rs with some difference (usually in `fn foo`) that //! should not affect the strict version hash (SVH) computation //! (#14132). #![crate_name = "a"] use std::marker::MarkerTrait; macro_rules! three { () => { 3 } } pub trait U : MarkerTrait {} pub trait V : MarkerTrait {} impl U for () {} impl V for () {} static A_CONSTANT : int = 2; pub fn
<T:U>(_: i32) -> int { 3 } pub fn an_unused_name() -> int { 4 }
foo
identifier_name
radec-conv.py
#!/usr/bin/env python import sys, math if len(sys.argv) != 3:
ra = sys.argv[1] dec = sys.argv[2] rai = ra.split(":") deci = dec.split(":") radeg = float(rai[0]) * 15.0 + float(rai[1]) * (1.0 / 60.0) + float(rai[2]) * (1.0 / 3600) decdeg = float(deci[0]) + float(deci[1]) * (1.0 / 60.0) + float(deci[2]) * (1.0 / 3600.0) print("RA,DEC: %f,%f deg" % (radeg, decdeg))
print("Usage:") print("%s [RA HH:MM:SS] [DEC Deg:Arcmin:Arcsec] " % sys.argv[0]) exit(0)
conditional_block
radec-conv.py
#!/usr/bin/env python import sys, math
print("%s [RA HH:MM:SS] [DEC Deg:Arcmin:Arcsec] " % sys.argv[0]) exit(0) ra = sys.argv[1] dec = sys.argv[2] rai = ra.split(":") deci = dec.split(":") radeg = float(rai[0]) * 15.0 + float(rai[1]) * (1.0 / 60.0) + float(rai[2]) * (1.0 / 3600) decdeg = float(deci[0]) + float(deci[1]) * (1.0 / 60.0) + float(deci[2]) * (1.0 / 3600.0) print("RA,DEC: %f,%f deg" % (radeg, decdeg))
if len(sys.argv) != 3: print("Usage:")
random_line_split
PositionalAudio.js
/** * @author mrdoob / http://mrdoob.com/ */ import { Vector3 } from '../math/Vector3.js'; import { Quaternion } from '../math/Quaternion.js'; import { Audio } from './Audio.js'; import { Object3D } from '../core/Object3D.js'; const _position = new Vector3(); const _quaternion = new Quaternion(); const _scale = new Vector3(); const _orientation = new Vector3(); function PositionalAudio( listener ) { Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.panningModel = 'HRTF'; this.panner.connect( this.gain ); } PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { constructor: PositionalAudio, getOutput: function () { return this.panner; }, getRefDistance: function () { return this.panner.refDistance; }, setRefDistance: function ( value ) { this.panner.refDistance = value; return this; }, getRolloffFactor: function () { return this.panner.rolloffFactor; },
return this; }, getDistanceModel: function () { return this.panner.distanceModel; }, setDistanceModel: function ( value ) { this.panner.distanceModel = value; return this; }, getMaxDistance: function () { return this.panner.maxDistance; }, setMaxDistance: function ( value ) { this.panner.maxDistance = value; return this; }, setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { this.panner.coneInnerAngle = coneInnerAngle; this.panner.coneOuterAngle = coneOuterAngle; this.panner.coneOuterGain = coneOuterGain; return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; this.matrixWorld.decompose( _position, _quaternion, _scale ); _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); const panner = this.panner; if ( panner.positionX ) { // code path for Chrome and Firefox (see #14393) const endTime = this.context.currentTime + this.listener.timeDelta; panner.positionX.linearRampToValueAtTime( _position.x, endTime ); panner.positionY.linearRampToValueAtTime( _position.y, endTime ); panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); } else { panner.setPosition( _position.x, _position.y, _position.z ); panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); } } } ); export { PositionalAudio };
setRolloffFactor: function ( value ) { this.panner.rolloffFactor = value;
random_line_split
PositionalAudio.js
/** * @author mrdoob / http://mrdoob.com/ */ import { Vector3 } from '../math/Vector3.js'; import { Quaternion } from '../math/Quaternion.js'; import { Audio } from './Audio.js'; import { Object3D } from '../core/Object3D.js'; const _position = new Vector3(); const _quaternion = new Quaternion(); const _scale = new Vector3(); const _orientation = new Vector3(); function PositionalAudio( listener )
PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { constructor: PositionalAudio, getOutput: function () { return this.panner; }, getRefDistance: function () { return this.panner.refDistance; }, setRefDistance: function ( value ) { this.panner.refDistance = value; return this; }, getRolloffFactor: function () { return this.panner.rolloffFactor; }, setRolloffFactor: function ( value ) { this.panner.rolloffFactor = value; return this; }, getDistanceModel: function () { return this.panner.distanceModel; }, setDistanceModel: function ( value ) { this.panner.distanceModel = value; return this; }, getMaxDistance: function () { return this.panner.maxDistance; }, setMaxDistance: function ( value ) { this.panner.maxDistance = value; return this; }, setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { this.panner.coneInnerAngle = coneInnerAngle; this.panner.coneOuterAngle = coneOuterAngle; this.panner.coneOuterGain = coneOuterGain; return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; this.matrixWorld.decompose( _position, _quaternion, _scale ); _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); const panner = this.panner; if ( panner.positionX ) { // code path for Chrome and Firefox (see #14393) const endTime = this.context.currentTime + this.listener.timeDelta; panner.positionX.linearRampToValueAtTime( _position.x, endTime ); panner.positionY.linearRampToValueAtTime( _position.y, endTime ); panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); } else { panner.setPosition( _position.x, _position.y, _position.z ); panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); } } } ); export { PositionalAudio };
{ Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.panningModel = 'HRTF'; this.panner.connect( this.gain ); }
identifier_body
PositionalAudio.js
/** * @author mrdoob / http://mrdoob.com/ */ import { Vector3 } from '../math/Vector3.js'; import { Quaternion } from '../math/Quaternion.js'; import { Audio } from './Audio.js'; import { Object3D } from '../core/Object3D.js'; const _position = new Vector3(); const _quaternion = new Quaternion(); const _scale = new Vector3(); const _orientation = new Vector3(); function
( listener ) { Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.panningModel = 'HRTF'; this.panner.connect( this.gain ); } PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { constructor: PositionalAudio, getOutput: function () { return this.panner; }, getRefDistance: function () { return this.panner.refDistance; }, setRefDistance: function ( value ) { this.panner.refDistance = value; return this; }, getRolloffFactor: function () { return this.panner.rolloffFactor; }, setRolloffFactor: function ( value ) { this.panner.rolloffFactor = value; return this; }, getDistanceModel: function () { return this.panner.distanceModel; }, setDistanceModel: function ( value ) { this.panner.distanceModel = value; return this; }, getMaxDistance: function () { return this.panner.maxDistance; }, setMaxDistance: function ( value ) { this.panner.maxDistance = value; return this; }, setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { this.panner.coneInnerAngle = coneInnerAngle; this.panner.coneOuterAngle = coneOuterAngle; this.panner.coneOuterGain = coneOuterGain; return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; this.matrixWorld.decompose( _position, _quaternion, _scale ); _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); const panner = this.panner; if ( panner.positionX ) { // code path for Chrome and Firefox (see #14393) const endTime = this.context.currentTime + this.listener.timeDelta; panner.positionX.linearRampToValueAtTime( _position.x, endTime ); panner.positionY.linearRampToValueAtTime( _position.y, endTime ); panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); } else { panner.setPosition( _position.x, _position.y, _position.z ); panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); } } } ); export { PositionalAudio };
PositionalAudio
identifier_name
PositionalAudio.js
/** * @author mrdoob / http://mrdoob.com/ */ import { Vector3 } from '../math/Vector3.js'; import { Quaternion } from '../math/Quaternion.js'; import { Audio } from './Audio.js'; import { Object3D } from '../core/Object3D.js'; const _position = new Vector3(); const _quaternion = new Quaternion(); const _scale = new Vector3(); const _orientation = new Vector3(); function PositionalAudio( listener ) { Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.panningModel = 'HRTF'; this.panner.connect( this.gain ); } PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { constructor: PositionalAudio, getOutput: function () { return this.panner; }, getRefDistance: function () { return this.panner.refDistance; }, setRefDistance: function ( value ) { this.panner.refDistance = value; return this; }, getRolloffFactor: function () { return this.panner.rolloffFactor; }, setRolloffFactor: function ( value ) { this.panner.rolloffFactor = value; return this; }, getDistanceModel: function () { return this.panner.distanceModel; }, setDistanceModel: function ( value ) { this.panner.distanceModel = value; return this; }, getMaxDistance: function () { return this.panner.maxDistance; }, setMaxDistance: function ( value ) { this.panner.maxDistance = value; return this; }, setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { this.panner.coneInnerAngle = coneInnerAngle; this.panner.coneOuterAngle = coneOuterAngle; this.panner.coneOuterGain = coneOuterGain; return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; this.matrixWorld.decompose( _position, _quaternion, _scale ); _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion ); const panner = this.panner; if ( panner.positionX )
else { panner.setPosition( _position.x, _position.y, _position.z ); panner.setOrientation( _orientation.x, _orientation.y, _orientation.z ); } } } ); export { PositionalAudio };
{ // code path for Chrome and Firefox (see #14393) const endTime = this.context.currentTime + this.listener.timeDelta; panner.positionX.linearRampToValueAtTime( _position.x, endTime ); panner.positionY.linearRampToValueAtTime( _position.y, endTime ); panner.positionZ.linearRampToValueAtTime( _position.z, endTime ); panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime ); panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime ); panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime ); }
conditional_block
test_Read.py
#!/usr/bin/python """test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/) Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) 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. """ from nose.tools import raises from Read import Read from MetageneError import MetageneError ##TODO: test set_sam_tag method ##TODO: test set_chromosome_sizes cigar_string = {} bad_cigar_string = {} bitwise_flag = {} bad_bitwise_flag = {} good_input = {} bad_input = {} chromosome_conversion = {"1": "chr1", "2": "chr2"} def setup(): """Create fixtures""" # define cigar strings; value: ((args for build_positions), expected_result) cigar_string['full_match'] = ((1, "10M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['insertion'] = ((1, "5M4I5M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['deletion'] = ((1, "5M4D5M", "*"), [1, 2, 3, 4, 5, 10, 11, 12, 13, 14]) cigar_string['gapped_match'] = ((1, "5M3N5M", "*"), [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]) cigar_string['softclipped_match'] = ((4, "3S5M", "*"), [4, 5, 6, 7, 8]) cigar_string['hardclipped_match'] = ((4, "3H5M3H", "*"), [4, 5, 6, 7, 8]) cigar_string['padded_match'] = ((1, "3P5M", "*"), [4, 5, 6, 7, 8]) cigar_string['mismatch'] = ((1, "5=1X3=", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9]) cigar_string['no_cigar_match'] = ((1, "*", "aaaaa"), [1, 2, 3, 4, 5]) bad_cigar_string['unknown_length'] = ((1, "*", "*"), "raise MetageneError") bad_cigar_string['illegal_cigar'] = ((1, "5M4B", "*"), "raise MetageneError") bad_cigar_string['misordered_cigar'] = ((1, "M5N4M5", "*"), "raise MetageneError") # define bitwise flags; value: ((args for parse_sam_bitwise_flag), expected_result(count?, reverse_complemented?)) bitwise_flag['unmapped'] = ((int("0b000000000100", 2),), (False, False)) bitwise_flag['unmapped_withflags'] = ((int("0b100111011101", 2),), (False, True)) bitwise_flag['plus_strand'] = ((int("0b000000000000", 2),), (True, False)) bitwise_flag['minus_strand'] = ((int("0b000000010000", 2),), (True, True)) bitwise_flag['multiple_segments'] = ((int("0b000000000001", 2),), (True, False)) # try various default and user-changed boolean flags bitwise_flag['count_secondary_alignment'] = ((int("0b000100000000", 2),), (True, False)) bitwise_flag['skip_secondary_alignment'] = ( (int("0b000100000000", 2), False, False, False, True, False, False), (False, False)) bitwise_flag['skip_failed_quality_control'] = ((int("0b001000000000", 2),), (False, False)) bitwise_flag['count_failed_quality_control'] = ( (int("0b001000000000", 2), True, True, False, True, False, False), (True, False)) bitwise_flag['skip_PCR_optical_duplicate'] = ((int("0b010000000000", 2),), (False, False)) bitwise_flag['count_PCR_optical_duplicate'] = ( (int("0b010000000000", 2), True, False, True, True, False, False), (True, False)) bitwise_flag['count_supplementary_alignment'] = ((int("0b100000000000", 2),), (True, False)) bitwise_flag['skip_supplementary_alignment'] = ( (int("0b100000000000", 2), True, False, False, False, False, False), (False, False)) bitwise_flag['count_only_start_success'] = ( (int("0b000001000001", 2), True, False, False, True, True, False), (True, False)) bitwise_flag['count_only_start_fail'] = ( (int("0b000000000001", 2), True, False, False, True, True, False), (False, False)) bitwise_flag['count_only_end_success'] = ( (int("0b000010000001", 2), True, False, False, True, False, True), (True, False)) bitwise_flag['count_only_end_fail'] = ( (int("0b000000000001", 2), True, False, False, True, False, True), (False, False)) bad_bitwise_flag['count_only_both'] = ( (int("0b000011000001", 2), True, False, False, True, True, True), ("Raise MetageneError",)) # define good and bad samline inputs good_input['no_tags'] = (0, "chr1", 200, "10M", 10, 1, 1, "+") good_input['plus_strand_match'] = (0, "chr1", 200, "10M", 10, 2, 4, "+") good_input['minus_strand_match'] = (16, "chr1", 200, "10M", 10, 2, 4, "-") good_input['no_match'] = (4, "*", 0, "*", 10, 1, 1, ".") sample = ["NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4"] Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NA:i:(\d+)') Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NH:i:(\d+)') def test_build_positions(): for test in cigar_string: yield (check_build_positions, test, cigar_string[test]) def check_build_positions(test, (values, expected)): position_array = Read.build_positions(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(position_array) assert position_array == expected, "{}Error: \tDid not create the expected position array.".format( test_description) def test_catch_bad_cigar_input(): for test in bad_cigar_string: yield (check_catch_bad_cigar_input, test, bad_cigar_string[test]) @raises(MetageneError) def check_catch_bad_cigar_input(test, (values, expected)): print Read.build_positions(*values) def test_parse_sam_bitwise_flag():
def check_parse_sam_bitwise_flag(test, (values, expected)): bitwise_result = Read.parse_sam_bitwise_flag(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(bitwise_result) assert bitwise_result == expected, "{}Error: \tDid not parse bitwise flag as expected.".format(test_description) def test_catch_bad_bitwise_input(): for test in bad_bitwise_flag: yield (check_catch_bad_bitwise_input, test, bad_bitwise_flag[test]) @raises(MetageneError) def check_catch_bad_bitwise_input(test, (values, expected)): print Read.parse_sam_bitwise_flag(*values) def build_samline(bitcode, chromosome, start, cigar, length, abundance, mappings): """Return a SAM format line""" string = "a" * length return "read\t{}\t{}\t{}\t255\t{}\t*\t0\t0\t{}\t{}\tNH:i:{}\tNA:i:{}".format( bitcode, chromosome, start, cigar, string, string, mappings, abundance) def test_create_read(): for test in good_input: yield (check_create_read, test, good_input[test]) def check_create_read(test, values): # create expected result if int(values[0]) == 4: expected = "Non-aligning read" else: start = int(values[2]) end = int(values[2]) + int(values[4]) - 1 if values[7] == "-": start = end end = int(values[2]) expected = "Read at {0}:{1}-{2} on {3} strand; counts for {4:2.3f}:".format( values[1], # chromosome start, end, values[7], # strand float(values[5]) / float(values[6])) # abundance / mappings # build input to test samline = build_samline(*values[0:-1]) # exclude final value (created, read) = Read.create_from_sam(samline, chromosome_conversion.values(), count_method='all') output = str(read).split("\t")[0] # create description in case test fails test_description = "\nTest: \t{}\n".format(test) test_description += "Abundance:\t{}\n".format(Read.has_sam_tag["NA"]) test_description += "Mappings:\t{}\n".format(Read.has_sam_tag["NH"]) test_description += "Sam Line:\t{}\n".format(samline) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(output) assert output == expected, "{}Error: \tDid not create expected read.".format(test_description) def test_catch_bad_input(): for test in bad_input: yield (check_catch_bad_input, test, bad_input[test]) @raises(MetageneError) def check_catch_bad_input(test, samline): print Read(sam_line)
for test in bitwise_flag: yield (check_parse_sam_bitwise_flag, test, bitwise_flag[test])
identifier_body
test_Read.py
#!/usr/bin/python """test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/) Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) 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. """ from nose.tools import raises from Read import Read from MetageneError import MetageneError ##TODO: test set_sam_tag method ##TODO: test set_chromosome_sizes cigar_string = {} bad_cigar_string = {} bitwise_flag = {} bad_bitwise_flag = {} good_input = {} bad_input = {} chromosome_conversion = {"1": "chr1", "2": "chr2"} def setup(): """Create fixtures""" # define cigar strings; value: ((args for build_positions), expected_result) cigar_string['full_match'] = ((1, "10M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['insertion'] = ((1, "5M4I5M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['deletion'] = ((1, "5M4D5M", "*"), [1, 2, 3, 4, 5, 10, 11, 12, 13, 14]) cigar_string['gapped_match'] = ((1, "5M3N5M", "*"), [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]) cigar_string['softclipped_match'] = ((4, "3S5M", "*"), [4, 5, 6, 7, 8]) cigar_string['hardclipped_match'] = ((4, "3H5M3H", "*"), [4, 5, 6, 7, 8]) cigar_string['padded_match'] = ((1, "3P5M", "*"), [4, 5, 6, 7, 8]) cigar_string['mismatch'] = ((1, "5=1X3=", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9]) cigar_string['no_cigar_match'] = ((1, "*", "aaaaa"), [1, 2, 3, 4, 5]) bad_cigar_string['unknown_length'] = ((1, "*", "*"), "raise MetageneError") bad_cigar_string['illegal_cigar'] = ((1, "5M4B", "*"), "raise MetageneError") bad_cigar_string['misordered_cigar'] = ((1, "M5N4M5", "*"), "raise MetageneError") # define bitwise flags; value: ((args for parse_sam_bitwise_flag), expected_result(count?, reverse_complemented?)) bitwise_flag['unmapped'] = ((int("0b000000000100", 2),), (False, False)) bitwise_flag['unmapped_withflags'] = ((int("0b100111011101", 2),), (False, True)) bitwise_flag['plus_strand'] = ((int("0b000000000000", 2),), (True, False)) bitwise_flag['minus_strand'] = ((int("0b000000010000", 2),), (True, True)) bitwise_flag['multiple_segments'] = ((int("0b000000000001", 2),), (True, False)) # try various default and user-changed boolean flags bitwise_flag['count_secondary_alignment'] = ((int("0b000100000000", 2),), (True, False)) bitwise_flag['skip_secondary_alignment'] = ( (int("0b000100000000", 2), False, False, False, True, False, False), (False, False)) bitwise_flag['skip_failed_quality_control'] = ((int("0b001000000000", 2),), (False, False)) bitwise_flag['count_failed_quality_control'] = ( (int("0b001000000000", 2), True, True, False, True, False, False), (True, False)) bitwise_flag['skip_PCR_optical_duplicate'] = ((int("0b010000000000", 2),), (False, False)) bitwise_flag['count_PCR_optical_duplicate'] = ( (int("0b010000000000", 2), True, False, True, True, False, False), (True, False)) bitwise_flag['count_supplementary_alignment'] = ((int("0b100000000000", 2),), (True, False)) bitwise_flag['skip_supplementary_alignment'] = ( (int("0b100000000000", 2), True, False, False, False, False, False), (False, False)) bitwise_flag['count_only_start_success'] = ( (int("0b000001000001", 2), True, False, False, True, True, False), (True, False)) bitwise_flag['count_only_start_fail'] = ( (int("0b000000000001", 2), True, False, False, True, True, False), (False, False)) bitwise_flag['count_only_end_success'] = ( (int("0b000010000001", 2), True, False, False, True, False, True), (True, False)) bitwise_flag['count_only_end_fail'] = ( (int("0b000000000001", 2), True, False, False, True, False, True), (False, False)) bad_bitwise_flag['count_only_both'] = ( (int("0b000011000001", 2), True, False, False, True, True, True), ("Raise MetageneError",)) # define good and bad samline inputs good_input['no_tags'] = (0, "chr1", 200, "10M", 10, 1, 1, "+") good_input['plus_strand_match'] = (0, "chr1", 200, "10M", 10, 2, 4, "+") good_input['minus_strand_match'] = (16, "chr1", 200, "10M", 10, 2, 4, "-") good_input['no_match'] = (4, "*", 0, "*", 10, 1, 1, ".") sample = ["NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4"] Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NA:i:(\d+)') Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NH:i:(\d+)') def test_build_positions(): for test in cigar_string: yield (check_build_positions, test, cigar_string[test]) def check_build_positions(test, (values, expected)): position_array = Read.build_positions(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(position_array) assert position_array == expected, "{}Error: \tDid not create the expected position array.".format( test_description) def test_catch_bad_cigar_input(): for test in bad_cigar_string: yield (check_catch_bad_cigar_input, test, bad_cigar_string[test]) @raises(MetageneError) def check_catch_bad_cigar_input(test, (values, expected)): print Read.build_positions(*values) def test_parse_sam_bitwise_flag(): for test in bitwise_flag: yield (check_parse_sam_bitwise_flag, test, bitwise_flag[test]) def check_parse_sam_bitwise_flag(test, (values, expected)): bitwise_result = Read.parse_sam_bitwise_flag(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(bitwise_result) assert bitwise_result == expected, "{}Error: \tDid not parse bitwise flag as expected.".format(test_description) def test_catch_bad_bitwise_input(): for test in bad_bitwise_flag:
@raises(MetageneError) def check_catch_bad_bitwise_input(test, (values, expected)): print Read.parse_sam_bitwise_flag(*values) def build_samline(bitcode, chromosome, start, cigar, length, abundance, mappings): """Return a SAM format line""" string = "a" * length return "read\t{}\t{}\t{}\t255\t{}\t*\t0\t0\t{}\t{}\tNH:i:{}\tNA:i:{}".format( bitcode, chromosome, start, cigar, string, string, mappings, abundance) def test_create_read(): for test in good_input: yield (check_create_read, test, good_input[test]) def check_create_read(test, values): # create expected result if int(values[0]) == 4: expected = "Non-aligning read" else: start = int(values[2]) end = int(values[2]) + int(values[4]) - 1 if values[7] == "-": start = end end = int(values[2]) expected = "Read at {0}:{1}-{2} on {3} strand; counts for {4:2.3f}:".format( values[1], # chromosome start, end, values[7], # strand float(values[5]) / float(values[6])) # abundance / mappings # build input to test samline = build_samline(*values[0:-1]) # exclude final value (created, read) = Read.create_from_sam(samline, chromosome_conversion.values(), count_method='all') output = str(read).split("\t")[0] # create description in case test fails test_description = "\nTest: \t{}\n".format(test) test_description += "Abundance:\t{}\n".format(Read.has_sam_tag["NA"]) test_description += "Mappings:\t{}\n".format(Read.has_sam_tag["NH"]) test_description += "Sam Line:\t{}\n".format(samline) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(output) assert output == expected, "{}Error: \tDid not create expected read.".format(test_description) def test_catch_bad_input(): for test in bad_input: yield (check_catch_bad_input, test, bad_input[test]) @raises(MetageneError) def check_catch_bad_input(test, samline): print Read(sam_line)
yield (check_catch_bad_bitwise_input, test, bad_bitwise_flag[test])
conditional_block
test_Read.py
#!/usr/bin/python
Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) 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. """ from nose.tools import raises from Read import Read from MetageneError import MetageneError ##TODO: test set_sam_tag method ##TODO: test set_chromosome_sizes cigar_string = {} bad_cigar_string = {} bitwise_flag = {} bad_bitwise_flag = {} good_input = {} bad_input = {} chromosome_conversion = {"1": "chr1", "2": "chr2"} def setup(): """Create fixtures""" # define cigar strings; value: ((args for build_positions), expected_result) cigar_string['full_match'] = ((1, "10M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['insertion'] = ((1, "5M4I5M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['deletion'] = ((1, "5M4D5M", "*"), [1, 2, 3, 4, 5, 10, 11, 12, 13, 14]) cigar_string['gapped_match'] = ((1, "5M3N5M", "*"), [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]) cigar_string['softclipped_match'] = ((4, "3S5M", "*"), [4, 5, 6, 7, 8]) cigar_string['hardclipped_match'] = ((4, "3H5M3H", "*"), [4, 5, 6, 7, 8]) cigar_string['padded_match'] = ((1, "3P5M", "*"), [4, 5, 6, 7, 8]) cigar_string['mismatch'] = ((1, "5=1X3=", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9]) cigar_string['no_cigar_match'] = ((1, "*", "aaaaa"), [1, 2, 3, 4, 5]) bad_cigar_string['unknown_length'] = ((1, "*", "*"), "raise MetageneError") bad_cigar_string['illegal_cigar'] = ((1, "5M4B", "*"), "raise MetageneError") bad_cigar_string['misordered_cigar'] = ((1, "M5N4M5", "*"), "raise MetageneError") # define bitwise flags; value: ((args for parse_sam_bitwise_flag), expected_result(count?, reverse_complemented?)) bitwise_flag['unmapped'] = ((int("0b000000000100", 2),), (False, False)) bitwise_flag['unmapped_withflags'] = ((int("0b100111011101", 2),), (False, True)) bitwise_flag['plus_strand'] = ((int("0b000000000000", 2),), (True, False)) bitwise_flag['minus_strand'] = ((int("0b000000010000", 2),), (True, True)) bitwise_flag['multiple_segments'] = ((int("0b000000000001", 2),), (True, False)) # try various default and user-changed boolean flags bitwise_flag['count_secondary_alignment'] = ((int("0b000100000000", 2),), (True, False)) bitwise_flag['skip_secondary_alignment'] = ( (int("0b000100000000", 2), False, False, False, True, False, False), (False, False)) bitwise_flag['skip_failed_quality_control'] = ((int("0b001000000000", 2),), (False, False)) bitwise_flag['count_failed_quality_control'] = ( (int("0b001000000000", 2), True, True, False, True, False, False), (True, False)) bitwise_flag['skip_PCR_optical_duplicate'] = ((int("0b010000000000", 2),), (False, False)) bitwise_flag['count_PCR_optical_duplicate'] = ( (int("0b010000000000", 2), True, False, True, True, False, False), (True, False)) bitwise_flag['count_supplementary_alignment'] = ((int("0b100000000000", 2),), (True, False)) bitwise_flag['skip_supplementary_alignment'] = ( (int("0b100000000000", 2), True, False, False, False, False, False), (False, False)) bitwise_flag['count_only_start_success'] = ( (int("0b000001000001", 2), True, False, False, True, True, False), (True, False)) bitwise_flag['count_only_start_fail'] = ( (int("0b000000000001", 2), True, False, False, True, True, False), (False, False)) bitwise_flag['count_only_end_success'] = ( (int("0b000010000001", 2), True, False, False, True, False, True), (True, False)) bitwise_flag['count_only_end_fail'] = ( (int("0b000000000001", 2), True, False, False, True, False, True), (False, False)) bad_bitwise_flag['count_only_both'] = ( (int("0b000011000001", 2), True, False, False, True, True, True), ("Raise MetageneError",)) # define good and bad samline inputs good_input['no_tags'] = (0, "chr1", 200, "10M", 10, 1, 1, "+") good_input['plus_strand_match'] = (0, "chr1", 200, "10M", 10, 2, 4, "+") good_input['minus_strand_match'] = (16, "chr1", 200, "10M", 10, 2, 4, "-") good_input['no_match'] = (4, "*", 0, "*", 10, 1, 1, ".") sample = ["NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4"] Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NA:i:(\d+)') Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NH:i:(\d+)') def test_build_positions(): for test in cigar_string: yield (check_build_positions, test, cigar_string[test]) def check_build_positions(test, (values, expected)): position_array = Read.build_positions(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(position_array) assert position_array == expected, "{}Error: \tDid not create the expected position array.".format( test_description) def test_catch_bad_cigar_input(): for test in bad_cigar_string: yield (check_catch_bad_cigar_input, test, bad_cigar_string[test]) @raises(MetageneError) def check_catch_bad_cigar_input(test, (values, expected)): print Read.build_positions(*values) def test_parse_sam_bitwise_flag(): for test in bitwise_flag: yield (check_parse_sam_bitwise_flag, test, bitwise_flag[test]) def check_parse_sam_bitwise_flag(test, (values, expected)): bitwise_result = Read.parse_sam_bitwise_flag(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(bitwise_result) assert bitwise_result == expected, "{}Error: \tDid not parse bitwise flag as expected.".format(test_description) def test_catch_bad_bitwise_input(): for test in bad_bitwise_flag: yield (check_catch_bad_bitwise_input, test, bad_bitwise_flag[test]) @raises(MetageneError) def check_catch_bad_bitwise_input(test, (values, expected)): print Read.parse_sam_bitwise_flag(*values) def build_samline(bitcode, chromosome, start, cigar, length, abundance, mappings): """Return a SAM format line""" string = "a" * length return "read\t{}\t{}\t{}\t255\t{}\t*\t0\t0\t{}\t{}\tNH:i:{}\tNA:i:{}".format( bitcode, chromosome, start, cigar, string, string, mappings, abundance) def test_create_read(): for test in good_input: yield (check_create_read, test, good_input[test]) def check_create_read(test, values): # create expected result if int(values[0]) == 4: expected = "Non-aligning read" else: start = int(values[2]) end = int(values[2]) + int(values[4]) - 1 if values[7] == "-": start = end end = int(values[2]) expected = "Read at {0}:{1}-{2} on {3} strand; counts for {4:2.3f}:".format( values[1], # chromosome start, end, values[7], # strand float(values[5]) / float(values[6])) # abundance / mappings # build input to test samline = build_samline(*values[0:-1]) # exclude final value (created, read) = Read.create_from_sam(samline, chromosome_conversion.values(), count_method='all') output = str(read).split("\t")[0] # create description in case test fails test_description = "\nTest: \t{}\n".format(test) test_description += "Abundance:\t{}\n".format(Read.has_sam_tag["NA"]) test_description += "Mappings:\t{}\n".format(Read.has_sam_tag["NH"]) test_description += "Sam Line:\t{}\n".format(samline) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(output) assert output == expected, "{}Error: \tDid not create expected read.".format(test_description) def test_catch_bad_input(): for test in bad_input: yield (check_catch_bad_input, test, bad_input[test]) @raises(MetageneError) def check_catch_bad_input(test, samline): print Read(sam_line)
"""test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/)
random_line_split
test_Read.py
#!/usr/bin/python """test_Read.py to test the Read class. Requires: python 2 (https://www.python.org/downloads/) nose 1.3 (https://nose.readthedocs.org/en/latest/) Joy-El R.B. Talbot Copyright (c) 2014 The MIT License (MIT) 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. """ from nose.tools import raises from Read import Read from MetageneError import MetageneError ##TODO: test set_sam_tag method ##TODO: test set_chromosome_sizes cigar_string = {} bad_cigar_string = {} bitwise_flag = {} bad_bitwise_flag = {} good_input = {} bad_input = {} chromosome_conversion = {"1": "chr1", "2": "chr2"} def setup(): """Create fixtures""" # define cigar strings; value: ((args for build_positions), expected_result) cigar_string['full_match'] = ((1, "10M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['insertion'] = ((1, "5M4I5M", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) cigar_string['deletion'] = ((1, "5M4D5M", "*"), [1, 2, 3, 4, 5, 10, 11, 12, 13, 14]) cigar_string['gapped_match'] = ((1, "5M3N5M", "*"), [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]) cigar_string['softclipped_match'] = ((4, "3S5M", "*"), [4, 5, 6, 7, 8]) cigar_string['hardclipped_match'] = ((4, "3H5M3H", "*"), [4, 5, 6, 7, 8]) cigar_string['padded_match'] = ((1, "3P5M", "*"), [4, 5, 6, 7, 8]) cigar_string['mismatch'] = ((1, "5=1X3=", "*"), [1, 2, 3, 4, 5, 6, 7, 8, 9]) cigar_string['no_cigar_match'] = ((1, "*", "aaaaa"), [1, 2, 3, 4, 5]) bad_cigar_string['unknown_length'] = ((1, "*", "*"), "raise MetageneError") bad_cigar_string['illegal_cigar'] = ((1, "5M4B", "*"), "raise MetageneError") bad_cigar_string['misordered_cigar'] = ((1, "M5N4M5", "*"), "raise MetageneError") # define bitwise flags; value: ((args for parse_sam_bitwise_flag), expected_result(count?, reverse_complemented?)) bitwise_flag['unmapped'] = ((int("0b000000000100", 2),), (False, False)) bitwise_flag['unmapped_withflags'] = ((int("0b100111011101", 2),), (False, True)) bitwise_flag['plus_strand'] = ((int("0b000000000000", 2),), (True, False)) bitwise_flag['minus_strand'] = ((int("0b000000010000", 2),), (True, True)) bitwise_flag['multiple_segments'] = ((int("0b000000000001", 2),), (True, False)) # try various default and user-changed boolean flags bitwise_flag['count_secondary_alignment'] = ((int("0b000100000000", 2),), (True, False)) bitwise_flag['skip_secondary_alignment'] = ( (int("0b000100000000", 2), False, False, False, True, False, False), (False, False)) bitwise_flag['skip_failed_quality_control'] = ((int("0b001000000000", 2),), (False, False)) bitwise_flag['count_failed_quality_control'] = ( (int("0b001000000000", 2), True, True, False, True, False, False), (True, False)) bitwise_flag['skip_PCR_optical_duplicate'] = ((int("0b010000000000", 2),), (False, False)) bitwise_flag['count_PCR_optical_duplicate'] = ( (int("0b010000000000", 2), True, False, True, True, False, False), (True, False)) bitwise_flag['count_supplementary_alignment'] = ((int("0b100000000000", 2),), (True, False)) bitwise_flag['skip_supplementary_alignment'] = ( (int("0b100000000000", 2), True, False, False, False, False, False), (False, False)) bitwise_flag['count_only_start_success'] = ( (int("0b000001000001", 2), True, False, False, True, True, False), (True, False)) bitwise_flag['count_only_start_fail'] = ( (int("0b000000000001", 2), True, False, False, True, True, False), (False, False)) bitwise_flag['count_only_end_success'] = ( (int("0b000010000001", 2), True, False, False, True, False, True), (True, False)) bitwise_flag['count_only_end_fail'] = ( (int("0b000000000001", 2), True, False, False, True, False, True), (False, False)) bad_bitwise_flag['count_only_both'] = ( (int("0b000011000001", 2), True, False, False, True, True, True), ("Raise MetageneError",)) # define good and bad samline inputs good_input['no_tags'] = (0, "chr1", 200, "10M", 10, 1, 1, "+") good_input['plus_strand_match'] = (0, "chr1", 200, "10M", 10, 2, 4, "+") good_input['minus_strand_match'] = (16, "chr1", 200, "10M", 10, 2, 4, "-") good_input['no_match'] = (4, "*", 0, "*", 10, 1, 1, ".") sample = ["NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4", "NA:i:4\tNH:i:4"] Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NA:i:(\d+)') Read.process_set_sam_tag(sample, count_tag=True, tag_regex='NH:i:(\d+)') def test_build_positions(): for test in cigar_string: yield (check_build_positions, test, cigar_string[test]) def check_build_positions(test, (values, expected)): position_array = Read.build_positions(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(position_array) assert position_array == expected, "{}Error: \tDid not create the expected position array.".format( test_description) def test_catch_bad_cigar_input(): for test in bad_cigar_string: yield (check_catch_bad_cigar_input, test, bad_cigar_string[test]) @raises(MetageneError) def check_catch_bad_cigar_input(test, (values, expected)): print Read.build_positions(*values) def test_parse_sam_bitwise_flag(): for test in bitwise_flag: yield (check_parse_sam_bitwise_flag, test, bitwise_flag[test]) def check_parse_sam_bitwise_flag(test, (values, expected)): bitwise_result = Read.parse_sam_bitwise_flag(*values) test_description = "\nTest: \t{}\n".format(test) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(bitwise_result) assert bitwise_result == expected, "{}Error: \tDid not parse bitwise flag as expected.".format(test_description) def test_catch_bad_bitwise_input(): for test in bad_bitwise_flag: yield (check_catch_bad_bitwise_input, test, bad_bitwise_flag[test]) @raises(MetageneError) def check_catch_bad_bitwise_input(test, (values, expected)): print Read.parse_sam_bitwise_flag(*values) def
(bitcode, chromosome, start, cigar, length, abundance, mappings): """Return a SAM format line""" string = "a" * length return "read\t{}\t{}\t{}\t255\t{}\t*\t0\t0\t{}\t{}\tNH:i:{}\tNA:i:{}".format( bitcode, chromosome, start, cigar, string, string, mappings, abundance) def test_create_read(): for test in good_input: yield (check_create_read, test, good_input[test]) def check_create_read(test, values): # create expected result if int(values[0]) == 4: expected = "Non-aligning read" else: start = int(values[2]) end = int(values[2]) + int(values[4]) - 1 if values[7] == "-": start = end end = int(values[2]) expected = "Read at {0}:{1}-{2} on {3} strand; counts for {4:2.3f}:".format( values[1], # chromosome start, end, values[7], # strand float(values[5]) / float(values[6])) # abundance / mappings # build input to test samline = build_samline(*values[0:-1]) # exclude final value (created, read) = Read.create_from_sam(samline, chromosome_conversion.values(), count_method='all') output = str(read).split("\t")[0] # create description in case test fails test_description = "\nTest: \t{}\n".format(test) test_description += "Abundance:\t{}\n".format(Read.has_sam_tag["NA"]) test_description += "Mappings:\t{}\n".format(Read.has_sam_tag["NH"]) test_description += "Sam Line:\t{}\n".format(samline) test_description += "Expected:\t{}\n".format(expected) test_description += "Position:\t{}\n".format(output) assert output == expected, "{}Error: \tDid not create expected read.".format(test_description) def test_catch_bad_input(): for test in bad_input: yield (check_catch_bad_input, test, bad_input[test]) @raises(MetageneError) def check_catch_bad_input(test, samline): print Read(sam_line)
build_samline
identifier_name
bool.py
# 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 https://mozilla.org/MPL/2.0/. from ..._input_field import InputField class BoolInput(InputField): """Simple input that controls a boolean variable. GUI indications ---------------- It can be implemented as a switch or a checkbox, for example. """ _false_strings = ("f", "false") _true_strings = ("t", "true") dtype = bool _type = 'bool' _default = {} def parse(self, val): if val is None: pass elif isinstance(val, str): val = val.lower() if val in self._true_strings: val = True elif val in self._false_strings:
else: raise ValueError(f"String '{val}' is not understood by {self.__class__.__name__}") elif not isinstance(val, bool): self._raise_type_error(val) return val
val = False
conditional_block
bool.py
# 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 https://mozilla.org/MPL/2.0/. from ..._input_field import InputField class BoolInput(InputField): """Simple input that controls a boolean variable. GUI indications ---------------- It can be implemented as a switch or a checkbox, for example. """ _false_strings = ("f", "false") _true_strings = ("t", "true") dtype = bool _type = 'bool' _default = {}
pass elif isinstance(val, str): val = val.lower() if val in self._true_strings: val = True elif val in self._false_strings: val = False else: raise ValueError(f"String '{val}' is not understood by {self.__class__.__name__}") elif not isinstance(val, bool): self._raise_type_error(val) return val
def parse(self, val): if val is None:
random_line_split
bool.py
# 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 https://mozilla.org/MPL/2.0/. from ..._input_field import InputField class
(InputField): """Simple input that controls a boolean variable. GUI indications ---------------- It can be implemented as a switch or a checkbox, for example. """ _false_strings = ("f", "false") _true_strings = ("t", "true") dtype = bool _type = 'bool' _default = {} def parse(self, val): if val is None: pass elif isinstance(val, str): val = val.lower() if val in self._true_strings: val = True elif val in self._false_strings: val = False else: raise ValueError(f"String '{val}' is not understood by {self.__class__.__name__}") elif not isinstance(val, bool): self._raise_type_error(val) return val
BoolInput
identifier_name
bool.py
# 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 https://mozilla.org/MPL/2.0/. from ..._input_field import InputField class BoolInput(InputField):
"""Simple input that controls a boolean variable. GUI indications ---------------- It can be implemented as a switch or a checkbox, for example. """ _false_strings = ("f", "false") _true_strings = ("t", "true") dtype = bool _type = 'bool' _default = {} def parse(self, val): if val is None: pass elif isinstance(val, str): val = val.lower() if val in self._true_strings: val = True elif val in self._false_strings: val = False else: raise ValueError(f"String '{val}' is not understood by {self.__class__.__name__}") elif not isinstance(val, bool): self._raise_type_error(val) return val
identifier_body
index.test.ts
/** * Created by cshao on 2021-02-19. */
const ESSerializer = require('../src/index'); import ClassA from './env/ClassA'; import ClassB from './env/ClassB'; import ClassC from './env/ClassC'; import MyObject from './env/MyObject'; import Person from './env/Person'; describe('Test serialize', () => { test('can serialize all fields of object', () => { const classAInstance = new ClassA(); classAInstance.name = 'SmallTiger'; const objectToBeSerialized = { name: 'Tiger', age: 42, sad: null, hate: undefined, live: true, son: classAInstance }; const serializedTextExpected = '{\"name\":\"Tiger\",\"age\":42,\"sad\":null,\"live\":true,\"son\":{\"_size\":0,\"_name\":\"SmallTiger\",\"age\":28,\"className\":\"ClassA\"}}'; expect(ESSerializer.serialize(objectToBeSerialized)).toStrictEqual(serializedTextExpected); }); test('can serialize function style class definition', () => { expect(ESSerializer.serialize(new Person(38))).toStrictEqual('{\"age\":38,\"className\":\"Person\"}'); }); test('can serialize prototype function style class definition', () => { expect(ESSerializer.serialize(new MyObject())).toStrictEqual('{\"property1\":\"First\",\"property2\":\"Second\",\"className\":\"MyObject\"}'); }); }); describe('Test deserialize', () => { test('can deserialize complex text', () => { const serializedText = '{"_hobby":"football","className":"ClassB","toy":{"_height":29,"className":"ClassC"},"friends":[{"_name":"Old man","age":88,"className":"ClassA"},{"_height":54,"className":"ClassC"},"To be or not to be"]}'; expect(ESSerializer.deserialize(serializedText, [SuperClassA, ClassA, ClassB, ClassC]).toy.height).toBe(29); }); test('can deserialize for function style class definition', () => { const serializedText = '{"age":77,"className":"Person"}'; expect(ESSerializer.deserialize(serializedText, [Person]).isOld()).toBe(true); }); test('can deserialize for prototype function style class definition', () => { const serializedText = '{\"property1\":\"One\",\"property2\":\"Two\",\"className\":\"MyObject\"}'; expect(ESSerializer.deserialize(serializedText, [MyObject]).isInitialized()).toBe(true); }); });
'use strict'; import SuperClassA from './env/SuperClassA';
random_line_split
architecture.py
# -*- encoding: utf-8 -*- """Implements Architecture UI""" from robottelo.constants import FILTER from robottelo.ui.base import Base from robottelo.ui.locators import common_locators, locators from robottelo.ui.navigator import Navigator class Architecture(Base): """Manipulates architecture from UI""" def navigate_to_entity(self): """Navigate to Architecture entity page""" Navigator(self.browser).go_to_architectures() def
(self): """Specify locator for Architecture entity search procedure""" return locators['arch.arch_name'] def create(self, name, os_names=None): """Creates new architecture from UI with existing OS""" self.click(locators['arch.new']) self.assign_value(locators['arch.name'], name) self.configure_entity(os_names, FILTER['arch_os']) self.click(common_locators['submit']) def delete(self, name, really=True): """Delete existing architecture from UI""" self.delete_entity( name, really, locators['arch.delete'], ) def update(self, old_name, new_name=None, os_names=None, new_os_names=None): """Update existing arch's name and OS""" self.search_and_click(old_name) if new_name: self.assign_value(locators['arch.name'], new_name) self.configure_entity( os_names, FILTER['arch_os'], new_entity_list=new_os_names ) self.click(common_locators['submit'])
_search_locator
identifier_name
architecture.py
# -*- encoding: utf-8 -*- """Implements Architecture UI""" from robottelo.constants import FILTER from robottelo.ui.base import Base from robottelo.ui.locators import common_locators, locators from robottelo.ui.navigator import Navigator class Architecture(Base): """Manipulates architecture from UI""" def navigate_to_entity(self): """Navigate to Architecture entity page"""
return locators['arch.arch_name'] def create(self, name, os_names=None): """Creates new architecture from UI with existing OS""" self.click(locators['arch.new']) self.assign_value(locators['arch.name'], name) self.configure_entity(os_names, FILTER['arch_os']) self.click(common_locators['submit']) def delete(self, name, really=True): """Delete existing architecture from UI""" self.delete_entity( name, really, locators['arch.delete'], ) def update(self, old_name, new_name=None, os_names=None, new_os_names=None): """Update existing arch's name and OS""" self.search_and_click(old_name) if new_name: self.assign_value(locators['arch.name'], new_name) self.configure_entity( os_names, FILTER['arch_os'], new_entity_list=new_os_names ) self.click(common_locators['submit'])
Navigator(self.browser).go_to_architectures() def _search_locator(self): """Specify locator for Architecture entity search procedure"""
random_line_split
architecture.py
# -*- encoding: utf-8 -*- """Implements Architecture UI""" from robottelo.constants import FILTER from robottelo.ui.base import Base from robottelo.ui.locators import common_locators, locators from robottelo.ui.navigator import Navigator class Architecture(Base): """Manipulates architecture from UI""" def navigate_to_entity(self): """Navigate to Architecture entity page""" Navigator(self.browser).go_to_architectures() def _search_locator(self): """Specify locator for Architecture entity search procedure""" return locators['arch.arch_name'] def create(self, name, os_names=None): """Creates new architecture from UI with existing OS""" self.click(locators['arch.new']) self.assign_value(locators['arch.name'], name) self.configure_entity(os_names, FILTER['arch_os']) self.click(common_locators['submit']) def delete(self, name, really=True): """Delete existing architecture from UI""" self.delete_entity( name, really, locators['arch.delete'], ) def update(self, old_name, new_name=None, os_names=None, new_os_names=None): """Update existing arch's name and OS""" self.search_and_click(old_name) if new_name:
self.configure_entity( os_names, FILTER['arch_os'], new_entity_list=new_os_names ) self.click(common_locators['submit'])
self.assign_value(locators['arch.name'], new_name)
conditional_block
architecture.py
# -*- encoding: utf-8 -*- """Implements Architecture UI""" from robottelo.constants import FILTER from robottelo.ui.base import Base from robottelo.ui.locators import common_locators, locators from robottelo.ui.navigator import Navigator class Architecture(Base): """Manipulates architecture from UI""" def navigate_to_entity(self):
def _search_locator(self): """Specify locator for Architecture entity search procedure""" return locators['arch.arch_name'] def create(self, name, os_names=None): """Creates new architecture from UI with existing OS""" self.click(locators['arch.new']) self.assign_value(locators['arch.name'], name) self.configure_entity(os_names, FILTER['arch_os']) self.click(common_locators['submit']) def delete(self, name, really=True): """Delete existing architecture from UI""" self.delete_entity( name, really, locators['arch.delete'], ) def update(self, old_name, new_name=None, os_names=None, new_os_names=None): """Update existing arch's name and OS""" self.search_and_click(old_name) if new_name: self.assign_value(locators['arch.name'], new_name) self.configure_entity( os_names, FILTER['arch_os'], new_entity_list=new_os_names ) self.click(common_locators['submit'])
"""Navigate to Architecture entity page""" Navigator(self.browser).go_to_architectures()
identifier_body
clientListStore.js
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1) { state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note } } } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => {
}) }, deleteMultipleClient({commit, dispatch}, clients) { HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) } } export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error)
random_line_split
clientListStore.js
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1) { state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note } } } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => { commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error) }) }, deleteMultipleClient({commit, dispatch}, clients)
} export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
{ HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) }
identifier_body
clientListStore.js
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1)
} } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => { commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error) }) }, deleteMultipleClient({commit, dispatch}, clients) { HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) } } export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
{ state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note }
conditional_block
clientListStore.js
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1) { state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note } } } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => { commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error) }) },
({commit, dispatch}, clients) { HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) } } export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
deleteMultipleClient
identifier_name
input.pp.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. // minimal junk #![feature(no_core)] #![no_core] macro_rules! foo /* 60#0 */(( $ x : ident ) => { y + $ x }); fn bar /* 62#0 */()
fn y /* 61#0 */() { }
{ let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ }
identifier_body
input.pp.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
// minimal junk #![feature(no_core)] #![no_core] macro_rules! foo /* 60#0 */(( $ x : ident ) => { y + $ x }); fn bar /* 62#0 */() { let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ } fn y /* 61#0 */() { }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
input.pp.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. // minimal junk #![feature(no_core)] #![no_core] macro_rules! foo /* 60#0 */(( $ x : ident ) => { y + $ x }); fn
/* 62#0 */() { let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ } fn y /* 61#0 */() { }
bar
identifier_name
rec.rs
use super::Fibonacci; pub struct
; impl Fibonacci for &Recursive { fn fib(self, n: u64) -> u64 { if n == 0 || n == 1 { 1 } else { self.fib(n - 1) + self.fib(n - 2) } } } #[cfg(test)] mod tests { use super::super::Fibonacci; use super::Recursive; macro_rules! fib_test { ($name:ident, $($i:expr, $e:expr),+) => { #[test] fn $name() { let r = Recursive; $({ let o = r.fib($i); assert_eq!(o, $e); })* } } } fib_test!(zero, 0, 1); fib_test!(one, 1, 1); fib_test!(two, 2, 2); fib_test!(three, 3, 3); }
Recursive
identifier_name
rec.rs
use super::Fibonacci; pub struct Recursive; impl Fibonacci for &Recursive { fn fib(self, n: u64) -> u64 { if n == 0 || n == 1 { 1 } else { self.fib(n - 1) + self.fib(n - 2) } } } #[cfg(test)] mod tests { use super::super::Fibonacci; use super::Recursive; macro_rules! fib_test { ($name:ident, $($i:expr, $e:expr),+) => { #[test] fn $name() { let r = Recursive; $({ let o = r.fib($i); assert_eq!(o, $e); })* } } }
fib_test!(two, 2, 2); fib_test!(three, 3, 3); }
fib_test!(zero, 0, 1); fib_test!(one, 1, 1);
random_line_split
rec.rs
use super::Fibonacci; pub struct Recursive; impl Fibonacci for &Recursive { fn fib(self, n: u64) -> u64 { if n == 0 || n == 1
else { self.fib(n - 1) + self.fib(n - 2) } } } #[cfg(test)] mod tests { use super::super::Fibonacci; use super::Recursive; macro_rules! fib_test { ($name:ident, $($i:expr, $e:expr),+) => { #[test] fn $name() { let r = Recursive; $({ let o = r.fib($i); assert_eq!(o, $e); })* } } } fib_test!(zero, 0, 1); fib_test!(one, 1, 1); fib_test!(two, 2, 2); fib_test!(three, 3, 3); }
{ 1 }
conditional_block
InputHandler.js
function InputHandler(viewport) { var self = this; self.pressedKeys = {}; self.mouseX = 0; self.mouseY = 0; self.mouseDownX = 0; self.mouseDownY = 0; self.mouseMoved = false; self.mouseDown = false; self.mouseButton = 0; // 1 = left | 2 = middle | 3 = right self.viewport = viewport; var viewportElem = viewport.get(0); viewportElem.ondrop = function(event) { self.onDrop(event); }; viewportElem.ondragover = function(event) { event.preventDefault(); }; viewportElem.onclick = function(event) { self.onClick(event); }; viewportElem.onmousedown = function(event) { self.onMouseDown(event); }; window.onmouseup = function(event) { self.onMouseUp(event); }; window.onkeydown = function(event) { self.onKeyDown(event); }; window.onkeyup = function(event) { self.onKeyUp(event); }; window.onmousemove = function(event) { self.onMouseMove(event); }; viewportElem.oncontextmenu = function(event) { event.preventDefault();}; viewport.mousewheel(function(event) { self.onScroll(event); }); } InputHandler.prototype.update = function(event) { for(var key in this.pressedKeys) { this.target.onKeyDown(key); } }; InputHandler.prototype.onKeyUp = function(event) { delete this.pressedKeys[event.keyCode]; }; InputHandler.prototype.onKeyDown = function(event) { // Avoid capturing key events from input boxes and text areas var tag = event.target.tagName.toLowerCase(); if (tag == 'input' || tag == 'textarea') return; var keyCode = event.keyCode; this.pressedKeys[keyCode] = true; var ctrl = event.ctrlKey; this.target.onKeyPress(keyCode, ctrl); }; InputHandler.prototype.isKeyDown = function(key) { var isDown = this.pressedKeys[key] !== undefined; return isDown; }; // Return mouse position in [0,1] range relative to bottom-left of viewport (screen space) InputHandler.prototype.convertToScreenSpace = function(pageX, pageY) { var left = this.viewport.offset().left; var top = this.viewport.offset().top; var width = this.viewport.innerWidth(); var height = this.viewport.innerHeight(); var x = (pageX - left)/width; var y = -(pageY - top)/height + 1.0; return [x,y]; }; InputHandler.prototype.onDrop = function(event) { event.preventDefault(); var mouse = this.convertToScreenSpace(event.pageX, event.pageY); var assetName = event.dataTransfer.getData("text"); this.target.dropAsset(assetName, mouse[0], mouse[1]); }; InputHandler.prototype.onClick = function(event) { if(this.mouseMoved) return; var screenSpace = this.convertToScreenSpace(event.pageX, event.pageY); this.target.onClick(screenSpace[0], screenSpace[1]); }; InputHandler.prototype.onMouseDown = function(event) { this.viewport.focus(); if(this.mouseButton > 0) return; // Don't process a mouse down from a different button until the current one is done this.mouseButton = event.which; this.mouseDown = true; var mouseX = event.pageX; var mouseY = event.pageY; this.mouseDownX = mouseX; this.mouseDownY = mouseY; this.mouseMoved = false; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseDown(screenSpace[0], screenSpace[1], this.mouseButton) }; InputHandler.prototype.onMouseUp = function(event) { this.mouseDown = false; this.mouseButton = 0; }; InputHandler.prototype.onMouseMove = function(event) { var mouseX = event.pageX; var mouseY = event.pageY; // Ignore click if mouse moved too much between mouse down and mouse click if(Math.abs(this.mouseDownX - mouseX) > 3 || Math.abs(this.mouseDownY - mouseY) > 3) { this.mouseMoved = true; } if(this.mouseDown) { event.preventDefault(); } var mouseMoveX = mouseX - this.mouseX; var mouseMoveY = mouseY - this.mouseY; this.mouseX = mouseX;
var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseMove(screenSpace[0], screenSpace[1], mouseMoveX, mouseMoveY, this.mouseButton); }; InputHandler.prototype.onScroll = function(event) { this.target.onScroll(event.deltaY); };
this.mouseY = mouseY;
random_line_split
InputHandler.js
function
(viewport) { var self = this; self.pressedKeys = {}; self.mouseX = 0; self.mouseY = 0; self.mouseDownX = 0; self.mouseDownY = 0; self.mouseMoved = false; self.mouseDown = false; self.mouseButton = 0; // 1 = left | 2 = middle | 3 = right self.viewport = viewport; var viewportElem = viewport.get(0); viewportElem.ondrop = function(event) { self.onDrop(event); }; viewportElem.ondragover = function(event) { event.preventDefault(); }; viewportElem.onclick = function(event) { self.onClick(event); }; viewportElem.onmousedown = function(event) { self.onMouseDown(event); }; window.onmouseup = function(event) { self.onMouseUp(event); }; window.onkeydown = function(event) { self.onKeyDown(event); }; window.onkeyup = function(event) { self.onKeyUp(event); }; window.onmousemove = function(event) { self.onMouseMove(event); }; viewportElem.oncontextmenu = function(event) { event.preventDefault();}; viewport.mousewheel(function(event) { self.onScroll(event); }); } InputHandler.prototype.update = function(event) { for(var key in this.pressedKeys) { this.target.onKeyDown(key); } }; InputHandler.prototype.onKeyUp = function(event) { delete this.pressedKeys[event.keyCode]; }; InputHandler.prototype.onKeyDown = function(event) { // Avoid capturing key events from input boxes and text areas var tag = event.target.tagName.toLowerCase(); if (tag == 'input' || tag == 'textarea') return; var keyCode = event.keyCode; this.pressedKeys[keyCode] = true; var ctrl = event.ctrlKey; this.target.onKeyPress(keyCode, ctrl); }; InputHandler.prototype.isKeyDown = function(key) { var isDown = this.pressedKeys[key] !== undefined; return isDown; }; // Return mouse position in [0,1] range relative to bottom-left of viewport (screen space) InputHandler.prototype.convertToScreenSpace = function(pageX, pageY) { var left = this.viewport.offset().left; var top = this.viewport.offset().top; var width = this.viewport.innerWidth(); var height = this.viewport.innerHeight(); var x = (pageX - left)/width; var y = -(pageY - top)/height + 1.0; return [x,y]; }; InputHandler.prototype.onDrop = function(event) { event.preventDefault(); var mouse = this.convertToScreenSpace(event.pageX, event.pageY); var assetName = event.dataTransfer.getData("text"); this.target.dropAsset(assetName, mouse[0], mouse[1]); }; InputHandler.prototype.onClick = function(event) { if(this.mouseMoved) return; var screenSpace = this.convertToScreenSpace(event.pageX, event.pageY); this.target.onClick(screenSpace[0], screenSpace[1]); }; InputHandler.prototype.onMouseDown = function(event) { this.viewport.focus(); if(this.mouseButton > 0) return; // Don't process a mouse down from a different button until the current one is done this.mouseButton = event.which; this.mouseDown = true; var mouseX = event.pageX; var mouseY = event.pageY; this.mouseDownX = mouseX; this.mouseDownY = mouseY; this.mouseMoved = false; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseDown(screenSpace[0], screenSpace[1], this.mouseButton) }; InputHandler.prototype.onMouseUp = function(event) { this.mouseDown = false; this.mouseButton = 0; }; InputHandler.prototype.onMouseMove = function(event) { var mouseX = event.pageX; var mouseY = event.pageY; // Ignore click if mouse moved too much between mouse down and mouse click if(Math.abs(this.mouseDownX - mouseX) > 3 || Math.abs(this.mouseDownY - mouseY) > 3) { this.mouseMoved = true; } if(this.mouseDown) { event.preventDefault(); } var mouseMoveX = mouseX - this.mouseX; var mouseMoveY = mouseY - this.mouseY; this.mouseX = mouseX; this.mouseY = mouseY; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseMove(screenSpace[0], screenSpace[1], mouseMoveX, mouseMoveY, this.mouseButton); }; InputHandler.prototype.onScroll = function(event) { this.target.onScroll(event.deltaY); };
InputHandler
identifier_name
InputHandler.js
function InputHandler(viewport) { var self = this; self.pressedKeys = {}; self.mouseX = 0; self.mouseY = 0; self.mouseDownX = 0; self.mouseDownY = 0; self.mouseMoved = false; self.mouseDown = false; self.mouseButton = 0; // 1 = left | 2 = middle | 3 = right self.viewport = viewport; var viewportElem = viewport.get(0); viewportElem.ondrop = function(event) { self.onDrop(event); }; viewportElem.ondragover = function(event) { event.preventDefault(); }; viewportElem.onclick = function(event) { self.onClick(event); }; viewportElem.onmousedown = function(event) { self.onMouseDown(event); }; window.onmouseup = function(event) { self.onMouseUp(event); }; window.onkeydown = function(event) { self.onKeyDown(event); }; window.onkeyup = function(event) { self.onKeyUp(event); }; window.onmousemove = function(event) { self.onMouseMove(event); }; viewportElem.oncontextmenu = function(event) { event.preventDefault();}; viewport.mousewheel(function(event) { self.onScroll(event); }); } InputHandler.prototype.update = function(event) { for(var key in this.pressedKeys) { this.target.onKeyDown(key); } }; InputHandler.prototype.onKeyUp = function(event) { delete this.pressedKeys[event.keyCode]; }; InputHandler.prototype.onKeyDown = function(event) { // Avoid capturing key events from input boxes and text areas var tag = event.target.tagName.toLowerCase(); if (tag == 'input' || tag == 'textarea') return; var keyCode = event.keyCode; this.pressedKeys[keyCode] = true; var ctrl = event.ctrlKey; this.target.onKeyPress(keyCode, ctrl); }; InputHandler.prototype.isKeyDown = function(key) { var isDown = this.pressedKeys[key] !== undefined; return isDown; }; // Return mouse position in [0,1] range relative to bottom-left of viewport (screen space) InputHandler.prototype.convertToScreenSpace = function(pageX, pageY) { var left = this.viewport.offset().left; var top = this.viewport.offset().top; var width = this.viewport.innerWidth(); var height = this.viewport.innerHeight(); var x = (pageX - left)/width; var y = -(pageY - top)/height + 1.0; return [x,y]; }; InputHandler.prototype.onDrop = function(event) { event.preventDefault(); var mouse = this.convertToScreenSpace(event.pageX, event.pageY); var assetName = event.dataTransfer.getData("text"); this.target.dropAsset(assetName, mouse[0], mouse[1]); }; InputHandler.prototype.onClick = function(event) { if(this.mouseMoved) return; var screenSpace = this.convertToScreenSpace(event.pageX, event.pageY); this.target.onClick(screenSpace[0], screenSpace[1]); }; InputHandler.prototype.onMouseDown = function(event) { this.viewport.focus(); if(this.mouseButton > 0) return; // Don't process a mouse down from a different button until the current one is done this.mouseButton = event.which; this.mouseDown = true; var mouseX = event.pageX; var mouseY = event.pageY; this.mouseDownX = mouseX; this.mouseDownY = mouseY; this.mouseMoved = false; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseDown(screenSpace[0], screenSpace[1], this.mouseButton) }; InputHandler.prototype.onMouseUp = function(event) { this.mouseDown = false; this.mouseButton = 0; }; InputHandler.prototype.onMouseMove = function(event) { var mouseX = event.pageX; var mouseY = event.pageY; // Ignore click if mouse moved too much between mouse down and mouse click if(Math.abs(this.mouseDownX - mouseX) > 3 || Math.abs(this.mouseDownY - mouseY) > 3)
if(this.mouseDown) { event.preventDefault(); } var mouseMoveX = mouseX - this.mouseX; var mouseMoveY = mouseY - this.mouseY; this.mouseX = mouseX; this.mouseY = mouseY; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseMove(screenSpace[0], screenSpace[1], mouseMoveX, mouseMoveY, this.mouseButton); }; InputHandler.prototype.onScroll = function(event) { this.target.onScroll(event.deltaY); };
{ this.mouseMoved = true; }
conditional_block
InputHandler.js
function InputHandler(viewport)
InputHandler.prototype.update = function(event) { for(var key in this.pressedKeys) { this.target.onKeyDown(key); } }; InputHandler.prototype.onKeyUp = function(event) { delete this.pressedKeys[event.keyCode]; }; InputHandler.prototype.onKeyDown = function(event) { // Avoid capturing key events from input boxes and text areas var tag = event.target.tagName.toLowerCase(); if (tag == 'input' || tag == 'textarea') return; var keyCode = event.keyCode; this.pressedKeys[keyCode] = true; var ctrl = event.ctrlKey; this.target.onKeyPress(keyCode, ctrl); }; InputHandler.prototype.isKeyDown = function(key) { var isDown = this.pressedKeys[key] !== undefined; return isDown; }; // Return mouse position in [0,1] range relative to bottom-left of viewport (screen space) InputHandler.prototype.convertToScreenSpace = function(pageX, pageY) { var left = this.viewport.offset().left; var top = this.viewport.offset().top; var width = this.viewport.innerWidth(); var height = this.viewport.innerHeight(); var x = (pageX - left)/width; var y = -(pageY - top)/height + 1.0; return [x,y]; }; InputHandler.prototype.onDrop = function(event) { event.preventDefault(); var mouse = this.convertToScreenSpace(event.pageX, event.pageY); var assetName = event.dataTransfer.getData("text"); this.target.dropAsset(assetName, mouse[0], mouse[1]); }; InputHandler.prototype.onClick = function(event) { if(this.mouseMoved) return; var screenSpace = this.convertToScreenSpace(event.pageX, event.pageY); this.target.onClick(screenSpace[0], screenSpace[1]); }; InputHandler.prototype.onMouseDown = function(event) { this.viewport.focus(); if(this.mouseButton > 0) return; // Don't process a mouse down from a different button until the current one is done this.mouseButton = event.which; this.mouseDown = true; var mouseX = event.pageX; var mouseY = event.pageY; this.mouseDownX = mouseX; this.mouseDownY = mouseY; this.mouseMoved = false; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseDown(screenSpace[0], screenSpace[1], this.mouseButton) }; InputHandler.prototype.onMouseUp = function(event) { this.mouseDown = false; this.mouseButton = 0; }; InputHandler.prototype.onMouseMove = function(event) { var mouseX = event.pageX; var mouseY = event.pageY; // Ignore click if mouse moved too much between mouse down and mouse click if(Math.abs(this.mouseDownX - mouseX) > 3 || Math.abs(this.mouseDownY - mouseY) > 3) { this.mouseMoved = true; } if(this.mouseDown) { event.preventDefault(); } var mouseMoveX = mouseX - this.mouseX; var mouseMoveY = mouseY - this.mouseY; this.mouseX = mouseX; this.mouseY = mouseY; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseMove(screenSpace[0], screenSpace[1], mouseMoveX, mouseMoveY, this.mouseButton); }; InputHandler.prototype.onScroll = function(event) { this.target.onScroll(event.deltaY); };
{ var self = this; self.pressedKeys = {}; self.mouseX = 0; self.mouseY = 0; self.mouseDownX = 0; self.mouseDownY = 0; self.mouseMoved = false; self.mouseDown = false; self.mouseButton = 0; // 1 = left | 2 = middle | 3 = right self.viewport = viewport; var viewportElem = viewport.get(0); viewportElem.ondrop = function(event) { self.onDrop(event); }; viewportElem.ondragover = function(event) { event.preventDefault(); }; viewportElem.onclick = function(event) { self.onClick(event); }; viewportElem.onmousedown = function(event) { self.onMouseDown(event); }; window.onmouseup = function(event) { self.onMouseUp(event); }; window.onkeydown = function(event) { self.onKeyDown(event); }; window.onkeyup = function(event) { self.onKeyUp(event); }; window.onmousemove = function(event) { self.onMouseMove(event); }; viewportElem.oncontextmenu = function(event) { event.preventDefault();}; viewport.mousewheel(function(event) { self.onScroll(event); }); }
identifier_body
terminalService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as cp from 'child_process'; import * as path from 'path'; import * as processes from 'vs/base/node/processes'; import * as nls from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { assign } from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { ITerminalService } from 'vs/workbench/parts/execution/common/execution'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITerminalConfiguration, getDefaultTerminalWindows, getDefaultTerminalLinuxReady, DEFAULT_TERMINAL_OSX } from 'vs/workbench/parts/execution/electron-browser/terminal'; import uri from 'vs/base/common/uri'; import { IProcessEnvironment } from 'vs/base/common/platform'; const TERMINAL_TITLE = nls.localize('console.title', "VS Code Console"); enum WinSpawnType { CMD, CMDER } export class WinTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly CMD = 'cmd.exe'; constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, processes.getWindowsShell(), cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); return new TPromise<void>((c, e) => { const title = `"${dir} - ${TERMINAL_TITLE}"`; const command = `""${args.join('" "')}" & pause"`; // use '|' to only pause on non-zero exit code const cmdArgs = [ '/c', 'start', title, '/wait', exec, '/c', command ]; // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env, windowsVerbatimArguments: true }; const cmd = cp.spawn(WinTerminalService.CMD, cmdArgs, options); cmd.on('error', e); c(null); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, command: string, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); const spawnType = this.getSpawnType(exec); // Make the drive letter uppercase on Windows (see #9448) if (cwd && cwd[1] === ':') { cwd = cwd[0].toUpperCase() + cwd.substr(1); } // cmder ignores the environment cwd and instead opts to always open in %USERPROFILE% // unless otherwise specified if (spawnType === WinSpawnType.CMDER) { spawner.spawn(exec, [cwd]); return TPromise.as(void 0); } // The '""' argument is the window title. Without this, exec doesn't work when the path // contains spaces const cmdArgs = ['/c', 'start', '/wait', '""', exec]; return new TPromise<void>((c, e) => { const env = cwd ? { cwd: cwd } : void 0; const child = spawner.spawn(command, cmdArgs, env); child.on('error', e); child.on('exit', () => c(null)); }); } private getSpawnType(exec: string): WinSpawnType { const basename = path.basename(exec).toLowerCase(); if (basename === 'cmder' || basename === 'cmder.exe') { return WinSpawnType.CMDER; } return WinSpawnType.CMD; } } export class MacTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly OSASCRIPT = '/usr/bin/osascript'; // osascript is the AppleScript interpreter on OS X constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd).done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { if (terminalApp === DEFAULT_TERMINAL_OSX || terminalApp === 'iTerm.app') { // On OS X we launch an AppleScript that creates (or reuses) a Terminal window // and then launches the program inside that window. const script = terminalApp === DEFAULT_TERMINAL_OSX ? 'TerminalHelper' : 'iTermHelper'; const scriptpath = uri.parse(require.toUrl(`vs/workbench/parts/execution/electron-browser/${script}.scpt`)).fsPath; const osaArgs = [ scriptpath, '-t', title || TERMINAL_TITLE, '-w', dir, ]; for (let a of args) { osaArgs.push('-a'); osaArgs.push(a); } if (envVars) { for (let key in envVars) { const value = envVars[key]; if (value === null) { osaArgs.push('-u'); osaArgs.push(key); } else { osaArgs.push('-e'); osaArgs.push(`${key}=${value}`); } } } let stderr = ''; const osa = cp.spawn(MacTerminalService.OSASCRIPT, osaArgs); osa.on('error', e); osa.stderr.on('data', (data) => { stderr += data.toString(); }); osa.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('mac.terminal.script.failed', "Script '{0}' failed with exit code {1}", script, code))); } } }); } else { e(new Error(nls.localize('mac.terminal.type.not.supported', "'{0}' not supported", terminalApp))); } }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { const child = spawner.spawn('/usr/bin/open', ['-a', terminalApp, cwd]); child.on('error', e); child.on('exit', () => c(null));
} export class LinuxTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly WAIT_MESSAGE = nls.localize('press.any.key', "Press any key to continue..."); constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); return new TPromise<void>((c, e) => { let termArgs: string[] = []; //termArgs.push('--title'); //termArgs.push(`"${TERMINAL_TITLE}"`); execPromise.then(exec => { if (exec.indexOf('gnome-terminal') >= 0) { termArgs.push('-x'); } else { termArgs.push('-e'); } termArgs.push('bash'); termArgs.push('-c'); const bashCommand = `${quote(args)}; echo; read -p "${LinuxTerminalService.WAIT_MESSAGE}" -n1;`; termArgs.push(`''${bashCommand}''`); // wrapping argument in two sets of ' because node is so "friendly" that it removes one set... // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env }; let stderr = ''; const cmd = cp.spawn(exec, termArgs, options); cmd.on('error', e); cmd.stderr.on('data', (data) => { stderr += data.toString(); }); cmd.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('linux.term.failed', "'{0}' failed with exit code {1}", exec, code))); } } }); }); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); const env = cwd ? { cwd: cwd } : void 0; return new TPromise<void>((c, e) => { execPromise.then(exec => { const child = spawner.spawn(exec, [], env); child.on('error', e); child.on('exit', () => c(null)); }); }); } } /** * Quote args if necessary and combine into a space separated string. */ function quote(args: string[]): string { let r = ''; for (let a of args) { if (a.indexOf(' ') >= 0) { r += '"' + a + '"'; } else { r += a; } r += ' '; } return r; }
}); }
random_line_split
terminalService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as cp from 'child_process'; import * as path from 'path'; import * as processes from 'vs/base/node/processes'; import * as nls from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { assign } from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { ITerminalService } from 'vs/workbench/parts/execution/common/execution'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITerminalConfiguration, getDefaultTerminalWindows, getDefaultTerminalLinuxReady, DEFAULT_TERMINAL_OSX } from 'vs/workbench/parts/execution/electron-browser/terminal'; import uri from 'vs/base/common/uri'; import { IProcessEnvironment } from 'vs/base/common/platform'; const TERMINAL_TITLE = nls.localize('console.title', "VS Code Console"); enum WinSpawnType { CMD, CMDER } export class WinTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly CMD = 'cmd.exe'; constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, processes.getWindowsShell(), cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); return new TPromise<void>((c, e) => { const title = `"${dir} - ${TERMINAL_TITLE}"`; const command = `""${args.join('" "')}" & pause"`; // use '|' to only pause on non-zero exit code const cmdArgs = [ '/c', 'start', title, '/wait', exec, '/c', command ]; // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env, windowsVerbatimArguments: true }; const cmd = cp.spawn(WinTerminalService.CMD, cmdArgs, options); cmd.on('error', e); c(null); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, command: string, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); const spawnType = this.getSpawnType(exec); // Make the drive letter uppercase on Windows (see #9448) if (cwd && cwd[1] === ':') { cwd = cwd[0].toUpperCase() + cwd.substr(1); } // cmder ignores the environment cwd and instead opts to always open in %USERPROFILE% // unless otherwise specified if (spawnType === WinSpawnType.CMDER) { spawner.spawn(exec, [cwd]); return TPromise.as(void 0); } // The '""' argument is the window title. Without this, exec doesn't work when the path // contains spaces const cmdArgs = ['/c', 'start', '/wait', '""', exec]; return new TPromise<void>((c, e) => { const env = cwd ? { cwd: cwd } : void 0; const child = spawner.spawn(command, cmdArgs, env); child.on('error', e); child.on('exit', () => c(null)); }); } private
(exec: string): WinSpawnType { const basename = path.basename(exec).toLowerCase(); if (basename === 'cmder' || basename === 'cmder.exe') { return WinSpawnType.CMDER; } return WinSpawnType.CMD; } } export class MacTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly OSASCRIPT = '/usr/bin/osascript'; // osascript is the AppleScript interpreter on OS X constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd).done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { if (terminalApp === DEFAULT_TERMINAL_OSX || terminalApp === 'iTerm.app') { // On OS X we launch an AppleScript that creates (or reuses) a Terminal window // and then launches the program inside that window. const script = terminalApp === DEFAULT_TERMINAL_OSX ? 'TerminalHelper' : 'iTermHelper'; const scriptpath = uri.parse(require.toUrl(`vs/workbench/parts/execution/electron-browser/${script}.scpt`)).fsPath; const osaArgs = [ scriptpath, '-t', title || TERMINAL_TITLE, '-w', dir, ]; for (let a of args) { osaArgs.push('-a'); osaArgs.push(a); } if (envVars) { for (let key in envVars) { const value = envVars[key]; if (value === null) { osaArgs.push('-u'); osaArgs.push(key); } else { osaArgs.push('-e'); osaArgs.push(`${key}=${value}`); } } } let stderr = ''; const osa = cp.spawn(MacTerminalService.OSASCRIPT, osaArgs); osa.on('error', e); osa.stderr.on('data', (data) => { stderr += data.toString(); }); osa.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('mac.terminal.script.failed', "Script '{0}' failed with exit code {1}", script, code))); } } }); } else { e(new Error(nls.localize('mac.terminal.type.not.supported', "'{0}' not supported", terminalApp))); } }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { const child = spawner.spawn('/usr/bin/open', ['-a', terminalApp, cwd]); child.on('error', e); child.on('exit', () => c(null)); }); } } export class LinuxTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly WAIT_MESSAGE = nls.localize('press.any.key', "Press any key to continue..."); constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); return new TPromise<void>((c, e) => { let termArgs: string[] = []; //termArgs.push('--title'); //termArgs.push(`"${TERMINAL_TITLE}"`); execPromise.then(exec => { if (exec.indexOf('gnome-terminal') >= 0) { termArgs.push('-x'); } else { termArgs.push('-e'); } termArgs.push('bash'); termArgs.push('-c'); const bashCommand = `${quote(args)}; echo; read -p "${LinuxTerminalService.WAIT_MESSAGE}" -n1;`; termArgs.push(`''${bashCommand}''`); // wrapping argument in two sets of ' because node is so "friendly" that it removes one set... // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env }; let stderr = ''; const cmd = cp.spawn(exec, termArgs, options); cmd.on('error', e); cmd.stderr.on('data', (data) => { stderr += data.toString(); }); cmd.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('linux.term.failed', "'{0}' failed with exit code {1}", exec, code))); } } }); }); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); const env = cwd ? { cwd: cwd } : void 0; return new TPromise<void>((c, e) => { execPromise.then(exec => { const child = spawner.spawn(exec, [], env); child.on('error', e); child.on('exit', () => c(null)); }); }); } } /** * Quote args if necessary and combine into a space separated string. */ function quote(args: string[]): string { let r = ''; for (let a of args) { if (a.indexOf(' ') >= 0) { r += '"' + a + '"'; } else { r += a; } r += ' '; } return r; }
getSpawnType
identifier_name
terminalService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as cp from 'child_process'; import * as path from 'path'; import * as processes from 'vs/base/node/processes'; import * as nls from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { assign } from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { ITerminalService } from 'vs/workbench/parts/execution/common/execution'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITerminalConfiguration, getDefaultTerminalWindows, getDefaultTerminalLinuxReady, DEFAULT_TERMINAL_OSX } from 'vs/workbench/parts/execution/electron-browser/terminal'; import uri from 'vs/base/common/uri'; import { IProcessEnvironment } from 'vs/base/common/platform'; const TERMINAL_TITLE = nls.localize('console.title', "VS Code Console"); enum WinSpawnType { CMD, CMDER } export class WinTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly CMD = 'cmd.exe'; constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, processes.getWindowsShell(), cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); return new TPromise<void>((c, e) => { const title = `"${dir} - ${TERMINAL_TITLE}"`; const command = `""${args.join('" "')}" & pause"`; // use '|' to only pause on non-zero exit code const cmdArgs = [ '/c', 'start', title, '/wait', exec, '/c', command ]; // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env, windowsVerbatimArguments: true }; const cmd = cp.spawn(WinTerminalService.CMD, cmdArgs, options); cmd.on('error', e); c(null); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, command: string, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); const spawnType = this.getSpawnType(exec); // Make the drive letter uppercase on Windows (see #9448) if (cwd && cwd[1] === ':') { cwd = cwd[0].toUpperCase() + cwd.substr(1); } // cmder ignores the environment cwd and instead opts to always open in %USERPROFILE% // unless otherwise specified if (spawnType === WinSpawnType.CMDER) { spawner.spawn(exec, [cwd]); return TPromise.as(void 0); } // The '""' argument is the window title. Without this, exec doesn't work when the path // contains spaces const cmdArgs = ['/c', 'start', '/wait', '""', exec]; return new TPromise<void>((c, e) => { const env = cwd ? { cwd: cwd } : void 0; const child = spawner.spawn(command, cmdArgs, env); child.on('error', e); child.on('exit', () => c(null)); }); } private getSpawnType(exec: string): WinSpawnType { const basename = path.basename(exec).toLowerCase(); if (basename === 'cmder' || basename === 'cmder.exe') { return WinSpawnType.CMDER; } return WinSpawnType.CMD; } } export class MacTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly OSASCRIPT = '/usr/bin/osascript'; // osascript is the AppleScript interpreter on OS X constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd).done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { if (terminalApp === DEFAULT_TERMINAL_OSX || terminalApp === 'iTerm.app') { // On OS X we launch an AppleScript that creates (or reuses) a Terminal window // and then launches the program inside that window. const script = terminalApp === DEFAULT_TERMINAL_OSX ? 'TerminalHelper' : 'iTermHelper'; const scriptpath = uri.parse(require.toUrl(`vs/workbench/parts/execution/electron-browser/${script}.scpt`)).fsPath; const osaArgs = [ scriptpath, '-t', title || TERMINAL_TITLE, '-w', dir, ]; for (let a of args) { osaArgs.push('-a'); osaArgs.push(a); } if (envVars) { for (let key in envVars) { const value = envVars[key]; if (value === null)
else { osaArgs.push('-e'); osaArgs.push(`${key}=${value}`); } } } let stderr = ''; const osa = cp.spawn(MacTerminalService.OSASCRIPT, osaArgs); osa.on('error', e); osa.stderr.on('data', (data) => { stderr += data.toString(); }); osa.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('mac.terminal.script.failed', "Script '{0}' failed with exit code {1}", script, code))); } } }); } else { e(new Error(nls.localize('mac.terminal.type.not.supported', "'{0}' not supported", terminalApp))); } }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { const child = spawner.spawn('/usr/bin/open', ['-a', terminalApp, cwd]); child.on('error', e); child.on('exit', () => c(null)); }); } } export class LinuxTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly WAIT_MESSAGE = nls.localize('press.any.key', "Press any key to continue..."); constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); return new TPromise<void>((c, e) => { let termArgs: string[] = []; //termArgs.push('--title'); //termArgs.push(`"${TERMINAL_TITLE}"`); execPromise.then(exec => { if (exec.indexOf('gnome-terminal') >= 0) { termArgs.push('-x'); } else { termArgs.push('-e'); } termArgs.push('bash'); termArgs.push('-c'); const bashCommand = `${quote(args)}; echo; read -p "${LinuxTerminalService.WAIT_MESSAGE}" -n1;`; termArgs.push(`''${bashCommand}''`); // wrapping argument in two sets of ' because node is so "friendly" that it removes one set... // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env }; let stderr = ''; const cmd = cp.spawn(exec, termArgs, options); cmd.on('error', e); cmd.stderr.on('data', (data) => { stderr += data.toString(); }); cmd.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('linux.term.failed', "'{0}' failed with exit code {1}", exec, code))); } } }); }); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); const env = cwd ? { cwd: cwd } : void 0; return new TPromise<void>((c, e) => { execPromise.then(exec => { const child = spawner.spawn(exec, [], env); child.on('error', e); child.on('exit', () => c(null)); }); }); } } /** * Quote args if necessary and combine into a space separated string. */ function quote(args: string[]): string { let r = ''; for (let a of args) { if (a.indexOf(' ') >= 0) { r += '"' + a + '"'; } else { r += a; } r += ' '; } return r; }
{ osaArgs.push('-u'); osaArgs.push(key); }
conditional_block
terminalService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as cp from 'child_process'; import * as path from 'path'; import * as processes from 'vs/base/node/processes'; import * as nls from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { assign } from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { ITerminalService } from 'vs/workbench/parts/execution/common/execution'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ITerminalConfiguration, getDefaultTerminalWindows, getDefaultTerminalLinuxReady, DEFAULT_TERMINAL_OSX } from 'vs/workbench/parts/execution/electron-browser/terminal'; import uri from 'vs/base/common/uri'; import { IProcessEnvironment } from 'vs/base/common/platform'; const TERMINAL_TITLE = nls.localize('console.title', "VS Code Console"); enum WinSpawnType { CMD, CMDER } export class WinTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly CMD = 'cmd.exe'; constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, processes.getWindowsShell(), cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); return new TPromise<void>((c, e) => { const title = `"${dir} - ${TERMINAL_TITLE}"`; const command = `""${args.join('" "')}" & pause"`; // use '|' to only pause on non-zero exit code const cmdArgs = [ '/c', 'start', title, '/wait', exec, '/c', command ]; // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env, windowsVerbatimArguments: true }; const cmd = cp.spawn(WinTerminalService.CMD, cmdArgs, options); cmd.on('error', e); c(null); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, command: string, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const exec = terminalConfig.windowsExec || getDefaultTerminalWindows(); const spawnType = this.getSpawnType(exec); // Make the drive letter uppercase on Windows (see #9448) if (cwd && cwd[1] === ':') { cwd = cwd[0].toUpperCase() + cwd.substr(1); } // cmder ignores the environment cwd and instead opts to always open in %USERPROFILE% // unless otherwise specified if (spawnType === WinSpawnType.CMDER) { spawner.spawn(exec, [cwd]); return TPromise.as(void 0); } // The '""' argument is the window title. Without this, exec doesn't work when the path // contains spaces const cmdArgs = ['/c', 'start', '/wait', '""', exec]; return new TPromise<void>((c, e) => { const env = cwd ? { cwd: cwd } : void 0; const child = spawner.spawn(command, cmdArgs, env); child.on('error', e); child.on('exit', () => c(null)); }); } private getSpawnType(exec: string): WinSpawnType { const basename = path.basename(exec).toLowerCase(); if (basename === 'cmder' || basename === 'cmder.exe') { return WinSpawnType.CMDER; } return WinSpawnType.CMD; } } export class MacTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly OSASCRIPT = '/usr/bin/osascript'; // osascript is the AppleScript interpreter on OS X constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd).done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { if (terminalApp === DEFAULT_TERMINAL_OSX || terminalApp === 'iTerm.app') { // On OS X we launch an AppleScript that creates (or reuses) a Terminal window // and then launches the program inside that window. const script = terminalApp === DEFAULT_TERMINAL_OSX ? 'TerminalHelper' : 'iTermHelper'; const scriptpath = uri.parse(require.toUrl(`vs/workbench/parts/execution/electron-browser/${script}.scpt`)).fsPath; const osaArgs = [ scriptpath, '-t', title || TERMINAL_TITLE, '-w', dir, ]; for (let a of args) { osaArgs.push('-a'); osaArgs.push(a); } if (envVars) { for (let key in envVars) { const value = envVars[key]; if (value === null) { osaArgs.push('-u'); osaArgs.push(key); } else { osaArgs.push('-e'); osaArgs.push(`${key}=${value}`); } } } let stderr = ''; const osa = cp.spawn(MacTerminalService.OSASCRIPT, osaArgs); osa.on('error', e); osa.stderr.on('data', (data) => { stderr += data.toString(); }); osa.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('mac.terminal.script.failed', "Script '{0}' failed with exit code {1}", script, code))); } } }); } else { e(new Error(nls.localize('mac.terminal.type.not.supported', "'{0}' not supported", terminalApp))); } }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void>
} export class LinuxTerminalService implements ITerminalService { public _serviceBrand: any; private static readonly WAIT_MESSAGE = nls.localize('press.any.key', "Press any key to continue..."); constructor( @IConfigurationService private readonly _configurationService: IConfigurationService ) { } public openTerminal(cwd?: string): void { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); this.spawnTerminal(cp, configuration, cwd) .done(null, errors.onUnexpectedError); } public runInTerminal(title: string, dir: string, args: string[], envVars: IProcessEnvironment): TPromise<void> { const configuration = this._configurationService.getValue<ITerminalConfiguration>(); const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); return new TPromise<void>((c, e) => { let termArgs: string[] = []; //termArgs.push('--title'); //termArgs.push(`"${TERMINAL_TITLE}"`); execPromise.then(exec => { if (exec.indexOf('gnome-terminal') >= 0) { termArgs.push('-x'); } else { termArgs.push('-e'); } termArgs.push('bash'); termArgs.push('-c'); const bashCommand = `${quote(args)}; echo; read -p "${LinuxTerminalService.WAIT_MESSAGE}" -n1;`; termArgs.push(`''${bashCommand}''`); // wrapping argument in two sets of ' because node is so "friendly" that it removes one set... // merge environment variables into a copy of the process.env const env = assign({}, process.env, envVars); // delete environment variables that have a null value Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]); const options: any = { cwd: dir, env: env }; let stderr = ''; const cmd = cp.spawn(exec, termArgs, options); cmd.on('error', e); cmd.stderr.on('data', (data) => { stderr += data.toString(); }); cmd.on('exit', (code: number) => { if (code === 0) { // OK c(null); } else { if (stderr) { const lines = stderr.split('\n', 1); e(new Error(lines[0])); } else { e(new Error(nls.localize('linux.term.failed', "'{0}' failed with exit code {1}", exec, code))); } } }); }); }); } private spawnTerminal(spawner, configuration: ITerminalConfiguration, cwd?: string): TPromise<void> { const terminalConfig = configuration.terminal.external; const execPromise = terminalConfig.linuxExec ? TPromise.as(terminalConfig.linuxExec) : getDefaultTerminalLinuxReady(); const env = cwd ? { cwd: cwd } : void 0; return new TPromise<void>((c, e) => { execPromise.then(exec => { const child = spawner.spawn(exec, [], env); child.on('error', e); child.on('exit', () => c(null)); }); }); } } /** * Quote args if necessary and combine into a space separated string. */ function quote(args: string[]): string { let r = ''; for (let a of args) { if (a.indexOf(' ') >= 0) { r += '"' + a + '"'; } else { r += a; } r += ' '; } return r; }
{ const terminalConfig = configuration.terminal.external; const terminalApp = terminalConfig.osxExec || DEFAULT_TERMINAL_OSX; return new TPromise<void>((c, e) => { const child = spawner.spawn('/usr/bin/open', ['-a', terminalApp, cwd]); child.on('error', e); child.on('exit', () => c(null)); }); }
identifier_body
catalog.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Floss } from '../models/floss'; import { DB } from '../models/db'; @Injectable() export class CatalogService { private flossUrl = 'app/floss'; // URL to web api constructor(private http: Http) { }
getFloss(id: number): Promise<Floss> { return this.getCatalog() .then(catalog => catalog.find(floss => floss.dmc === id)); } deleteFloss(floss: Floss, group : string): void { var my : Floss[] = this.load(group); if(!my){ my = []; } let newArr : Floss[] = my.filter(value => value.dmc != floss.dmc); console.log(newArr); this.store(group, newArr); } addFlossTo(floss: Floss, group: string) : void{ var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); if(found) return; console.log(collection); collection.push(floss); this.store(group, collection); } isFlossIn(floss: Floss, group: string) : boolean { var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); return found ? true : false; } store(name: string, data: any): void { let localData: any = localStorage.getItem('sara'); if (localData) { localData = JSON.parse(localData); } else { localData = {}; } localData[name] = data; localStorage.setItem('sara', JSON.stringify(localData)) } load(name: string): any { let data: any = JSON.parse(localStorage.getItem('sara')); if (!data) { return undefined; } if (name) { if (data[name]) { return data[name]; } else { return undefined; } } return data; } }
getCatalog(): Promise<Floss[]> { return Promise.resolve(DB.db); }
random_line_split
catalog.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Floss } from '../models/floss'; import { DB } from '../models/db'; @Injectable() export class CatalogService { private flossUrl = 'app/floss'; // URL to web api constructor(private http: Http) { } getCatalog(): Promise<Floss[]> { return Promise.resolve(DB.db); } getFloss(id: number): Promise<Floss> { return this.getCatalog() .then(catalog => catalog.find(floss => floss.dmc === id)); } deleteFloss(floss: Floss, group : string): void { var my : Floss[] = this.load(group); if(!my){ my = []; } let newArr : Floss[] = my.filter(value => value.dmc != floss.dmc); console.log(newArr); this.store(group, newArr); } addFlossTo(floss: Floss, group: string) : void{ var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); if(found) return; console.log(collection); collection.push(floss); this.store(group, collection); } isFlossIn(floss: Floss, group: string) : boolean { var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); return found ? true : false; } store(name: string, data: any): void { let localData: any = localStorage.getItem('sara'); if (localData) { localData = JSON.parse(localData); } else { localData = {}; } localData[name] = data; localStorage.setItem('sara', JSON.stringify(localData)) } load(name: string): any { let data: any = JSON.parse(localStorage.getItem('sara')); if (!data) { return undefined; } if (name) { if (data[name]) { return data[name]; } else
} return data; } }
{ return undefined; }
conditional_block
catalog.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Floss } from '../models/floss'; import { DB } from '../models/db'; @Injectable() export class CatalogService { private flossUrl = 'app/floss'; // URL to web api constructor(private http: Http) { } getCatalog(): Promise<Floss[]> { return Promise.resolve(DB.db); } getFloss(id: number): Promise<Floss> { return this.getCatalog() .then(catalog => catalog.find(floss => floss.dmc === id)); } deleteFloss(floss: Floss, group : string): void { var my : Floss[] = this.load(group); if(!my){ my = []; } let newArr : Floss[] = my.filter(value => value.dmc != floss.dmc); console.log(newArr); this.store(group, newArr); } addFlossTo(floss: Floss, group: string) : void{ var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); if(found) return; console.log(collection); collection.push(floss); this.store(group, collection); } isFlossIn(floss: Floss, group: string) : boolean
store(name: string, data: any): void { let localData: any = localStorage.getItem('sara'); if (localData) { localData = JSON.parse(localData); } else { localData = {}; } localData[name] = data; localStorage.setItem('sara', JSON.stringify(localData)) } load(name: string): any { let data: any = JSON.parse(localStorage.getItem('sara')); if (!data) { return undefined; } if (name) { if (data[name]) { return data[name]; } else { return undefined; } } return data; } }
{ var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); return found ? true : false; }
identifier_body
catalog.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Floss } from '../models/floss'; import { DB } from '../models/db'; @Injectable() export class CatalogService { private flossUrl = 'app/floss'; // URL to web api constructor(private http: Http) { } getCatalog(): Promise<Floss[]> { return Promise.resolve(DB.db); }
(id: number): Promise<Floss> { return this.getCatalog() .then(catalog => catalog.find(floss => floss.dmc === id)); } deleteFloss(floss: Floss, group : string): void { var my : Floss[] = this.load(group); if(!my){ my = []; } let newArr : Floss[] = my.filter(value => value.dmc != floss.dmc); console.log(newArr); this.store(group, newArr); } addFlossTo(floss: Floss, group: string) : void{ var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); if(found) return; console.log(collection); collection.push(floss); this.store(group, collection); } isFlossIn(floss: Floss, group: string) : boolean { var collection : Floss[] = this.load(group); if(!collection){ collection = []; } let found : Floss = collection.find(value => value.dmc === floss.dmc); return found ? true : false; } store(name: string, data: any): void { let localData: any = localStorage.getItem('sara'); if (localData) { localData = JSON.parse(localData); } else { localData = {}; } localData[name] = data; localStorage.setItem('sara', JSON.stringify(localData)) } load(name: string): any { let data: any = JSON.parse(localStorage.getItem('sara')); if (!data) { return undefined; } if (name) { if (data[name]) { return data[name]; } else { return undefined; } } return data; } }
getFloss
identifier_name
ng_if.ts
* Removes or recreates a portion of the DOM tree based on an {expression}. * * If the expression assigned to `ng-if` evaluates to a false value then the element * is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. * * # Example: * * ``` * <div *ng-if="errorCount > 0" class="error"> * <!-- Error message displayed when the errorCount property on the current context is greater * than 0. --> * {{errorCount}} errors detected * </div> * ``` * * # Syntax * * - `<div *ng-if="condition">...</div>` * - `<div template="ng-if condition">...</div>` * - `<template [ng-if]="condition"><div>...</div></template>` */ @Directive({selector: '[ng-if]', properties: ['ngIf']}) export class NgIf { viewContainer: ViewContainerRef; templateRef: TemplateRef; prevCondition: boolean; constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef) { this.viewContainer = viewContainer; this.prevCondition = null; this.templateRef = templateRef; } set ngIf(newCondition /* boolean */) { if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) { this.prevCondition = true; this.viewContainer.createEmbeddedView(this.templateRef); } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) { this.prevCondition = false; this.viewContainer.clear(); } } }
import {Directive} from 'angular2/annotations'; import {ViewContainerRef, TemplateRef} from 'angular2/core'; import {isBlank} from 'angular2/src/facade/lang'; /**
random_line_split
ng_if.ts
import {Directive} from 'angular2/annotations'; import {ViewContainerRef, TemplateRef} from 'angular2/core'; import {isBlank} from 'angular2/src/facade/lang'; /** * Removes or recreates a portion of the DOM tree based on an {expression}. * * If the expression assigned to `ng-if` evaluates to a false value then the element * is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. * * # Example: * * ``` * <div *ng-if="errorCount > 0" class="error"> * <!-- Error message displayed when the errorCount property on the current context is greater * than 0. --> * {{errorCount}} errors detected * </div> * ``` * * # Syntax * * - `<div *ng-if="condition">...</div>` * - `<div template="ng-if condition">...</div>` * - `<template [ng-if]="condition"><div>...</div></template>` */ @Directive({selector: '[ng-if]', properties: ['ngIf']}) export class NgIf { viewContainer: ViewContainerRef; templateRef: TemplateRef; prevCondition: boolean;
(viewContainer: ViewContainerRef, templateRef: TemplateRef) { this.viewContainer = viewContainer; this.prevCondition = null; this.templateRef = templateRef; } set ngIf(newCondition /* boolean */) { if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) { this.prevCondition = true; this.viewContainer.createEmbeddedView(this.templateRef); } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) { this.prevCondition = false; this.viewContainer.clear(); } } }
constructor
identifier_name
About.py
# -*- coding: utf-8 -*- import sys, os, time from Tools.HardwareInfo import HardwareInfo def getVersionString(): return getImageVersionString() def getImageVersionString(): try: if os.path.isfile('/var/lib/opkg/status'): st = os.stat('/var/lib/opkg/status') else: st = os.stat('/usr/lib/ipkg/status') tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: return time.strftime("%Y-%m-%d %H:%M:%S", tm) except: pass return _("unavailable") def getFlashDateString(): try: return time.strftime(_("%Y-%m-%d %H:%M"), time.strptime(open("/etc/version").read().strip(), '%Y%m%d%H%M')) except: return _("unknown") def getEnigmaVersionString(): import enigma enigma_version = enigma.getEnigmaVersionString() if '-(no branch)' in enigma_version: enigma_version = enigma_version [:-12] return enigma_version def getGStreamerVersionString(): import enigma return enigma.getGStreamerVersionString() def getKernelVersionString(): try: return open("/proc/version","r").read().split(' ', 4)[2].split('-',2)[0] except: return _("unknown") def getHardwareTypeString(): return HardwareInfo().get_device_string() def getImageTypeString(): try: return "Taapat based on " + open("/etc/issue").readlines()[-2].capitalize().strip()[:-6] except: return _("undefined") def getCPUInfoString(): try: cpu_count = 0 cpu_speed = 0 temperature = None for line in open("/proc/cpuinfo").readlines(): line = [x.strip() for x in line.strip().split(":")] if line[0] in ("system type", "model name"): processor = line[1].split()[0] elif line[0] == "cpu MHz": cpu_speed = "%1.0f" % float(line[1]) elif line[0] == "processor": cpu_count += 1 if not cpu_speed: try: cpu_speed = int(open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq").read()) / 1000 except: try: import binascii cpu_speed = int(int(binascii.hexlify(open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb').read()), 16) / 100000000) * 100 except: cpu_speed = "-" if os.path.isfile('/proc/stb/fp/temp_sensor_avs'): temperature = open("/proc/stb/fp/temp_sensor_avs").readline().replace('\n','') if os.path.isfile("/sys/devices/virtual/thermal/thermal_zone0/temp"): try: temperature = int(open("/sys/devices/virtual/thermal/thermal_zone0/temp").read().strip())/1000 except: pass if temperature: return "%s %s MHz (%s) %s�C" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count, temperature) return "%s %s MHz (%s)" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count) except: return _("undefined") def getDriverInstalledDate(): try: from glob import glob driver = [x.split("-")[1][:8] for x in open(glob("/var/lib/opkg/info/vuplus-dvb-*.control")[0], "r") if x.startswith("Version:")][0] return "%s-%s-%s" % (driver[:4], driver[4:6], driver[6:]) except: return _("unknown") def getPythonVersionString(): try: import commands status, output = commands.getstatusoutput("python -V") return output.split(' ')[1] except: return _("unknown") def Ge
: import socket, fcntl, struct, array, sys is_64bits = sys.maxsize > 2**32 struct_size = 40 if is_64bits else 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) max_possible = 8 # initial value while True: _bytes = max_possible * struct_size names = array.array('B') for i in range(0, _bytes): names.append(0) outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', _bytes, names.buffer_info()[0]) ))[0] if outbytes == _bytes: max_possible *= 2 else: break namestr = names.tostring() ifaces = [] for i in range(0, outbytes, struct_size): iface_name = bytes.decode(namestr[i:i+16]).split('\0', 1)[0].encode('ascii') if iface_name != 'lo': iface_addr = socket.inet_ntoa(namestr[i+20:i+24]) ifaces.append((iface_name, iface_addr)) return ifaces # For modules that do "from About import about" about = sys.modules[__name__]
tIPsFromNetworkInterfaces()
identifier_name
About.py
# -*- coding: utf-8 -*- import sys, os, time from Tools.HardwareInfo import HardwareInfo def getVersionString(): return getImageVersionString() def getImageVersionString(): try: if os.path.isfile('/var/lib/opkg/status'): st = os.stat('/var/lib/opkg/status') else: st = os.stat('/usr/lib/ipkg/status') tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: return time.strftime("%Y-%m-%d %H:%M:%S", tm) except: pass return _("unavailable") def getFlashDateString(): try: return time.strftime(_("%Y-%m-%d %H:%M"), time.strptime(open("/etc/version").read().strip(), '%Y%m%d%H%M')) except: return _("unknown") def getEnigmaVersionString(): import enigma enigma_version = enigma.getEnigmaVersionString() if '-(no branch)' in enigma_version: enigma_version = enigma_version [:-12] return enigma_version def getGStreamerVersionString(): import enigma return enigma.getGStreamerVersionString() def getKernelVersionString(): try: return open("/proc/version","r").read().split(' ', 4)[2].split('-',2)[0] except: return _("unknown") def getHardwareTypeString(): return HardwareInfo().get_device_string() def getImageTypeString(): try: return "Taapat based on " + open("/etc/issue").readlines()[-2].capitalize().strip()[:-6] except: return _("undefined") def getCPUInfoString(): try: cpu_count = 0 cpu_speed = 0 temperature = None for line in open("/proc/cpuinfo").readlines(): line = [x.strip() for x in line.strip().split(":")] if line[0] in ("system type", "model name"): processor = line[1].split()[0] elif line[0] == "cpu MHz": cpu_speed = "%1.0f" % float(line[1]) elif line[0] == "processor": cpu_count += 1 if not cpu_speed: try: cpu_speed = int(open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq").read()) / 1000 except: try: import binascii cpu_speed = int(int(binascii.hexlify(open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb').read()), 16) / 100000000) * 100 except: cpu_speed = "-" if os.path.isfile('/proc/stb/fp/temp_sensor_avs'): temperature = open("/proc/stb/fp/temp_sensor_avs").readline().replace('\n','') if os.path.isfile("/sys/devices/virtual/thermal/thermal_zone0/temp"): try: temperature = int(open("/sys/devices/virtual/thermal/thermal_zone0/temp").read().strip())/1000 except: pass if temperature: return "%s %s MHz (%s) %s�C" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count, temperature) return "%s %s MHz (%s)" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count) except: return _("undefined") def getDriverInstalledDate(): try: from glob import glob driver = [x.split("-")[1][:8] for x in open(glob("/var/lib/opkg/info/vuplus-dvb-*.control")[0], "r") if x.startswith("Version:")][0] return "%s-%s-%s" % (driver[:4], driver[4:6], driver[6:]) except: return _("unknown") def getPythonVersionString(): try: import commands status, output = commands.getstatusoutput("python -V") return output.split(' ')[1] except: return _("unknown") def GetIPsFromNetworkInterfaces(): import socket, fcntl, struct, array, sys is_64bits = sys.maxsize > 2**32 struct_size = 40 if is_64bits else 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) max_possible = 8 # initial value while True: _bytes = max_possible * struct_size names = array.array('B') for i in range(0, _bytes): names.append(0) outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', _bytes, names.buffer_info()[0]) ))[0] if outbytes == _bytes: ma
else: break namestr = names.tostring() ifaces = [] for i in range(0, outbytes, struct_size): iface_name = bytes.decode(namestr[i:i+16]).split('\0', 1)[0].encode('ascii') if iface_name != 'lo': iface_addr = socket.inet_ntoa(namestr[i+20:i+24]) ifaces.append((iface_name, iface_addr)) return ifaces # For modules that do "from About import about" about = sys.modules[__name__]
x_possible *= 2
conditional_block
About.py
# -*- coding: utf-8 -*- import sys, os, time from Tools.HardwareInfo import HardwareInfo def getVersionString(): return getImageVersionString() def getImageVersionString(): try: if os.path.isfile('/var/lib/opkg/status'): st = os.stat('/var/lib/opkg/status') else: st = os.stat('/usr/lib/ipkg/status') tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: return time.strftime("%Y-%m-%d %H:%M:%S", tm) except: pass return _("unavailable") def getFlashDateString(): try: return time.strftime(_("%Y-%m-%d %H:%M"), time.strptime(open("/etc/version").read().strip(), '%Y%m%d%H%M')) except: return _("unknown") def getEnigmaVersionString(): import enigma enigma_version = enigma.getEnigmaVersionString() if '-(no branch)' in enigma_version: enigma_version = enigma_version [:-12] return enigma_version def getGStreamerVersionString(): import enigma return enigma.getGStreamerVersionString() def getKernelVersionString(): try: return open("/proc/version","r").read().split(' ', 4)[2].split('-',2)[0] except: return _("unknown") def getHardwareTypeString():
def getImageTypeString(): try: return "Taapat based on " + open("/etc/issue").readlines()[-2].capitalize().strip()[:-6] except: return _("undefined") def getCPUInfoString(): try: cpu_count = 0 cpu_speed = 0 temperature = None for line in open("/proc/cpuinfo").readlines(): line = [x.strip() for x in line.strip().split(":")] if line[0] in ("system type", "model name"): processor = line[1].split()[0] elif line[0] == "cpu MHz": cpu_speed = "%1.0f" % float(line[1]) elif line[0] == "processor": cpu_count += 1 if not cpu_speed: try: cpu_speed = int(open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq").read()) / 1000 except: try: import binascii cpu_speed = int(int(binascii.hexlify(open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb').read()), 16) / 100000000) * 100 except: cpu_speed = "-" if os.path.isfile('/proc/stb/fp/temp_sensor_avs'): temperature = open("/proc/stb/fp/temp_sensor_avs").readline().replace('\n','') if os.path.isfile("/sys/devices/virtual/thermal/thermal_zone0/temp"): try: temperature = int(open("/sys/devices/virtual/thermal/thermal_zone0/temp").read().strip())/1000 except: pass if temperature: return "%s %s MHz (%s) %s�C" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count, temperature) return "%s %s MHz (%s)" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count) except: return _("undefined") def getDriverInstalledDate(): try: from glob import glob driver = [x.split("-")[1][:8] for x in open(glob("/var/lib/opkg/info/vuplus-dvb-*.control")[0], "r") if x.startswith("Version:")][0] return "%s-%s-%s" % (driver[:4], driver[4:6], driver[6:]) except: return _("unknown") def getPythonVersionString(): try: import commands status, output = commands.getstatusoutput("python -V") return output.split(' ')[1] except: return _("unknown") def GetIPsFromNetworkInterfaces(): import socket, fcntl, struct, array, sys is_64bits = sys.maxsize > 2**32 struct_size = 40 if is_64bits else 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) max_possible = 8 # initial value while True: _bytes = max_possible * struct_size names = array.array('B') for i in range(0, _bytes): names.append(0) outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', _bytes, names.buffer_info()[0]) ))[0] if outbytes == _bytes: max_possible *= 2 else: break namestr = names.tostring() ifaces = [] for i in range(0, outbytes, struct_size): iface_name = bytes.decode(namestr[i:i+16]).split('\0', 1)[0].encode('ascii') if iface_name != 'lo': iface_addr = socket.inet_ntoa(namestr[i+20:i+24]) ifaces.append((iface_name, iface_addr)) return ifaces # For modules that do "from About import about" about = sys.modules[__name__]
return HardwareInfo().get_device_string()
identifier_body
About.py
# -*- coding: utf-8 -*- import sys, os, time from Tools.HardwareInfo import HardwareInfo def getVersionString(): return getImageVersionString() def getImageVersionString(): try: if os.path.isfile('/var/lib/opkg/status'): st = os.stat('/var/lib/opkg/status') else: st = os.stat('/usr/lib/ipkg/status') tm = time.localtime(st.st_mtime) if tm.tm_year >= 2011: return time.strftime("%Y-%m-%d %H:%M:%S", tm) except: pass return _("unavailable") def getFlashDateString(): try: return time.strftime(_("%Y-%m-%d %H:%M"), time.strptime(open("/etc/version").read().strip(), '%Y%m%d%H%M')) except: return _("unknown") def getEnigmaVersionString(): import enigma enigma_version = enigma.getEnigmaVersionString() if '-(no branch)' in enigma_version: enigma_version = enigma_version [:-12] return enigma_version def getGStreamerVersionString(): import enigma return enigma.getGStreamerVersionString() def getKernelVersionString(): try: return open("/proc/version","r").read().split(' ', 4)[2].split('-',2)[0] except: return _("unknown") def getHardwareTypeString(): return HardwareInfo().get_device_string() def getImageTypeString(): try: return "Taapat based on " + open("/etc/issue").readlines()[-2].capitalize().strip()[:-6] except: return _("undefined") def getCPUInfoString(): try: cpu_count = 0 cpu_speed = 0 temperature = None for line in open("/proc/cpuinfo").readlines(): line = [x.strip() for x in line.strip().split(":")] if line[0] in ("system type", "model name"): processor = line[1].split()[0] elif line[0] == "cpu MHz": cpu_speed = "%1.0f" % float(line[1]) elif line[0] == "processor": cpu_count += 1 if not cpu_speed: try: cpu_speed = int(open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq").read()) / 1000 except: try: import binascii cpu_speed = int(int(binascii.hexlify(open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb').read()), 16) / 100000000) * 100 except: cpu_speed = "-" if os.path.isfile('/proc/stb/fp/temp_sensor_avs'): temperature = open("/proc/stb/fp/temp_sensor_avs").readline().replace('\n','') if os.path.isfile("/sys/devices/virtual/thermal/thermal_zone0/temp"): try: temperature = int(open("/sys/devices/virtual/thermal/thermal_zone0/temp").read().strip())/1000 except: pass if temperature: return "%s %s MHz (%s) %s�C" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count, temperature) return "%s %s MHz (%s)" % (processor, cpu_speed, ngettext("%d core", "%d cores", cpu_count) % cpu_count) except: return _("undefined") def getDriverInstalledDate(): try: from glob import glob driver = [x.split("-")[1][:8] for x in open(glob("/var/lib/opkg/info/vuplus-dvb-*.control")[0], "r") if x.startswith("Version:")][0]
return _("unknown") def getPythonVersionString(): try: import commands status, output = commands.getstatusoutput("python -V") return output.split(' ')[1] except: return _("unknown") def GetIPsFromNetworkInterfaces(): import socket, fcntl, struct, array, sys is_64bits = sys.maxsize > 2**32 struct_size = 40 if is_64bits else 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) max_possible = 8 # initial value while True: _bytes = max_possible * struct_size names = array.array('B') for i in range(0, _bytes): names.append(0) outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', _bytes, names.buffer_info()[0]) ))[0] if outbytes == _bytes: max_possible *= 2 else: break namestr = names.tostring() ifaces = [] for i in range(0, outbytes, struct_size): iface_name = bytes.decode(namestr[i:i+16]).split('\0', 1)[0].encode('ascii') if iface_name != 'lo': iface_addr = socket.inet_ntoa(namestr[i+20:i+24]) ifaces.append((iface_name, iface_addr)) return ifaces # For modules that do "from About import about" about = sys.modules[__name__]
return "%s-%s-%s" % (driver[:4], driver[4:6], driver[6:]) except:
random_line_split
macro-pat.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. macro_rules! mypat { () => ( Some('y') ) } macro_rules! char_x { () => ( 'x' ) } macro_rules! some { ($x:pat) => ( Some($x) ) } macro_rules! indirect { () => ( some!(char_x!()) ) } macro_rules! ident_pat { ($x:ident) => ( $x ) } fn f(c: Option<char>) -> uint { match c {
mypat!() => 2, _ => 3, } } pub fn main() { assert_eq!(1u, f(Some('x'))); assert_eq!(2u, f(Some('y'))); assert_eq!(3u, f(None)); assert_eq!(1, match Some('x') { Some(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { some!(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { indirect!() => 1, _ => 2, }); assert_eq!(3, { let ident_pat!(x) = 2; x+1 }); }
Some('x') => 1,
random_line_split
macro-pat.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. macro_rules! mypat { () => ( Some('y') ) } macro_rules! char_x { () => ( 'x' ) } macro_rules! some { ($x:pat) => ( Some($x) ) } macro_rules! indirect { () => ( some!(char_x!()) ) } macro_rules! ident_pat { ($x:ident) => ( $x ) } fn f(c: Option<char>) -> uint { match c { Some('x') => 1, mypat!() => 2, _ => 3, } } pub fn main()
{ assert_eq!(1u, f(Some('x'))); assert_eq!(2u, f(Some('y'))); assert_eq!(3u, f(None)); assert_eq!(1, match Some('x') { Some(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { some!(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { indirect!() => 1, _ => 2, }); assert_eq!(3, { let ident_pat!(x) = 2; x+1 }); }
identifier_body
macro-pat.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. macro_rules! mypat { () => ( Some('y') ) } macro_rules! char_x { () => ( 'x' ) } macro_rules! some { ($x:pat) => ( Some($x) ) } macro_rules! indirect { () => ( some!(char_x!()) ) } macro_rules! ident_pat { ($x:ident) => ( $x ) } fn
(c: Option<char>) -> uint { match c { Some('x') => 1, mypat!() => 2, _ => 3, } } pub fn main() { assert_eq!(1u, f(Some('x'))); assert_eq!(2u, f(Some('y'))); assert_eq!(3u, f(None)); assert_eq!(1, match Some('x') { Some(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { some!(char_x!()) => 1, _ => 2, }); assert_eq!(1, match Some('x') { indirect!() => 1, _ => 2, }); assert_eq!(3, { let ident_pat!(x) = 2; x+1 }); }
f
identifier_name
Action.js
/* * Ext JS Library 2.3.0 * Copyright(c) 2006-2009, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Action * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * the Form needs to perform an action such as submit or load. The Configuration options * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p> * <p>The instance of Action which performed the action is passed to the success * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}), * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p> */ Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; /** * Failure type returned when client side validation of the Form fails * thus aborting a submit action. * @type {String} * @static */ Ext.form.Action.CLIENT_INVALID = 'client'; /** * Failure type returned when server side validation of the Form fails * indicating that field-specific error messages have been returned in the * response's <tt style="font-weight:bold">errors</tt> property. * @type {String} * @static */ Ext.form.Action.SERVER_INVALID = 'server'; /** * Failure type returned when a communication error happens when attempting * to send a request to the remote server. * @type {String} * @static */ Ext.form.Action.CONNECT_FAILURE = 'connect'; /** * Failure type returned when no field values are returned in the response's * <tt style="font-weight:bold">data</tt> property. * @type {String} * @static */ Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { /** * @cfg {String} url The URL that the Action is to invoke. */ /** * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens * <b>before</b> the {@link #success} callback is called and before the Form's * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires. */ /** * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method. */ /** * @cfg {Mixed} params<p>Extra parameter values to pass. These are added to the Form's * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's * input fields.</p> * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p> */ /** * @cfg {Number} timeout The number of milliseconds to wait for a server response before * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. */ /** * @cfg {Function} success The function to call when a valid success return packet is recieved. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Function} failure The function to call when a failure packet was recieved, or when an * error ocurred in the Ajax communication. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax * error ocurred, the failure type will be in {@link #failureType}. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference * for the callback functions). */ /** * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * The type of action this Action instance performs. * Currently only "submit" and "load" are supported. * @type {String} */ type : 'default', /** * The type of failure detected. See {@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID}, * {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID}, * {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}, {@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE} * @property failureType * @type {String} *//** * The XMLHttpRequest object used to perform the action. * @property response * @type {Object} *//** * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and * other, action-specific properties. * @property result * @type {Object} */ // interface method run : function(options){ }, // interface method success : function(response){ }, // interface method handleResponse : function(response){ }, // default connection failure failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, // private processResponse : function(response){ this.response = response; if(!response.responseText && !response.responseXML){ return true; } this.result = this.handleResponse(response); return this.result; }, // utility functions used internally getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, // private getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, // private getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, // private createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; /** * @class Ext.form.Action.Submit * @extends Ext.form.Action * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s * and processes the returned response.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#submit submit}ting.</p> * <p>A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally * an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error * messages for invalid fields.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: false, errors: { clientCode: "Client not found", portOfLoading: "This field must not be null" } }</code></pre> * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code> errorReader: new Ext.data.XmlReader({ record : 'field', success: '@success' }, [ 'id', 'msg' ] ) </code></pre> * <p>then the results may be sent back in XML format:</p><pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;message success="false"&gt; &lt;errors&gt; &lt;field&gt; &lt;id&gt;clientCode&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;field&gt; &lt;id&gt;portOfLoading&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;/errors&gt; &lt;/message&gt; </code></pre> * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p> */ Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { /** * @cfg {Ext.data.DataReader} errorReader <b>Optional. JSON is interpreted with no need for an errorReader.</b> * <p>A Reader which reads a single record from the returned data. The DataReader's <b>success</b> property specifies * how submission success is determined. The Record's data provides the error messages to apply to any invalid form Fields.</p>. */ /** * @cfg {boolean} clientValidation Determines whether a Form's fields are validated * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission. * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation * is performed. */ type : 'submit', // private run : function(){ var o = this.options; var method = this.getMethod(); var isGet = method == 'GET'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(isGet), method: method, headers: o.headers,
this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, // private success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, // private handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); /** * @class Ext.form.Action.Load * @extends Ext.form.Action * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#load load}ing.</p> * <p>A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and * a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property * contains the values of Fields to load. The individual value object for each Field * is passed to the Field's {@link Ext.form.Field#setValue setValue} method.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: true, data: { clientName: "Fred. Olsen Lines", portOfLoading: "FXT", portOfDischarge: "OSL" } }</code></pre> * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> */ Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { // private type : 'load', // private run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), headers: this.options.headers, params:this.getParams() })); }, // private success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, // private handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit };
params:!isGet ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ // client validation failed
random_line_split
Action.js
/* * Ext JS Library 2.3.0 * Copyright(c) 2006-2009, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Action * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * the Form needs to perform an action such as submit or load. The Configuration options * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p> * <p>The instance of Action which performed the action is passed to the success * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}), * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p> */ Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; /** * Failure type returned when client side validation of the Form fails * thus aborting a submit action. * @type {String} * @static */ Ext.form.Action.CLIENT_INVALID = 'client'; /** * Failure type returned when server side validation of the Form fails * indicating that field-specific error messages have been returned in the * response's <tt style="font-weight:bold">errors</tt> property. * @type {String} * @static */ Ext.form.Action.SERVER_INVALID = 'server'; /** * Failure type returned when a communication error happens when attempting * to send a request to the remote server. * @type {String} * @static */ Ext.form.Action.CONNECT_FAILURE = 'connect'; /** * Failure type returned when no field values are returned in the response's * <tt style="font-weight:bold">data</tt> property. * @type {String} * @static */ Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { /** * @cfg {String} url The URL that the Action is to invoke. */ /** * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens * <b>before</b> the {@link #success} callback is called and before the Form's * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires. */ /** * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method. */ /** * @cfg {Mixed} params<p>Extra parameter values to pass. These are added to the Form's * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's * input fields.</p> * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p> */ /** * @cfg {Number} timeout The number of milliseconds to wait for a server response before * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. */ /** * @cfg {Function} success The function to call when a valid success return packet is recieved. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Function} failure The function to call when a failure packet was recieved, or when an * error ocurred in the Ajax communication. * The function is passed the following parameters:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax * error ocurred, the failure type will be in {@link #failureType}. The {@link #result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul> */ /** * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference * for the callback functions). */ /** * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait} * during the time the action is being processed. */ /** * The type of action this Action instance performs. * Currently only "submit" and "load" are supported. * @type {String} */ type : 'default', /** * The type of failure detected. See {@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID}, * {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID}, * {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}, {@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE} * @property failureType * @type {String} *//** * The XMLHttpRequest object used to perform the action. * @property response * @type {Object} *//** * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and * other, action-specific properties. * @property result * @type {Object} */ // interface method run : function(options){ }, // interface method success : function(response){ }, // interface method handleResponse : function(response){ }, // default connection failure failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, // private processResponse : function(response){ this.response = response; if(!response.responseText && !response.responseXML){ return true; } this.result = this.handleResponse(response); return this.result; }, // utility functions used internally getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, // private getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, // private getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, // private createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; /** * @class Ext.form.Action.Submit * @extends Ext.form.Action * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s * and processes the returned response.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#submit submit}ting.</p> * <p>A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally * an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error * messages for invalid fields.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: false, errors: { clientCode: "Client not found", portOfLoading: "This field must not be null" } }</code></pre> * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code> errorReader: new Ext.data.XmlReader({ record : 'field', success: '@success' }, [ 'id', 'msg' ] ) </code></pre> * <p>then the results may be sent back in XML format:</p><pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;message success="false"&gt; &lt;errors&gt; &lt;field&gt; &lt;id&gt;clientCode&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;field&gt; &lt;id&gt;portOfLoading&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;/errors&gt; &lt;/message&gt; </code></pre> * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p> */ Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { /** * @cfg {Ext.data.DataReader} errorReader <b>Optional. JSON is interpreted with no need for an errorReader.</b> * <p>A Reader which reads a single record from the returned data. The DataReader's <b>success</b> property specifies * how submission success is determined. The Record's data provides the error messages to apply to any invalid form Fields.</p>. */ /** * @cfg {boolean} clientValidation Determines whether a Form's fields are validated * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission. * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation * is performed. */ type : 'submit', // private run : function(){ var o = this.options; var method = this.getMethod(); var isGet = method == 'GET'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(isGet), method: method, headers: o.headers, params:!isGet ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ // client validation failed this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, // private success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, // private handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++)
} if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); /** * @class Ext.form.Action.Load * @extends Ext.form.Action * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p> * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * {@link Ext.form.BasicForm#load load}ing.</p> * <p>A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and * a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property * contains the values of Fields to load. The individual value object for each Field * is passed to the Field's {@link Ext.form.Field#setValue setValue} method.</p> * <p>By default, response packets are assumed to be JSON, so a typical response * packet may look like this:</p><pre><code> { success: true, data: { clientName: "Fred. Olsen Lines", portOfLoading: "FXT", portOfDischarge: "OSL" } }</code></pre> * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p> */ Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { // private type : 'load', // private run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), headers: this.options.headers, params:this.getParams() })); }, // private success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, // private handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit };
{ var r = rs.records[i]; errors[i] = r.data; }
conditional_block
0003_emailvalidationtoken.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-16 21:51 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user', '0002_profile_validated'), ] operations = [ migrations.CreateModel( name='EmailValidationToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=100, unique=True)), ('expire', models.DateTimeField()), ('consumed', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],
), ]
random_line_split
0003_emailvalidationtoken.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-16 21:51 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user', '0002_profile_validated'), ] operations = [ migrations.CreateModel( name='EmailValidationToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=100, unique=True)), ('expire', models.DateTimeField()), ('consumed', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
identifier_body
0003_emailvalidationtoken.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-16 21:51 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user', '0002_profile_validated'), ] operations = [ migrations.CreateModel( name='EmailValidationToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=100, unique=True)), ('expire', models.DateTimeField()), ('consumed', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
Migration
identifier_name
photo.big.preview.dialogue.ts
import { Component, ElementRef, Renderer2, Input } from '@angular/core'; import { NgIf } from '@angular/common'; import { GenericDlgComponent } from './../dialog/generic.dlg.component'; @Component({ selector: 'photo-big-preview-dlg', templateUrl: './view/photo.big.preview.component.html' }) export class PhotoBigPreviewComponent extends GenericDlgComponent { @Input() _parent:any; private _imgElement:any; constructor(private _element:ElementRef, private _renderer:Renderer2) { super(); this.titleLabel = 'preview~'; } /* -------------------------------- */ /* abstract method implementations */ /* -------------------------------- */ protected buttonOneClick(_e:Event):void { // nothing to do in this case } protected buttonTwoClick(_e:Event):void { // reset flags etc this._resetFlags(); PhotoBigPreviewComponent.hideDlg( this._element.nativeElement.querySelector('#dlgPhotoBigPreview'), this._renderer); } private _getImgElement() { if (!this._imgElement)
return this._imgElement; } /** * clean up on the flag(s) and data for this dialogue */ private _resetFlags() { let _iE:any=this._getImgElement(); if (_iE) { this._renderer.setAttribute(_iE, "src", "", null); } } /** * STATIC method to show the dialog */ public static showPhotoBigPreviewDlg( _e:any, _imgE:any, _renderer:Renderer2, _dataUri:string) { // handle the HTML width too => modal-dialog max-width: 500px; _renderer.setAttribute(_imgE, "src", _dataUri, ""); _renderer.addClass(_e, 'show'); _renderer.setStyle(_e, 'display', 'block'); } }
{ this._imgElement=this._element.nativeElement.querySelector('#imgContent'); }
conditional_block
photo.big.preview.dialogue.ts
import { Component, ElementRef, Renderer2, Input } from '@angular/core'; import { NgIf } from '@angular/common'; import { GenericDlgComponent } from './../dialog/generic.dlg.component'; @Component({ selector: 'photo-big-preview-dlg', templateUrl: './view/photo.big.preview.component.html' }) export class PhotoBigPreviewComponent extends GenericDlgComponent { @Input() _parent:any; private _imgElement:any; constructor(private _element:ElementRef, private _renderer:Renderer2) { super(); this.titleLabel = 'preview~'; } /* -------------------------------- */ /* abstract method implementations */ /* -------------------------------- */ protected
(_e:Event):void { // nothing to do in this case } protected buttonTwoClick(_e:Event):void { // reset flags etc this._resetFlags(); PhotoBigPreviewComponent.hideDlg( this._element.nativeElement.querySelector('#dlgPhotoBigPreview'), this._renderer); } private _getImgElement() { if (!this._imgElement) { this._imgElement=this._element.nativeElement.querySelector('#imgContent'); } return this._imgElement; } /** * clean up on the flag(s) and data for this dialogue */ private _resetFlags() { let _iE:any=this._getImgElement(); if (_iE) { this._renderer.setAttribute(_iE, "src", "", null); } } /** * STATIC method to show the dialog */ public static showPhotoBigPreviewDlg( _e:any, _imgE:any, _renderer:Renderer2, _dataUri:string) { // handle the HTML width too => modal-dialog max-width: 500px; _renderer.setAttribute(_imgE, "src", _dataUri, ""); _renderer.addClass(_e, 'show'); _renderer.setStyle(_e, 'display', 'block'); } }
buttonOneClick
identifier_name
photo.big.preview.dialogue.ts
import { Component, ElementRef, Renderer2, Input } from '@angular/core'; import { NgIf } from '@angular/common'; import { GenericDlgComponent } from './../dialog/generic.dlg.component'; @Component({ selector: 'photo-big-preview-dlg', templateUrl: './view/photo.big.preview.component.html' }) export class PhotoBigPreviewComponent extends GenericDlgComponent { @Input() _parent:any; private _imgElement:any; constructor(private _element:ElementRef, private _renderer:Renderer2) { super(); this.titleLabel = 'preview~'; } /* -------------------------------- */ /* abstract method implementations */ /* -------------------------------- */ protected buttonOneClick(_e:Event):void { // nothing to do in this case } protected buttonTwoClick(_e:Event):void
private _getImgElement() { if (!this._imgElement) { this._imgElement=this._element.nativeElement.querySelector('#imgContent'); } return this._imgElement; } /** * clean up on the flag(s) and data for this dialogue */ private _resetFlags() { let _iE:any=this._getImgElement(); if (_iE) { this._renderer.setAttribute(_iE, "src", "", null); } } /** * STATIC method to show the dialog */ public static showPhotoBigPreviewDlg( _e:any, _imgE:any, _renderer:Renderer2, _dataUri:string) { // handle the HTML width too => modal-dialog max-width: 500px; _renderer.setAttribute(_imgE, "src", _dataUri, ""); _renderer.addClass(_e, 'show'); _renderer.setStyle(_e, 'display', 'block'); } }
{ // reset flags etc this._resetFlags(); PhotoBigPreviewComponent.hideDlg( this._element.nativeElement.querySelector('#dlgPhotoBigPreview'), this._renderer); }
identifier_body
photo.big.preview.dialogue.ts
import { Component, ElementRef, Renderer2, Input } from '@angular/core'; import { NgIf } from '@angular/common'; import { GenericDlgComponent } from './../dialog/generic.dlg.component'; @Component({ selector: 'photo-big-preview-dlg', templateUrl: './view/photo.big.preview.component.html' }) export class PhotoBigPreviewComponent extends GenericDlgComponent { @Input() _parent:any; private _imgElement:any; constructor(private _element:ElementRef, private _renderer:Renderer2) { super(); this.titleLabel = 'preview~'; } /* -------------------------------- */ /* abstract method implementations */ /* -------------------------------- */ protected buttonOneClick(_e:Event):void { // nothing to do in this case } protected buttonTwoClick(_e:Event):void { // reset flags etc this._resetFlags();
this._renderer); } private _getImgElement() { if (!this._imgElement) { this._imgElement=this._element.nativeElement.querySelector('#imgContent'); } return this._imgElement; } /** * clean up on the flag(s) and data for this dialogue */ private _resetFlags() { let _iE:any=this._getImgElement(); if (_iE) { this._renderer.setAttribute(_iE, "src", "", null); } } /** * STATIC method to show the dialog */ public static showPhotoBigPreviewDlg( _e:any, _imgE:any, _renderer:Renderer2, _dataUri:string) { // handle the HTML width too => modal-dialog max-width: 500px; _renderer.setAttribute(_imgE, "src", _dataUri, ""); _renderer.addClass(_e, 'show'); _renderer.setStyle(_e, 'display', 'block'); } }
PhotoBigPreviewComponent.hideDlg( this._element.nativeElement.querySelector('#dlgPhotoBigPreview'),
random_line_split
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({ clean: ['dist'], ts: { default : { options: { compiler: './node_modules/typescript/bin/tsc', module: "commonjs", fast: 'never', preserveConstEnums: true }, src: 'src/**/*.ts', outDir: 'dist' }, watch : { options: { compiler: './node_modules/typescript/bin/tsc', module: "commonjs", fast: 'never', preserveConstEnums: true }, src: 'src/**/*.ts', watch: 'src/', outDir: 'dist' } }, copy: { main: { src: './lib/runtime.d.ts', dest: './dist/runtime.d.ts' } }, bump : { options : { files : ['package.json'], updateConfigs : [], commit : true, commitMessage : 'chore(ver): v%VERSION%', commitFiles : ['package.json', 'CHANGELOG.md'], createTag : true, tagName : 'v%VERSION%', tagMessage : 'chore(ver): v%VERSION%', push : true, pushTo : 'origin', gitDescribeOptions : '--tags --always --abbrev=1 --dirty=-d', globalReplace : false, prereleaseName : "rc", regExp : false } }, shell : { addChangelog : { command : 'git add CHANGELOG.md' } }, changelog : { options : { } } }); grunt.registerTask("release", "Release a new version", function(target) { if(!target) { target = "minor"; } return grunt.task.run("bump-only:" + target, "changelog", "shell:addChangelog", "bump-commit"); }); grunt.registerTask('default', ['ts:default', 'copy']); };
require('load-grunt-tasks')(grunt);
random_line_split
Gruntfile.js
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ clean: ['dist'], ts: { default : { options: { compiler: './node_modules/typescript/bin/tsc', module: "commonjs", fast: 'never', preserveConstEnums: true }, src: 'src/**/*.ts', outDir: 'dist' }, watch : { options: { compiler: './node_modules/typescript/bin/tsc', module: "commonjs", fast: 'never', preserveConstEnums: true }, src: 'src/**/*.ts', watch: 'src/', outDir: 'dist' } }, copy: { main: { src: './lib/runtime.d.ts', dest: './dist/runtime.d.ts' } }, bump : { options : { files : ['package.json'], updateConfigs : [], commit : true, commitMessage : 'chore(ver): v%VERSION%', commitFiles : ['package.json', 'CHANGELOG.md'], createTag : true, tagName : 'v%VERSION%', tagMessage : 'chore(ver): v%VERSION%', push : true, pushTo : 'origin', gitDescribeOptions : '--tags --always --abbrev=1 --dirty=-d', globalReplace : false, prereleaseName : "rc", regExp : false } }, shell : { addChangelog : { command : 'git add CHANGELOG.md' } }, changelog : { options : { } } }); grunt.registerTask("release", "Release a new version", function(target) { if(!target)
return grunt.task.run("bump-only:" + target, "changelog", "shell:addChangelog", "bump-commit"); }); grunt.registerTask('default', ['ts:default', 'copy']); };
{ target = "minor"; }
conditional_block
factories.py
# Copyright (C) 2021 Sebastian Pipping <sebastian@pipping.org> # Licensed under GNU Affero GPL v3 or later from django.utils.timezone import now from factory import LazyFunction, Sequence from factory.django import DjangoModelFactory from ..models import DebianLogIndex, DebianLogMods, DebianPopcon, DebianWnpp, IssueKind class DebianLogIndexFactory(DjangoModelFactory): class Meta: model = DebianLogIndex event_stamp = LazyFunction(now) log_stamp = LazyFunction(now) class DebianLogModsFactory(DjangoModelFactory): class Meta:
class DebianPopconFactory(DjangoModelFactory): class Meta: model = DebianPopcon class DebianWnppFactory(DjangoModelFactory): class Meta: model = DebianWnpp ident = Sequence(int) cron_stamp = LazyFunction(now) mod_stamp = LazyFunction(now) open_stamp = LazyFunction(now) kind = IssueKind.RFA.value # anything that matches the default filters
model = DebianLogMods
identifier_body
factories.py
# Copyright (C) 2021 Sebastian Pipping <sebastian@pipping.org> # Licensed under GNU Affero GPL v3 or later from django.utils.timezone import now from factory import LazyFunction, Sequence from factory.django import DjangoModelFactory from ..models import DebianLogIndex, DebianLogMods, DebianPopcon, DebianWnpp, IssueKind class DebianLogIndexFactory(DjangoModelFactory): class Meta: model = DebianLogIndex event_stamp = LazyFunction(now) log_stamp = LazyFunction(now) class DebianLogModsFactory(DjangoModelFactory): class Meta: model = DebianLogMods class DebianPopconFactory(DjangoModelFactory): class
: model = DebianPopcon class DebianWnppFactory(DjangoModelFactory): class Meta: model = DebianWnpp ident = Sequence(int) cron_stamp = LazyFunction(now) mod_stamp = LazyFunction(now) open_stamp = LazyFunction(now) kind = IssueKind.RFA.value # anything that matches the default filters
Meta
identifier_name
factories.py
# Copyright (C) 2021 Sebastian Pipping <sebastian@pipping.org> # Licensed under GNU Affero GPL v3 or later from django.utils.timezone import now from factory import LazyFunction, Sequence from factory.django import DjangoModelFactory from ..models import DebianLogIndex, DebianLogMods, DebianPopcon, DebianWnpp, IssueKind class DebianLogIndexFactory(DjangoModelFactory): class Meta: model = DebianLogIndex event_stamp = LazyFunction(now) log_stamp = LazyFunction(now) class DebianLogModsFactory(DjangoModelFactory): class Meta: model = DebianLogMods class DebianPopconFactory(DjangoModelFactory): class Meta: model = DebianPopcon class DebianWnppFactory(DjangoModelFactory): class Meta: model = DebianWnpp
mod_stamp = LazyFunction(now) open_stamp = LazyFunction(now) kind = IssueKind.RFA.value # anything that matches the default filters
ident = Sequence(int) cron_stamp = LazyFunction(now)
random_line_split
error.rs
// Copyright 2015-2017 Parity Technologies // // 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. use std::fmt; use std::error::Error as StdError; #[derive(Debug, PartialEq, Eq)] /// Error concerning the RLP decoder. pub enum DecoderError { /// Data has additional bytes at the end of the valid RLP fragment. RlpIsTooBig, /// Data has too few bytes for valid RLP. RlpIsTooShort, /// Expect an encoded list, RLP was something else. RlpExpectedToBeList, /// Expect encoded data, RLP was something else. RlpExpectedToBeData, /// Expected a different size list. RlpIncorrectListLen, /// Data length number has a prefixed zero byte, invalid for numbers. RlpDataLenWithZeroPrefix, /// List length number has a prefixed zero byte, invalid for numbers. RlpListLenWithZeroPrefix, /// Non-canonical (longer than necessary) representation used for data or list. RlpInvalidIndirection, /// Declared length is inconsistent with data specified after. RlpInconsistentLengthAndData, /// Custom rlp decoding error. Custom(&'static str), } impl StdError for DecoderError { fn
(&self) -> &str { "builder error" } } impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } }
description
identifier_name
error.rs
// Copyright 2015-2017 Parity Technologies // // 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. use std::fmt; use std::error::Error as StdError;
#[derive(Debug, PartialEq, Eq)] /// Error concerning the RLP decoder. pub enum DecoderError { /// Data has additional bytes at the end of the valid RLP fragment. RlpIsTooBig, /// Data has too few bytes for valid RLP. RlpIsTooShort, /// Expect an encoded list, RLP was something else. RlpExpectedToBeList, /// Expect encoded data, RLP was something else. RlpExpectedToBeData, /// Expected a different size list. RlpIncorrectListLen, /// Data length number has a prefixed zero byte, invalid for numbers. RlpDataLenWithZeroPrefix, /// List length number has a prefixed zero byte, invalid for numbers. RlpListLenWithZeroPrefix, /// Non-canonical (longer than necessary) representation used for data or list. RlpInvalidIndirection, /// Declared length is inconsistent with data specified after. RlpInconsistentLengthAndData, /// Custom rlp decoding error. Custom(&'static str), } impl StdError for DecoderError { fn description(&self) -> &str { "builder error" } } impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self, f) } }
random_line_split
utility.rs
// Copyright 2016 Kyle Mayes // // 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. //! Various utilities. use std::cell::{RefCell}; use std::rc::{Rc}; use rustc_errors::{DiagnosticBuilder, FatalError, Handler, Level}; use rustc_errors::emitter::{Emitter}; use syntax::ext::tt::transcribe; use syntax::ast::*; use syntax::codemap::{CodeMap, Span, DUMMY_SP}; use syntax::parse::{ParseSess, PResult}; use syntax::parse::common::{SeqSep}; use syntax::parse::lexer::{Reader, TokenAndSpan}; use syntax::parse::parser::{Parser, PathStyle}; use syntax::parse::token::{BinOpToken, Token}; use syntax::ptr::{P}; use syntax::tokenstream::{Delimited, TokenTree}; /// A result type for reporting errors in plugins. pub type PluginResult<T> = Result<T, (Span, String)>; //================================================ // Macros //================================================ // parse! _______________________________________ /// Defines a parsing method for `TransactionParser` that parses a particular AST entity. macro_rules! parse { ($name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected($description, name, |p| p.$name($($argument), *)) } }; (OPTION: $name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected_option($description, name, |p| p.$name($($argument), *)) } }; } //================================================ // Structs //================================================ // SaveEmitter ___________________________________ /// The most recent fatal parsing error, if any. thread_local! { static ERROR: RefCell<Option<(Span, String)>> = RefCell::default() } /// A diagnostic emitter that saves fatal parsing errors to a thread local variable. struct SaveEmitter; impl SaveEmitter { //- Static ----------------------------------- /// Returns the last fatal parsing error. fn get_error() -> (Span, String) { ERROR.with(|e| e.borrow().clone().unwrap_or_else(|| (DUMMY_SP, "no error".into()))) } } impl Emitter for SaveEmitter { fn emit(&mut self, builder: &DiagnosticBuilder) { if builder.level == Level::Fatal { let span = builder.span.primary_span().unwrap_or(DUMMY_SP); ERROR.with(|e| *e.borrow_mut() = Some((span, builder.message.clone()))); } } } // TokenReader ___________________________________ /// A `Reader` that wraps a slice of `TokenAndSpan`s. #[derive(Clone)] struct TokenReader<'s> { session: &'s ParseSess, tokens: &'s [TokenAndSpan], index: usize, } impl<'s> TokenReader<'s> { //- Constructors ----------------------------- /// Constructs a new `TokenReader`. fn new(session: &'s ParseSess, tokens: &'s [TokenAndSpan]) -> TokenReader<'s> { TokenReader { session: session, tokens: tokens, index: 0 } } } impl<'s> Reader for TokenReader<'s> { fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { let next = self.tokens[self.index].clone(); if !self.is_eof() { self.index += 1; } Ok(next) } fn fatal(&self, _: &str) -> FatalError { unreachable!() } fn err(&self, _: &str) { } fn emit_fatal_errors(&mut self) { } fn peek(&self) -> TokenAndSpan { self.tokens[self.index].clone() } } // Transaction ___________________________________ /// A parser transaction. pub struct Transaction(usize); impl Transaction { //- Accessors --------------------------------- /// Resets the parser to the state it was in when this transaction was created. pub fn rollback(&self, parser: &mut TransactionParser) { parser.index = self.0; } } // TransactionParser _____________________________ /// A wrapper around a `Parser` which allows for rolling back parsing actions. #[allow(missing_debug_implementations)] pub struct TransactionParser { session: ParseSess, tokens: Vec<TokenAndSpan>, index: usize, span: Span, } impl TransactionParser { //- Constructors ----------------------------- /// Constructs a new `TransactionParser`. pub fn new(session: &ParseSess, tts: &[TokenTree]) -> TransactionParser { let handler = Handler::with_emitter(false, false, Box::new(SaveEmitter)); let mut codemap = CodeMap::new(); codemap.files = session.codemap().files.clone(); TransactionParser { session: ParseSess::with_span_handler(handler, Rc::new(codemap)), tokens: flatten_tts(session, tts), index: 0, span: span_tts(tts), } } //- Accessors -------------------------------- /// Returns the span of current token. pub fn get_span(&self) -> Span { self.tokens.get(self.index).map_or(self.span, |t| t.sp) } /// Returns the span of the last token processed. pub fn get_last_span(&self) -> Span { self.tokens.get(self.index.saturating_sub(1)).map_or(self.span, |t| t.sp) } /// Returns whether the current token is the EOF token. fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } /// Returns the span of the remaining tokens, if any. pub fn get_remainder_span(&self) -> Option<Span> { if self.is_eof() { None } else { Some(span_spans(self.get_span(), self.span)) } } /// Creates a new transaction which saves the current state of this parser. pub fn transaction(&self) -> Transaction { Transaction(self.index) } /// Returns a parsing error. fn get_error(&self, mut span: Span, description: &str, name: Option<&str>) -> (Span, String) { let mut message = if let Some(name) = name { format!("expected {}: '{}'", description, name) } else { format!("expected {}", description) }; if self.is_eof() { span = self.span; message = format!("unexpected end of arguments: {}", message); } (span, message) } //- Mutators --------------------------------- /// Applies a parsing action to this parser, returning the result of the action. #[cfg_attr(feature="clippy", allow(needless_lifetimes))] pub fn apply<'s, T, F: FnOnce(&mut Parser<'s>) -> T>(&'s mut self, f: F) -> (Span, T) { let reader = TokenReader::new(&self.session, &self.tokens[self.index..]); let mut parser = Parser::new(&self.session, Box::new(reader), None, false); let start = self.get_span(); let result = f(&mut parser); self.index += parser.tokens_consumed; let end = self.get_last_span(); (span_spans(start, end), result) } /// Attempts to consume the supplied token, returning whether a token was consumed. pub fn eat(&mut self, token: &Token) -> bool { self.apply(|p| p.eat(token)).1 } /// Returns the next token. pub fn next_token( &mut self, description: &str, name: Option<&str> ) -> PluginResult<(Span, Token)> { match self.tokens[self.index].tok.clone() { Token::Eof => Err(self.get_error(DUMMY_SP, description, name)), token => { self.index += 1; Ok((self.get_last_span(), token)) }, } } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, T>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(value)) => return Ok((span, value)), (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected_option<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, Option<T>>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(Some(value))) => return Ok((span, value)), (span, Ok(_)) => { span }, (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } parse!(parse_attribute(true), "attribute", Attribute); parse!(parse_block(), "block", P<Block>); parse!(parse_expr(), "expression", P<Expr>); parse!(parse_ident(), "identifier", Ident); parse!(OPTION: parse_item(), "item", P<Item>); parse!(parse_lifetime(), "lifetime", Lifetime); parse!(parse_lit(), "literal", Lit); parse!(parse_meta_item(), "meta item", MetaItem); parse!(parse_pat(), "pattern", P<Pat>); parse!(parse_path(PathStyle::Type), "path", Path); parse!(OPTION: parse_stmt(), "statement", Stmt); parse!(parse_ty(), "type", P<Ty>); parse!(parse_token_tree(), "token tree", TokenTree); pub fn parse_binop(&mut self, name: &str) -> PluginResult<(Span, BinOpToken)> { match try!(self.next_token("binary operator", Some(name))) { (span, Token::BinOp(binop)) | (span, Token::BinOpEq(binop)) => Ok((span, binop)), (span, _) => Err((span, "expected binary operator".into())), } } pub fn parse_delim(&mut self, name: &str) -> PluginResult<(Span, Delimited)> { let (start, delim) = match try!(self.next_token("opening delimiter", Some(name))) { (span, Token::OpenDelim(delim)) => (span, delim), (span, _) => return Err((span, "expected opening delimiter".into())), };
let end = self.get_last_span(); let delimited = Delimited { delim: delim, open_span: start, tts: try!(tts), close_span: end, }; Ok((span_spans(start, end), delimited)) } pub fn parse_token(&mut self, name: &str) -> PluginResult<(Span, Token)> { self.next_token("token", Some(name)) } } //================================================ // Functions //================================================ /// Flattens the supplied token trees. fn flatten_tts(session: &ParseSess, tts: &[TokenTree]) -> Vec<TokenAndSpan> { let mut reader = transcribe::new_tt_reader(&session.span_diagnostic, None, tts.into()); let mut tokens = vec![]; while reader.peek().tok != Token::Eof { tokens.push(reader.next_token()); } tokens.push(reader.next_token()); tokens } /// Returns a span that spans the supplied spans. pub fn span_spans(start: Span, end: Span) -> Span { Span { lo: start.lo, hi: end.hi, expn_id: start.expn_id } } /// Returns a span that spans all of the supplied token trees. pub fn span_tts(tts: &[TokenTree]) -> Span { let start = tts.get(0).map_or(DUMMY_SP, TokenTree::get_span); let end = tts.iter().last().map_or(DUMMY_SP, TokenTree::get_span); span_spans(start, end) }
let tts = self.apply(|p| { let sep = SeqSep { sep: None, trailing_sep_allowed: false }; p.parse_seq_to_end(&Token::CloseDelim(delim), sep, |p| p.parse_token_tree()) }).1.map_err(|mut err| { err.cancel(); SaveEmitter::get_error() });
random_line_split
utility.rs
// Copyright 2016 Kyle Mayes // // 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. //! Various utilities. use std::cell::{RefCell}; use std::rc::{Rc}; use rustc_errors::{DiagnosticBuilder, FatalError, Handler, Level}; use rustc_errors::emitter::{Emitter}; use syntax::ext::tt::transcribe; use syntax::ast::*; use syntax::codemap::{CodeMap, Span, DUMMY_SP}; use syntax::parse::{ParseSess, PResult}; use syntax::parse::common::{SeqSep}; use syntax::parse::lexer::{Reader, TokenAndSpan}; use syntax::parse::parser::{Parser, PathStyle}; use syntax::parse::token::{BinOpToken, Token}; use syntax::ptr::{P}; use syntax::tokenstream::{Delimited, TokenTree}; /// A result type for reporting errors in plugins. pub type PluginResult<T> = Result<T, (Span, String)>; //================================================ // Macros //================================================ // parse! _______________________________________ /// Defines a parsing method for `TransactionParser` that parses a particular AST entity. macro_rules! parse { ($name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected($description, name, |p| p.$name($($argument), *)) } }; (OPTION: $name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected_option($description, name, |p| p.$name($($argument), *)) } }; } //================================================ // Structs //================================================ // SaveEmitter ___________________________________ /// The most recent fatal parsing error, if any. thread_local! { static ERROR: RefCell<Option<(Span, String)>> = RefCell::default() } /// A diagnostic emitter that saves fatal parsing errors to a thread local variable. struct SaveEmitter; impl SaveEmitter { //- Static ----------------------------------- /// Returns the last fatal parsing error. fn get_error() -> (Span, String) { ERROR.with(|e| e.borrow().clone().unwrap_or_else(|| (DUMMY_SP, "no error".into()))) } } impl Emitter for SaveEmitter { fn emit(&mut self, builder: &DiagnosticBuilder) { if builder.level == Level::Fatal { let span = builder.span.primary_span().unwrap_or(DUMMY_SP); ERROR.with(|e| *e.borrow_mut() = Some((span, builder.message.clone()))); } } } // TokenReader ___________________________________ /// A `Reader` that wraps a slice of `TokenAndSpan`s. #[derive(Clone)] struct TokenReader<'s> { session: &'s ParseSess, tokens: &'s [TokenAndSpan], index: usize, } impl<'s> TokenReader<'s> { //- Constructors ----------------------------- /// Constructs a new `TokenReader`. fn new(session: &'s ParseSess, tokens: &'s [TokenAndSpan]) -> TokenReader<'s> { TokenReader { session: session, tokens: tokens, index: 0 } } } impl<'s> Reader for TokenReader<'s> { fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { let next = self.tokens[self.index].clone(); if !self.is_eof() { self.index += 1; } Ok(next) } fn fatal(&self, _: &str) -> FatalError { unreachable!() } fn err(&self, _: &str) { } fn emit_fatal_errors(&mut self) { } fn peek(&self) -> TokenAndSpan { self.tokens[self.index].clone() } } // Transaction ___________________________________ /// A parser transaction. pub struct Transaction(usize); impl Transaction { //- Accessors --------------------------------- /// Resets the parser to the state it was in when this transaction was created. pub fn rollback(&self, parser: &mut TransactionParser) { parser.index = self.0; } } // TransactionParser _____________________________ /// A wrapper around a `Parser` which allows for rolling back parsing actions. #[allow(missing_debug_implementations)] pub struct TransactionParser { session: ParseSess, tokens: Vec<TokenAndSpan>, index: usize, span: Span, } impl TransactionParser { //- Constructors ----------------------------- /// Constructs a new `TransactionParser`. pub fn new(session: &ParseSess, tts: &[TokenTree]) -> TransactionParser { let handler = Handler::with_emitter(false, false, Box::new(SaveEmitter)); let mut codemap = CodeMap::new(); codemap.files = session.codemap().files.clone(); TransactionParser { session: ParseSess::with_span_handler(handler, Rc::new(codemap)), tokens: flatten_tts(session, tts), index: 0, span: span_tts(tts), } } //- Accessors -------------------------------- /// Returns the span of current token. pub fn get_span(&self) -> Span { self.tokens.get(self.index).map_or(self.span, |t| t.sp) } /// Returns the span of the last token processed. pub fn get_last_span(&self) -> Span { self.tokens.get(self.index.saturating_sub(1)).map_or(self.span, |t| t.sp) } /// Returns whether the current token is the EOF token. fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } /// Returns the span of the remaining tokens, if any. pub fn get_remainder_span(&self) -> Option<Span> { if self.is_eof() { None } else { Some(span_spans(self.get_span(), self.span)) } } /// Creates a new transaction which saves the current state of this parser. pub fn transaction(&self) -> Transaction { Transaction(self.index) } /// Returns a parsing error. fn get_error(&self, mut span: Span, description: &str, name: Option<&str>) -> (Span, String) { let mut message = if let Some(name) = name { format!("expected {}: '{}'", description, name) } else { format!("expected {}", description) }; if self.is_eof() { span = self.span; message = format!("unexpected end of arguments: {}", message); } (span, message) } //- Mutators --------------------------------- /// Applies a parsing action to this parser, returning the result of the action. #[cfg_attr(feature="clippy", allow(needless_lifetimes))] pub fn apply<'s, T, F: FnOnce(&mut Parser<'s>) -> T>(&'s mut self, f: F) -> (Span, T) { let reader = TokenReader::new(&self.session, &self.tokens[self.index..]); let mut parser = Parser::new(&self.session, Box::new(reader), None, false); let start = self.get_span(); let result = f(&mut parser); self.index += parser.tokens_consumed; let end = self.get_last_span(); (span_spans(start, end), result) } /// Attempts to consume the supplied token, returning whether a token was consumed. pub fn eat(&mut self, token: &Token) -> bool { self.apply(|p| p.eat(token)).1 } /// Returns the next token. pub fn next_token( &mut self, description: &str, name: Option<&str> ) -> PluginResult<(Span, Token)> { match self.tokens[self.index].tok.clone() { Token::Eof => Err(self.get_error(DUMMY_SP, description, name)), token => { self.index += 1; Ok((self.get_last_span(), token)) }, } } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, T>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(value)) => return Ok((span, value)), (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected_option<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, Option<T>>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(Some(value))) => return Ok((span, value)), (span, Ok(_)) => { span }, (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } parse!(parse_attribute(true), "attribute", Attribute); parse!(parse_block(), "block", P<Block>); parse!(parse_expr(), "expression", P<Expr>); parse!(parse_ident(), "identifier", Ident); parse!(OPTION: parse_item(), "item", P<Item>); parse!(parse_lifetime(), "lifetime", Lifetime); parse!(parse_lit(), "literal", Lit); parse!(parse_meta_item(), "meta item", MetaItem); parse!(parse_pat(), "pattern", P<Pat>); parse!(parse_path(PathStyle::Type), "path", Path); parse!(OPTION: parse_stmt(), "statement", Stmt); parse!(parse_ty(), "type", P<Ty>); parse!(parse_token_tree(), "token tree", TokenTree); pub fn parse_binop(&mut self, name: &str) -> PluginResult<(Span, BinOpToken)> { match try!(self.next_token("binary operator", Some(name))) { (span, Token::BinOp(binop)) | (span, Token::BinOpEq(binop)) => Ok((span, binop)), (span, _) => Err((span, "expected binary operator".into())), } } pub fn
(&mut self, name: &str) -> PluginResult<(Span, Delimited)> { let (start, delim) = match try!(self.next_token("opening delimiter", Some(name))) { (span, Token::OpenDelim(delim)) => (span, delim), (span, _) => return Err((span, "expected opening delimiter".into())), }; let tts = self.apply(|p| { let sep = SeqSep { sep: None, trailing_sep_allowed: false }; p.parse_seq_to_end(&Token::CloseDelim(delim), sep, |p| p.parse_token_tree()) }).1.map_err(|mut err| { err.cancel(); SaveEmitter::get_error() }); let end = self.get_last_span(); let delimited = Delimited { delim: delim, open_span: start, tts: try!(tts), close_span: end, }; Ok((span_spans(start, end), delimited)) } pub fn parse_token(&mut self, name: &str) -> PluginResult<(Span, Token)> { self.next_token("token", Some(name)) } } //================================================ // Functions //================================================ /// Flattens the supplied token trees. fn flatten_tts(session: &ParseSess, tts: &[TokenTree]) -> Vec<TokenAndSpan> { let mut reader = transcribe::new_tt_reader(&session.span_diagnostic, None, tts.into()); let mut tokens = vec![]; while reader.peek().tok != Token::Eof { tokens.push(reader.next_token()); } tokens.push(reader.next_token()); tokens } /// Returns a span that spans the supplied spans. pub fn span_spans(start: Span, end: Span) -> Span { Span { lo: start.lo, hi: end.hi, expn_id: start.expn_id } } /// Returns a span that spans all of the supplied token trees. pub fn span_tts(tts: &[TokenTree]) -> Span { let start = tts.get(0).map_or(DUMMY_SP, TokenTree::get_span); let end = tts.iter().last().map_or(DUMMY_SP, TokenTree::get_span); span_spans(start, end) }
parse_delim
identifier_name
utility.rs
// Copyright 2016 Kyle Mayes // // 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. //! Various utilities. use std::cell::{RefCell}; use std::rc::{Rc}; use rustc_errors::{DiagnosticBuilder, FatalError, Handler, Level}; use rustc_errors::emitter::{Emitter}; use syntax::ext::tt::transcribe; use syntax::ast::*; use syntax::codemap::{CodeMap, Span, DUMMY_SP}; use syntax::parse::{ParseSess, PResult}; use syntax::parse::common::{SeqSep}; use syntax::parse::lexer::{Reader, TokenAndSpan}; use syntax::parse::parser::{Parser, PathStyle}; use syntax::parse::token::{BinOpToken, Token}; use syntax::ptr::{P}; use syntax::tokenstream::{Delimited, TokenTree}; /// A result type for reporting errors in plugins. pub type PluginResult<T> = Result<T, (Span, String)>; //================================================ // Macros //================================================ // parse! _______________________________________ /// Defines a parsing method for `TransactionParser` that parses a particular AST entity. macro_rules! parse { ($name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected($description, name, |p| p.$name($($argument), *)) } }; (OPTION: $name:ident($($argument:expr), *)$(.$method:ident())*, $description:expr, $ty:ty) => { pub fn $name(&mut self, name: &str) -> PluginResult<(Span, $ty)> { self.parse_expected_option($description, name, |p| p.$name($($argument), *)) } }; } //================================================ // Structs //================================================ // SaveEmitter ___________________________________ /// The most recent fatal parsing error, if any. thread_local! { static ERROR: RefCell<Option<(Span, String)>> = RefCell::default() } /// A diagnostic emitter that saves fatal parsing errors to a thread local variable. struct SaveEmitter; impl SaveEmitter { //- Static ----------------------------------- /// Returns the last fatal parsing error. fn get_error() -> (Span, String) { ERROR.with(|e| e.borrow().clone().unwrap_or_else(|| (DUMMY_SP, "no error".into()))) } } impl Emitter for SaveEmitter { fn emit(&mut self, builder: &DiagnosticBuilder) { if builder.level == Level::Fatal { let span = builder.span.primary_span().unwrap_or(DUMMY_SP); ERROR.with(|e| *e.borrow_mut() = Some((span, builder.message.clone()))); } } } // TokenReader ___________________________________ /// A `Reader` that wraps a slice of `TokenAndSpan`s. #[derive(Clone)] struct TokenReader<'s> { session: &'s ParseSess, tokens: &'s [TokenAndSpan], index: usize, } impl<'s> TokenReader<'s> { //- Constructors ----------------------------- /// Constructs a new `TokenReader`. fn new(session: &'s ParseSess, tokens: &'s [TokenAndSpan]) -> TokenReader<'s> { TokenReader { session: session, tokens: tokens, index: 0 } } } impl<'s> Reader for TokenReader<'s> { fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { let next = self.tokens[self.index].clone(); if !self.is_eof() { self.index += 1; } Ok(next) } fn fatal(&self, _: &str) -> FatalError { unreachable!() } fn err(&self, _: &str) { } fn emit_fatal_errors(&mut self) { } fn peek(&self) -> TokenAndSpan { self.tokens[self.index].clone() } } // Transaction ___________________________________ /// A parser transaction. pub struct Transaction(usize); impl Transaction { //- Accessors --------------------------------- /// Resets the parser to the state it was in when this transaction was created. pub fn rollback(&self, parser: &mut TransactionParser) { parser.index = self.0; } } // TransactionParser _____________________________ /// A wrapper around a `Parser` which allows for rolling back parsing actions. #[allow(missing_debug_implementations)] pub struct TransactionParser { session: ParseSess, tokens: Vec<TokenAndSpan>, index: usize, span: Span, } impl TransactionParser { //- Constructors ----------------------------- /// Constructs a new `TransactionParser`. pub fn new(session: &ParseSess, tts: &[TokenTree]) -> TransactionParser { let handler = Handler::with_emitter(false, false, Box::new(SaveEmitter)); let mut codemap = CodeMap::new(); codemap.files = session.codemap().files.clone(); TransactionParser { session: ParseSess::with_span_handler(handler, Rc::new(codemap)), tokens: flatten_tts(session, tts), index: 0, span: span_tts(tts), } } //- Accessors -------------------------------- /// Returns the span of current token. pub fn get_span(&self) -> Span { self.tokens.get(self.index).map_or(self.span, |t| t.sp) } /// Returns the span of the last token processed. pub fn get_last_span(&self) -> Span { self.tokens.get(self.index.saturating_sub(1)).map_or(self.span, |t| t.sp) } /// Returns whether the current token is the EOF token. fn is_eof(&self) -> bool { self.index + 1 >= self.tokens.len() } /// Returns the span of the remaining tokens, if any. pub fn get_remainder_span(&self) -> Option<Span>
/// Creates a new transaction which saves the current state of this parser. pub fn transaction(&self) -> Transaction { Transaction(self.index) } /// Returns a parsing error. fn get_error(&self, mut span: Span, description: &str, name: Option<&str>) -> (Span, String) { let mut message = if let Some(name) = name { format!("expected {}: '{}'", description, name) } else { format!("expected {}", description) }; if self.is_eof() { span = self.span; message = format!("unexpected end of arguments: {}", message); } (span, message) } //- Mutators --------------------------------- /// Applies a parsing action to this parser, returning the result of the action. #[cfg_attr(feature="clippy", allow(needless_lifetimes))] pub fn apply<'s, T, F: FnOnce(&mut Parser<'s>) -> T>(&'s mut self, f: F) -> (Span, T) { let reader = TokenReader::new(&self.session, &self.tokens[self.index..]); let mut parser = Parser::new(&self.session, Box::new(reader), None, false); let start = self.get_span(); let result = f(&mut parser); self.index += parser.tokens_consumed; let end = self.get_last_span(); (span_spans(start, end), result) } /// Attempts to consume the supplied token, returning whether a token was consumed. pub fn eat(&mut self, token: &Token) -> bool { self.apply(|p| p.eat(token)).1 } /// Returns the next token. pub fn next_token( &mut self, description: &str, name: Option<&str> ) -> PluginResult<(Span, Token)> { match self.tokens[self.index].tok.clone() { Token::Eof => Err(self.get_error(DUMMY_SP, description, name)), token => { self.index += 1; Ok((self.get_last_span(), token)) }, } } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, T>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(value)) => return Ok((span, value)), (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } /// Applies a parsing action to this parser, returning the result of the action. fn parse_expected_option<'s, T, F: FnOnce(&mut Parser<'s>) -> PResult<'s, Option<T>>>( &'s mut self, description: &str, name: &str, f: F ) -> PluginResult<(Span, T)> { let this: *const TransactionParser = self as *const TransactionParser; let span = match self.apply(f) { (span, Ok(Some(value))) => return Ok((span, value)), (span, Ok(_)) => { span }, (span, Err(mut err)) => { err.cancel(); span }, }; // FIXME: hack to get around mutable borrow bug let error = unsafe { (*this).get_error(span, description, Some(name)) }; Err(error) } parse!(parse_attribute(true), "attribute", Attribute); parse!(parse_block(), "block", P<Block>); parse!(parse_expr(), "expression", P<Expr>); parse!(parse_ident(), "identifier", Ident); parse!(OPTION: parse_item(), "item", P<Item>); parse!(parse_lifetime(), "lifetime", Lifetime); parse!(parse_lit(), "literal", Lit); parse!(parse_meta_item(), "meta item", MetaItem); parse!(parse_pat(), "pattern", P<Pat>); parse!(parse_path(PathStyle::Type), "path", Path); parse!(OPTION: parse_stmt(), "statement", Stmt); parse!(parse_ty(), "type", P<Ty>); parse!(parse_token_tree(), "token tree", TokenTree); pub fn parse_binop(&mut self, name: &str) -> PluginResult<(Span, BinOpToken)> { match try!(self.next_token("binary operator", Some(name))) { (span, Token::BinOp(binop)) | (span, Token::BinOpEq(binop)) => Ok((span, binop)), (span, _) => Err((span, "expected binary operator".into())), } } pub fn parse_delim(&mut self, name: &str) -> PluginResult<(Span, Delimited)> { let (start, delim) = match try!(self.next_token("opening delimiter", Some(name))) { (span, Token::OpenDelim(delim)) => (span, delim), (span, _) => return Err((span, "expected opening delimiter".into())), }; let tts = self.apply(|p| { let sep = SeqSep { sep: None, trailing_sep_allowed: false }; p.parse_seq_to_end(&Token::CloseDelim(delim), sep, |p| p.parse_token_tree()) }).1.map_err(|mut err| { err.cancel(); SaveEmitter::get_error() }); let end = self.get_last_span(); let delimited = Delimited { delim: delim, open_span: start, tts: try!(tts), close_span: end, }; Ok((span_spans(start, end), delimited)) } pub fn parse_token(&mut self, name: &str) -> PluginResult<(Span, Token)> { self.next_token("token", Some(name)) } } //================================================ // Functions //================================================ /// Flattens the supplied token trees. fn flatten_tts(session: &ParseSess, tts: &[TokenTree]) -> Vec<TokenAndSpan> { let mut reader = transcribe::new_tt_reader(&session.span_diagnostic, None, tts.into()); let mut tokens = vec![]; while reader.peek().tok != Token::Eof { tokens.push(reader.next_token()); } tokens.push(reader.next_token()); tokens } /// Returns a span that spans the supplied spans. pub fn span_spans(start: Span, end: Span) -> Span { Span { lo: start.lo, hi: end.hi, expn_id: start.expn_id } } /// Returns a span that spans all of the supplied token trees. pub fn span_tts(tts: &[TokenTree]) -> Span { let start = tts.get(0).map_or(DUMMY_SP, TokenTree::get_span); let end = tts.iter().last().map_or(DUMMY_SP, TokenTree::get_span); span_spans(start, end) }
{ if self.is_eof() { None } else { Some(span_spans(self.get_span(), self.span)) } }
identifier_body
test.ts
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/zone-testing'; import {getTestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; declare const require: any; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); // Then we find all the tests. const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context);
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
random_line_split
createDB.py
import sqlite3 import sys import os def
(): sane = 1 while sane == 1: print "[ - ] Please enter absolute path to cred. database to be created: " in_path = raw_input() if os.path.exists(in_path): os.system('cls' if os.name == 'nt' else 'clear') print "[ - ] Invalid path, try again." else: sane = 0 return(in_path) def main(dbPath): createQ = "CREATE TABLE "+'"main"'+" ('pri_Index' INTEGER PRIMARY KEY AUTOINCREMENT, 'identifier' TEXT , 'clearTextP' TEXT , 'srcMD5' TEXT , 'srcSHA1' TEXT , 'srcBCRYPT' TEXT , 'rainTableMD5' TEXT , 'rainTableSHA1' TEXT , 'rainTableBCRYPT' TEXT)" try: db_conn = sqlite3.connect(dbPath) except: print "[ - ] Unable to create, check path and try again." sys.exit(1) cur = db_conn.cursor() cur.execute(createQ) print "[ - ] DB created at "+dbPath+"\nPress enter to exit." end = raw_input() try: main(menu()) except KeyboardInterrupt: print "[ - ] CTRL+C caught, exiting."
menu
identifier_name
createDB.py
import sqlite3 import sys import os def menu(): sane = 1 while sane == 1: print "[ - ] Please enter absolute path to cred. database to be created: " in_path = raw_input() if os.path.exists(in_path): os.system('cls' if os.name == 'nt' else 'clear') print "[ - ] Invalid path, try again." else: sane = 0 return(in_path)
print "[ - ] Unable to create, check path and try again." sys.exit(1) cur = db_conn.cursor() cur.execute(createQ) print "[ - ] DB created at "+dbPath+"\nPress enter to exit." end = raw_input() try: main(menu()) except KeyboardInterrupt: print "[ - ] CTRL+C caught, exiting."
def main(dbPath): createQ = "CREATE TABLE "+'"main"'+" ('pri_Index' INTEGER PRIMARY KEY AUTOINCREMENT, 'identifier' TEXT , 'clearTextP' TEXT , 'srcMD5' TEXT , 'srcSHA1' TEXT , 'srcBCRYPT' TEXT , 'rainTableMD5' TEXT , 'rainTableSHA1' TEXT , 'rainTableBCRYPT' TEXT)" try: db_conn = sqlite3.connect(dbPath) except:
random_line_split
createDB.py
import sqlite3 import sys import os def menu(): sane = 1 while sane == 1: print "[ - ] Please enter absolute path to cred. database to be created: " in_path = raw_input() if os.path.exists(in_path): os.system('cls' if os.name == 'nt' else 'clear') print "[ - ] Invalid path, try again." else:
return(in_path) def main(dbPath): createQ = "CREATE TABLE "+'"main"'+" ('pri_Index' INTEGER PRIMARY KEY AUTOINCREMENT, 'identifier' TEXT , 'clearTextP' TEXT , 'srcMD5' TEXT , 'srcSHA1' TEXT , 'srcBCRYPT' TEXT , 'rainTableMD5' TEXT , 'rainTableSHA1' TEXT , 'rainTableBCRYPT' TEXT)" try: db_conn = sqlite3.connect(dbPath) except: print "[ - ] Unable to create, check path and try again." sys.exit(1) cur = db_conn.cursor() cur.execute(createQ) print "[ - ] DB created at "+dbPath+"\nPress enter to exit." end = raw_input() try: main(menu()) except KeyboardInterrupt: print "[ - ] CTRL+C caught, exiting."
sane = 0
conditional_block
createDB.py
import sqlite3 import sys import os def menu():
def main(dbPath): createQ = "CREATE TABLE "+'"main"'+" ('pri_Index' INTEGER PRIMARY KEY AUTOINCREMENT, 'identifier' TEXT , 'clearTextP' TEXT , 'srcMD5' TEXT , 'srcSHA1' TEXT , 'srcBCRYPT' TEXT , 'rainTableMD5' TEXT , 'rainTableSHA1' TEXT , 'rainTableBCRYPT' TEXT)" try: db_conn = sqlite3.connect(dbPath) except: print "[ - ] Unable to create, check path and try again." sys.exit(1) cur = db_conn.cursor() cur.execute(createQ) print "[ - ] DB created at "+dbPath+"\nPress enter to exit." end = raw_input() try: main(menu()) except KeyboardInterrupt: print "[ - ] CTRL+C caught, exiting."
sane = 1 while sane == 1: print "[ - ] Please enter absolute path to cred. database to be created: " in_path = raw_input() if os.path.exists(in_path): os.system('cls' if os.name == 'nt' else 'clear') print "[ - ] Invalid path, try again." else: sane = 0 return(in_path)
identifier_body
jquery.calendario.js
/** * jquery.calendario.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2012, Codrops * http://www.codrops.com */ ;( function( $, window, undefined ) { 'use strict'; $.Calendario = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.Calendario.defaults = { /* you can also pass: month : initialize calendar with this month (1-12). Default is today. year : initialize calendar with this year. Default is today. caldata : initial data/content for the calendar. caldata format: { 'MM-DD-YYYY' : 'HTML Content', 'MM-DD-YYYY' : 'HTML Content', 'MM-DD-YYYY' : 'HTML Content' ... } */ weeks : [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], weekabbrs : [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ], months : [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthabbrs : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], // choose between values in options.weeks or options.weekabbrs displayWeekAbbr : false, // choose between values in options.months or options.monthabbrs displayMonthAbbr : false, // left most day in the calendar // 0 - Sunday, 1 - Monday, ... , 6 - Saturday startIn : 1, onDayClick : function( $el, $content, dateProperties ) { return false; } }; $.Calendario.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.Calendario.defaults, options ); this.today = new Date(); this.month = ( isNaN( this.options.month ) || this.options.month == null) ? this.today.getMonth() : this.options.month - 1; this.year = ( isNaN( this.options.year ) || this.options.year == null) ? this.today.getFullYear() : this.options.year; this.caldata = this.options.caldata || {}; this._generateTemplate(); this._initEvents(); }, _initEvents : function() { var self = this; this.$el.on( 'click.calendario', 'div.fc-row > div', function() { var $cell = $( this ), idx = $cell.index(), $content = $cell.children( 'div' ), dateProp = { day : $cell.children( 'span.fc-date' ).text(), month : self.month + 1, monthname : self.options.displayMonthAbbr ? self.options.monthabbrs[ self.month ] : self.options.months[ self.month ], year : self.year, weekday : idx + self.options.startIn, weekdayname : self.options.weeks[ idx + self.options.startIn ] }; if( dateProp.day ) { self.options.onDayClick( $cell, $content, dateProp ); } } ); }, // Calendar logic based on http://jszen.blogspot.pt/2007/03/how-to-build-simple-calendar-with.html _generateTemplate : function( callback ) { var head = this._getHead(), body = this._getBody(), rowClass; switch( this.rowTotal ) { case 4 : rowClass = 'fc-four-rows'; break; case 5 : rowClass = 'fc-five-rows'; break; case 6 : rowClass = 'fc-six-rows'; break; } this.$cal = $( '<div class="fc-calendar ' + rowClass + '">' ).append( head, body ); this.$el.find( 'div.fc-calendar' ).remove().end().append( this.$cal ); if( callback ) { callback.call(); } }, _getHead : function() { var html = '<div class="fc-head">'; for ( var i = 0; i <= 6; i++ ) { var pos = i + this.options.startIn, j = pos > 6 ? pos - 6 - 1 : pos; html += '<div>'; html += this.options.displayWeekAbbr ? this.options.weekabbrs[ j ] : this.options.weeks[ j ]; html += '</div>'; } html += '</div>'; return html; }, _getBody : function() { var d = new Date( this.year, this.month + 1, 0 ), // number of days in the month monthLength = d.getDate(), firstDay = new Date( this.year, this.month, 1 ); // day of the week this.startingDay = firstDay.getDay(); var html = '<div class="fc-body clearfix"><div class="fc-row">', // fill in the days day = 1; // this loop is for weeks (rows) for ( var i = 0; i < 7; i++ ) { // this loop is for weekdays (cells) for ( var j = 0; j <= 6; j++ ) { var pos = this.startingDay - this.options.startIn, p = pos < 0 ? 6 + pos + 1 : pos, inner = '', today = this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day === this.today.getDate(), content = ''; if ( day <= monthLength && ( i > 0 || j >= p ) ) { inner += '<span class="fc-date">' + day + '</span><span class="fc-weekday">' + this.options.weekabbrs[ j + this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn ] + '</span>'; // this day is: var strdate = ( this.month + 1 < 10 ? '0' + ( this.month + 1 ) : this.month + 1 ) + '-' + ( day < 10 ? '0' + day : day ) + '-' + this.year, dayData = this.caldata[ strdate ]; if( dayData ) { content = dayData; } if( content !== '' ) { inner += '<div>' + content + '</div>'; } ++day; } else { today = false; } var cellClasses = today ? 'fc-today ' : ''; if( content !== '' )
html += cellClasses !== '' ? '<div class="' + cellClasses + '">' : '<div>'; html += inner; html += '</div>'; } // stop making rows if we've run out of days if (day > monthLength) { this.rowTotal = i + 1; break; } else { html += '</div><div class="fc-row">'; } } html += '</div></div>'; return html; }, // based on http://stackoverflow.com/a/8390325/989439 _isValidDate : function( date ) { date = date.replace(/-/gi,''); var month = parseInt( date.substring( 0, 2 ), 10 ), day = parseInt( date.substring( 2, 4 ), 10 ), year = parseInt( date.substring( 4, 8 ), 10 ); if( ( month < 1 ) || ( month > 12 ) ) { return false; } else if( ( day < 1 ) || ( day > 31 ) ) { return false; } else if( ( ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) ) && ( day > 30 ) ) { return false; } else if( ( month == 2 ) && ( ( ( year % 400 ) == 0) || ( ( year % 4 ) == 0 ) ) && ( ( year % 100 ) != 0 ) && ( day > 29 ) ) { return false; } else if( ( month == 2 ) && ( ( year % 100 ) == 0 ) && ( day > 29 ) ) { return false; } return { day : day, month : month, year : year }; }, _move : function( period, dir, callback ) { if( dir === 'previous' ) { if( period === 'month' ) { this.year = this.month > 0 ? this.year : --this.year; this.month = this.month > 0 ? --this.month : 11; } else if( period === 'year' ) { this.year = --this.year; } } else if( dir === 'next' ) { if( period === 'month' ) { this.year = this.month < 11 ? this.year : ++this.year; this.month = this.month < 11 ? ++this.month : 0; } else if( period === 'year' ) { this.year = ++this.year; } } this._generateTemplate( callback ); }, /************************* ******PUBLIC METHODS ***** **************************/ getYear : function() { return this.year; }, getMonth : function() { return this.month + 1; }, getMonthName : function() { return this.options.displayMonthAbbr ? this.options.monthabbrs[ this.month ] : this.options.months[ this.month ]; }, // gets the cell's content div associated to a day of the current displayed month // day : 1 - [28||29||30||31] getCell : function( day ) { var row = Math.floor( ( day + this.startingDay - this.options.startIn ) / 7 ), pos = day + this.startingDay - this.options.startIn - ( row * 7 ) - 1; return this.$cal.find( 'div.fc-body' ).children( 'div.fc-row' ).eq( row ).children( 'div' ).eq( pos ).children( 'div' ); }, setData : function( caldata ) { caldata = caldata || {}; $.extend( this.caldata, caldata ); this._generateTemplate(); }, // goes to today's month/year gotoNow : function( callback ) { this.month = this.today.getMonth(); this.year = this.today.getFullYear(); this._generateTemplate( callback ); }, // goes to month/year goto : function( month, year, callback ) { this.month = month; this.year = year; this._generateTemplate( callback ); }, gotoPreviousMonth : function( callback ) { this._move( 'month', 'previous', callback ); }, gotoPreviousYear : function( callback ) { this._move( 'year', 'previous', callback ); }, gotoNextMonth : function( callback ) { this._move( 'month', 'next', callback ); }, gotoNextYear : function( callback ) { this._move( 'year', 'next', callback ); } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.calendario = function( options ) { var instance = $.data( this, 'calendario' ); if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { if ( !instance ) { logError( "cannot call methods on calendario prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for calendario instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { if ( instance ) { instance._init(); } else { instance = $.data( this, 'calendario', new $.Calendario( options, this ) ); } }); } return instance; }; } )( jQuery, window );
{ cellClasses += 'fc-content'; }
conditional_block
jquery.calendario.js
/** * jquery.calendario.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2012, Codrops * http://www.codrops.com */ ;( function( $, window, undefined ) { 'use strict'; $.Calendario = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.Calendario.defaults = { /* you can also pass: month : initialize calendar with this month (1-12). Default is today. year : initialize calendar with this year. Default is today. caldata : initial data/content for the calendar. caldata format: { 'MM-DD-YYYY' : 'HTML Content', 'MM-DD-YYYY' : 'HTML Content', 'MM-DD-YYYY' : 'HTML Content' ... } */ weeks : [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], weekabbrs : [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ], months : [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthabbrs : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], // choose between values in options.weeks or options.weekabbrs displayWeekAbbr : false, // choose between values in options.months or options.monthabbrs displayMonthAbbr : false, // left most day in the calendar // 0 - Sunday, 1 - Monday, ... , 6 - Saturday startIn : 1, onDayClick : function( $el, $content, dateProperties ) { return false; } }; $.Calendario.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.Calendario.defaults, options ); this.today = new Date(); this.month = ( isNaN( this.options.month ) || this.options.month == null) ? this.today.getMonth() : this.options.month - 1; this.year = ( isNaN( this.options.year ) || this.options.year == null) ? this.today.getFullYear() : this.options.year; this.caldata = this.options.caldata || {}; this._generateTemplate(); this._initEvents(); }, _initEvents : function() { var self = this; this.$el.on( 'click.calendario', 'div.fc-row > div', function() { var $cell = $( this ), idx = $cell.index(), $content = $cell.children( 'div' ), dateProp = { day : $cell.children( 'span.fc-date' ).text(), month : self.month + 1, monthname : self.options.displayMonthAbbr ? self.options.monthabbrs[ self.month ] : self.options.months[ self.month ], year : self.year, weekday : idx + self.options.startIn, weekdayname : self.options.weeks[ idx + self.options.startIn ] }; if( dateProp.day ) { self.options.onDayClick( $cell, $content, dateProp ); } } ); }, // Calendar logic based on http://jszen.blogspot.pt/2007/03/how-to-build-simple-calendar-with.html _generateTemplate : function( callback ) { var head = this._getHead(), body = this._getBody(), rowClass; switch( this.rowTotal ) { case 4 : rowClass = 'fc-four-rows'; break; case 5 : rowClass = 'fc-five-rows'; break; case 6 : rowClass = 'fc-six-rows'; break; } this.$cal = $( '<div class="fc-calendar ' + rowClass + '">' ).append( head, body ); this.$el.find( 'div.fc-calendar' ).remove().end().append( this.$cal ); if( callback ) { callback.call(); } }, _getHead : function() { var html = '<div class="fc-head">'; for ( var i = 0; i <= 6; i++ ) { var pos = i + this.options.startIn, j = pos > 6 ? pos - 6 - 1 : pos; html += '<div>'; html += this.options.displayWeekAbbr ? this.options.weekabbrs[ j ] : this.options.weeks[ j ]; html += '</div>'; } html += '</div>'; return html; }, _getBody : function() { var d = new Date( this.year, this.month + 1, 0 ), // number of days in the month monthLength = d.getDate(), firstDay = new Date( this.year, this.month, 1 ); // day of the week this.startingDay = firstDay.getDay(); var html = '<div class="fc-body clearfix"><div class="fc-row">', // fill in the days day = 1; // this loop is for weeks (rows) for ( var i = 0; i < 7; i++ ) { // this loop is for weekdays (cells) for ( var j = 0; j <= 6; j++ ) { var pos = this.startingDay - this.options.startIn, p = pos < 0 ? 6 + pos + 1 : pos, inner = '', today = this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day === this.today.getDate(), content = ''; if ( day <= monthLength && ( i > 0 || j >= p ) ) { inner += '<span class="fc-date">' + day + '</span><span class="fc-weekday">' + this.options.weekabbrs[ j + this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn ] + '</span>'; // this day is: var strdate = ( this.month + 1 < 10 ? '0' + ( this.month + 1 ) : this.month + 1 ) + '-' + ( day < 10 ? '0' + day : day ) + '-' + this.year, dayData = this.caldata[ strdate ]; if( dayData ) { content = dayData; } if( content !== '' ) { inner += '<div>' + content + '</div>'; } ++day; } else { today = false; } var cellClasses = today ? 'fc-today ' : ''; if( content !== '' ) { cellClasses += 'fc-content'; } html += cellClasses !== '' ? '<div class="' + cellClasses + '">' : '<div>'; html += inner; html += '</div>'; } // stop making rows if we've run out of days if (day > monthLength) { this.rowTotal = i + 1; break; } else { html += '</div><div class="fc-row">'; } } html += '</div></div>'; return html; }, // based on http://stackoverflow.com/a/8390325/989439 _isValidDate : function( date ) { date = date.replace(/-/gi,''); var month = parseInt( date.substring( 0, 2 ), 10 ), day = parseInt( date.substring( 2, 4 ), 10 ), year = parseInt( date.substring( 4, 8 ), 10 ); if( ( month < 1 ) || ( month > 12 ) ) { return false; } else if( ( day < 1 ) || ( day > 31 ) ) { return false; } else if( ( ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) ) && ( day > 30 ) ) { return false; } else if( ( month == 2 ) && ( ( ( year % 400 ) == 0) || ( ( year % 4 ) == 0 ) ) && ( ( year % 100 ) != 0 ) && ( day > 29 ) ) { return false; } else if( ( month == 2 ) && ( ( year % 100 ) == 0 ) && ( day > 29 ) ) { return false; } return { day : day, month : month, year : year }; }, _move : function( period, dir, callback ) { if( dir === 'previous' ) { if( period === 'month' ) { this.year = this.month > 0 ? this.year : --this.year; this.month = this.month > 0 ? --this.month : 11; } else if( period === 'year' ) { this.year = --this.year; } } else if( dir === 'next' ) { if( period === 'month' ) { this.year = this.month < 11 ? this.year : ++this.year; this.month = this.month < 11 ? ++this.month : 0; } else if( period === 'year' ) { this.year = ++this.year; } } this._generateTemplate( callback ); }, /************************* ******PUBLIC METHODS ***** **************************/ getYear : function() { return this.year; }, getMonth : function() { return this.month + 1; }, getMonthName : function() { return this.options.displayMonthAbbr ? this.options.monthabbrs[ this.month ] : this.options.months[ this.month ]; }, // gets the cell's content div associated to a day of the current displayed month // day : 1 - [28||29||30||31] getCell : function( day ) { var row = Math.floor( ( day + this.startingDay - this.options.startIn ) / 7 ), pos = day + this.startingDay - this.options.startIn - ( row * 7 ) - 1; return this.$cal.find( 'div.fc-body' ).children( 'div.fc-row' ).eq( row ).children( 'div' ).eq( pos ).children( 'div' ); }, setData : function( caldata ) { caldata = caldata || {}; $.extend( this.caldata, caldata ); this._generateTemplate(); }, // goes to today's month/year gotoNow : function( callback ) { this.month = this.today.getMonth(); this.year = this.today.getFullYear(); this._generateTemplate( callback ); }, // goes to month/year goto : function( month, year, callback ) { this.month = month; this.year = year; this._generateTemplate( callback ); }, gotoPreviousMonth : function( callback ) { this._move( 'month', 'previous', callback ); }, gotoPreviousYear : function( callback ) { this._move( 'year', 'previous', callback ); }, gotoNextMonth : function( callback ) { this._move( 'month', 'next', callback ); }, gotoNextYear : function( callback ) { this._move( 'year', 'next', callback ); } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.calendario = function( options ) { var instance = $.data( this, 'calendario' ); if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { if ( !instance ) {
logError( "cannot call methods on calendario prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for calendario instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { if ( instance ) { instance._init(); } else { instance = $.data( this, 'calendario', new $.Calendario( options, this ) ); } }); } return instance; }; } )( jQuery, window );
random_line_split
pipeobject.py
# This file is a part of pysnapshotd, a program for automated backups # Copyright (C) 2015-2016 Jonas Thiem # # This program 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. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import threading class BufferedPipeObject(object): def __init__(self): self.closed = False self.contents = b"" self.access_mutex = threading.Lock() self.waiting_for_content_semaphore = \ threading.Semaphore() self.waiting_for_content_counter = 0 self._write_func = None def _set_write_func(self, f): self.access_mutex.acquire() self._write_func = f self.access_mutex.release() def close(self): self.access_mutex.acquire() self.closed = True self.access_mutex.release() def write(self, data): # First, check if pipe is still open at all: self.access_mutex.acquire() if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Do nothing for an obvious dummy command: if len(data) == 0: self.access_mutex.release() return 0 # Try to write with the write func if given: # (which means this pipe object itself will always remain empty and # .read() on it will block forever, since things are somewhat bypassed # directly to some target write function) if self._write_func != None: try: self._write_func(data) except Exception: self.closed = True finally: self.access_mutex.release() return # Otherwise, just put contents in internal buffer for reading from # this pipe from "the other end": try: self.contents += data i = 0 while i < self.waiting_for_content_counter: self.waiting_for_content_semaphore.\ release() i += 1 finally: self.access_mutex.release() def read(self, amount):
print(" >> PIPE READ: " + str(amount)) if amount <= 0: print(" >> PIPE READ DATA: <empty read>") return b"" self.access_mutex.acquire() # Try to read data as long as needed to acquire requested amount: obtained_data = b"" while True: # If pipe was closed along this process, abort: if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Try to obtain as much data as requested: if len(self.contents) > 0: added_data = self.contents[:amount] obtained_data += added_data self.contents = self.contents[len(added_data):] amount -= len(added_data) # If there is not enough data available, we will need to wait for # more: if amount > 0: self.waiting_for_content_counter += 1 self.access_mutex.release() self.waiting_for_content_semaphore.acquire() self.access_mutex.acquire() else: assert(len(obtained_data) > 0) print(" >> PIPE READ DATA: " + str(obtained_data)) return obtained_data
identifier_body
pipeobject.py
# This file is a part of pysnapshotd, a program for automated backups # Copyright (C) 2015-2016 Jonas Thiem # # This program 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. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import threading class BufferedPipeObject(object): def __init__(self): self.closed = False self.contents = b"" self.access_mutex = threading.Lock() self.waiting_for_content_semaphore = \ threading.Semaphore() self.waiting_for_content_counter = 0 self._write_func = None def _set_write_func(self, f): self.access_mutex.acquire() self._write_func = f self.access_mutex.release() def close(self): self.access_mutex.acquire() self.closed = True self.access_mutex.release() def
(self, data): # First, check if pipe is still open at all: self.access_mutex.acquire() if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Do nothing for an obvious dummy command: if len(data) == 0: self.access_mutex.release() return 0 # Try to write with the write func if given: # (which means this pipe object itself will always remain empty and # .read() on it will block forever, since things are somewhat bypassed # directly to some target write function) if self._write_func != None: try: self._write_func(data) except Exception: self.closed = True finally: self.access_mutex.release() return # Otherwise, just put contents in internal buffer for reading from # this pipe from "the other end": try: self.contents += data i = 0 while i < self.waiting_for_content_counter: self.waiting_for_content_semaphore.\ release() i += 1 finally: self.access_mutex.release() def read(self, amount): print(" >> PIPE READ: " + str(amount)) if amount <= 0: print(" >> PIPE READ DATA: <empty read>") return b"" self.access_mutex.acquire() # Try to read data as long as needed to acquire requested amount: obtained_data = b"" while True: # If pipe was closed along this process, abort: if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Try to obtain as much data as requested: if len(self.contents) > 0: added_data = self.contents[:amount] obtained_data += added_data self.contents = self.contents[len(added_data):] amount -= len(added_data) # If there is not enough data available, we will need to wait for # more: if amount > 0: self.waiting_for_content_counter += 1 self.access_mutex.release() self.waiting_for_content_semaphore.acquire() self.access_mutex.acquire() else: assert(len(obtained_data) > 0) print(" >> PIPE READ DATA: " + str(obtained_data)) return obtained_data
write
identifier_name
pipeobject.py
# This file is a part of pysnapshotd, a program for automated backups # Copyright (C) 2015-2016 Jonas Thiem # # This program 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. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import threading class BufferedPipeObject(object): def __init__(self): self.closed = False self.contents = b"" self.access_mutex = threading.Lock() self.waiting_for_content_semaphore = \ threading.Semaphore() self.waiting_for_content_counter = 0 self._write_func = None def _set_write_func(self, f): self.access_mutex.acquire() self._write_func = f self.access_mutex.release() def close(self): self.access_mutex.acquire() self.closed = True self.access_mutex.release() def write(self, data): # First, check if pipe is still open at all: self.access_mutex.acquire() if self.closed: self.access_mutex.release()
# Do nothing for an obvious dummy command: if len(data) == 0: self.access_mutex.release() return 0 # Try to write with the write func if given: # (which means this pipe object itself will always remain empty and # .read() on it will block forever, since things are somewhat bypassed # directly to some target write function) if self._write_func != None: try: self._write_func(data) except Exception: self.closed = True finally: self.access_mutex.release() return # Otherwise, just put contents in internal buffer for reading from # this pipe from "the other end": try: self.contents += data i = 0 while i < self.waiting_for_content_counter: self.waiting_for_content_semaphore.\ release() i += 1 finally: self.access_mutex.release() def read(self, amount): print(" >> PIPE READ: " + str(amount)) if amount <= 0: print(" >> PIPE READ DATA: <empty read>") return b"" self.access_mutex.acquire() # Try to read data as long as needed to acquire requested amount: obtained_data = b"" while True: # If pipe was closed along this process, abort: if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Try to obtain as much data as requested: if len(self.contents) > 0: added_data = self.contents[:amount] obtained_data += added_data self.contents = self.contents[len(added_data):] amount -= len(added_data) # If there is not enough data available, we will need to wait for # more: if amount > 0: self.waiting_for_content_counter += 1 self.access_mutex.release() self.waiting_for_content_semaphore.acquire() self.access_mutex.acquire() else: assert(len(obtained_data) > 0) print(" >> PIPE READ DATA: " + str(obtained_data)) return obtained_data
raise OSError("broken pipe - pipe has been closed")
random_line_split
pipeobject.py
# This file is a part of pysnapshotd, a program for automated backups # Copyright (C) 2015-2016 Jonas Thiem # # This program 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. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import threading class BufferedPipeObject(object): def __init__(self): self.closed = False self.contents = b"" self.access_mutex = threading.Lock() self.waiting_for_content_semaphore = \ threading.Semaphore() self.waiting_for_content_counter = 0 self._write_func = None def _set_write_func(self, f): self.access_mutex.acquire() self._write_func = f self.access_mutex.release() def close(self): self.access_mutex.acquire() self.closed = True self.access_mutex.release() def write(self, data): # First, check if pipe is still open at all: self.access_mutex.acquire() if self.closed: self.access_mutex.release() raise OSError("broken pipe - pipe has been closed") # Do nothing for an obvious dummy command: if len(data) == 0: self.access_mutex.release() return 0 # Try to write with the write func if given: # (which means this pipe object itself will always remain empty and # .read() on it will block forever, since things are somewhat bypassed # directly to some target write function) if self._write_func != None: try: self._write_func(data) except Exception: self.closed = True finally: self.access_mutex.release() return # Otherwise, just put contents in internal buffer for reading from # this pipe from "the other end": try: self.contents += data i = 0 while i < self.waiting_for_content_counter: self.waiting_for_content_semaphore.\ release() i += 1 finally: self.access_mutex.release() def read(self, amount): print(" >> PIPE READ: " + str(amount)) if amount <= 0: print(" >> PIPE READ DATA: <empty read>") return b"" self.access_mutex.acquire() # Try to read data as long as needed to acquire requested amount: obtained_data = b"" while True: # If pipe was closed along this process, abort: if self.closed:
# Try to obtain as much data as requested: if len(self.contents) > 0: added_data = self.contents[:amount] obtained_data += added_data self.contents = self.contents[len(added_data):] amount -= len(added_data) # If there is not enough data available, we will need to wait for # more: if amount > 0: self.waiting_for_content_counter += 1 self.access_mutex.release() self.waiting_for_content_semaphore.acquire() self.access_mutex.acquire() else: assert(len(obtained_data) > 0) print(" >> PIPE READ DATA: " + str(obtained_data)) return obtained_data
self.access_mutex.release() raise OSError("broken pipe - pipe has been closed")
conditional_block
main.rs
extern crate rand; use std::io; use rand::Rng; // provide a random number generator use std::cmp::Ordering; fn
() { let lower_bound = 1; let upper_bound = 101; println!("Guess the num! {} ~ {}", lower_bound, upper_bound); let secret = rand::thread_rng() // get a copy of the rng .gen_range(lower_bound, upper_bound); // println!("The secret num is: {}", secret); loop { let mut guess = String::new(); println!("Input your guess:"); // print!("Input your guess:"); // io::stdout().flush(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { println!("Please Enter a number!\n"); continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
main
identifier_name
main.rs
extern crate rand; use std::io; use rand::Rng; // provide a random number generator use std::cmp::Ordering; fn main()
{ let lower_bound = 1; let upper_bound = 101; println!("Guess the num! {} ~ {}", lower_bound, upper_bound); let secret = rand::thread_rng() // get a copy of the rng .gen_range(lower_bound, upper_bound); // println!("The secret num is: {}", secret); loop { let mut guess = String::new(); println!("Input your guess:"); // print!("Input your guess:"); // io::stdout().flush(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { println!("Please Enter a number!\n"); continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
identifier_body
main.rs
extern crate rand; use std::io; use rand::Rng; // provide a random number generator use std::cmp::Ordering; fn main() { let lower_bound = 1; let upper_bound = 101; println!("Guess the num! {} ~ {}", lower_bound, upper_bound); let secret = rand::thread_rng() // get a copy of the rng .gen_range(lower_bound, upper_bound); // println!("The secret num is: {}", secret); loop { let mut guess = String::new(); println!("Input your guess:"); // print!("Input your guess:"); // io::stdout().flush(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) =>
}; println!("You guessed: {}", guess); match guess.cmp(&secret) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
{ println!("Please Enter a number!\n"); continue; }
conditional_block
main.rs
extern crate rand; use std::io; use rand::Rng; // provide a random number generator use std::cmp::Ordering; fn main() { let lower_bound = 1; let upper_bound = 101; println!("Guess the num! {} ~ {}", lower_bound, upper_bound); let secret = rand::thread_rng() // get a copy of the rng .gen_range(lower_bound, upper_bound); // println!("The secret num is: {}", secret); loop { let mut guess = String::new(); println!("Input your guess:"); // print!("Input your guess:"); // io::stdout().flush(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => { println!("Please Enter a number!\n"); continue; } };
Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
println!("You guessed: {}", guess); match guess.cmp(&secret) {
random_line_split
main.rs
extern crate tcod; extern crate rand; use std::cmp; use tcod::console::*; use tcod::colors::{self, Color}; use rand::Rng; // Actual size of the window const SCREEN_WIDTH: i32 = 80; const SCREEN_HEIGHT: i32 = 50; // Size of the map in the window const MAP_WIDTH: i32 = 80; const MAP_HEIGHT: i32 = 45; // Parameters for the autodungeon generator const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 30; const LIMIT_FPS: i32 = 20; const COLOR_DARK_WALL: Color = Color { r: 0, g: 0, b: 100}; const COLOR_DARK_GROUND: Color = Color {r: 50, g:50, b: 150}; type Map = Vec<Vec<Tile>>; #[derive(Clone, Copy, Debug)] struct Tile { blocked: bool, block_sight: bool, } impl Tile { pub fn empty() -> Self { Tile {blocked: false, block_sight: false} } pub fn wall() -> Self { Tile {blocked: true, block_sight: true} } } #[derive(Clone, Copy, Debug)] struct Rect { x1: i32, y1: i32, x2: i32, y2: i32, } impl Rect { pub fn new(x: i32, y:i32, w: i32, h: i32) -> Self { Rect { x1: x, y1: y, x2: x + w, y2: y + h } } pub fn center(&self) -> (i32, i32) { let center_x=(self.x1 + self.x2) / 2; let center_y=(self.y1 + self.y2) / 2; (center_x, center_y) } pub fn intersects_with(&self, other: &Rect) -> bool { (self.x1 <= other.x2) && (self.x2 >= other.x1) && (self.y1 <= other.y2) && (self.y2 >= other.y1) } } #[derive(Debug)] struct Object { x: i32, y: i32, char: char, color: Color, } impl Object { pub fn new (x: i32, y: i32, char: char, color: Color) -> Self { Object { x: x, y: y, char: char, color: color, } } pub fn move_by(&mut self, dx: i32, dy: i32, map: &Map){ if !map[(self.x + dx) as usize][(self.y + dy) as usize].blocked { self.x += dx; self.y += dy; } } pub fn
(&self, con: &mut Console) { con.set_default_foreground(self.color); con.put_char(self.x, self.y, self.char, BackgroundFlag::None); } pub fn clear(&self, con: &mut Console) { con.put_char(self.x, self.y, ' ', BackgroundFlag::None) } } fn create_room(room: Rect, map: &mut Map) { for x in (room.x1 + 1)..room.x2 { for y in (room.y1 + 1)..room.y2 { map[x as usize][y as usize] = Tile::empty(); } } } fn create_h_tunnel(x1: i32, x2: i32, y: i32, map: &mut Map) { for x in cmp::min(x1, x2)..cmp::max(x1, x2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn create_v_tunnel(y1: i32, y2: i32, y: i32, map: &mut Map) { for x in cmp::min(y1, y2)..cmp::max(y1, y2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn make_map() -> (Map, (i32, i32)) { let mut map = vec![vec![Tile::wall(); MAP_HEIGHT as usize]; MAP_WIDTH as usize]; let mut rooms = vec![]; let mut starting_position = (0,0); for _ in 0..MAX_ROOMS { let w = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let x = rand::thread_rng().gen_range(0, MAP_WIDTH - w); let y = rand::thread_rng().gen_range(0, MAP_HEIGHT - h); let new_room = Rect::new(x, y, w, h); let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); if !failed { create_room(new_room, &mut map); let (new_x, new_y) = new_room.center(); if rooms.is_empty() { starting_position = (new_x, new_y); } else { let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); if rand::random() { create_h_tunnel(prev_x, new_x, prev_y, &mut map); create_v_tunnel(prev_x, new_x, new_y, &mut map); } } rooms.push(new_room); } } (map, starting_position) } fn render_all(root: &mut Root, con: &mut Offscreen, objects: &[Object], map: &Map) { for y in 0..MAP_HEIGHT { for x in 0..MAP_WIDTH { let wall = map[x as usize][y as usize].block_sight; if wall { con.set_char_background(x, y, COLOR_DARK_WALL, BackgroundFlag::Set); } else { con.set_char_background(x, y, COLOR_DARK_GROUND, BackgroundFlag::Set); } } } for object in objects { object.draw(con); } blit (con, (0,0), (MAP_WIDTH, MAP_HEIGHT), root, (0,0), 1.0, 1.0); } fn handle_keys(root: &mut Root, player: &mut Object, map: &Map) -> bool { use tcod::input::Key; use tcod::input::KeyCode::*; let key = root.wait_for_keypress(true); match key { Key { code: Enter, alt: true, .. } => { let fullscreen = root.is_fullscreen(); root.set_fullscreen(!fullscreen); } Key { code: Escape, ..} => return true, Key { code: Up, ..} => player.move_by(0, -1, map), Key { code: Down, .. } => player.move_by(0, 1, map), Key { code: Left, .. } => player.move_by(-1, 0, map), Key { code: Right, .. } => player.move_by(1, 0, map), _ => {}, } false } fn main (){ let mut root = Root::initializer() .font("arial10x10.png", FontLayout::Tcod) .font_type(FontType::Greyscale) .size(SCREEN_WIDTH, SCREEN_WIDTH) .title("Dungeon Crawler") .init(); tcod::system::set_fps(LIMIT_FPS); let mut con = Offscreen::new(MAP_WIDTH, MAP_HEIGHT); let (map, (player_x, player_y)) = make_map(); let player = Object::new(player_x, player_y, '@', colors::WHITE); let npc = Object::new(SCREEN_WIDTH /2 -5, SCREEN_HEIGHT /2, '@', colors::YELLOW); let mut objects = [player, npc]; while !root.window_closed() { render_all(&mut root, &mut con, &objects, &map); root.flush(); for object in &objects { object.clear(&mut con) } let player = &mut objects[0]; let exit = handle_keys(&mut root, player, &map); if exit { break } } }
draw
identifier_name
main.rs
extern crate tcod; extern crate rand; use std::cmp; use tcod::console::*; use tcod::colors::{self, Color}; use rand::Rng; // Actual size of the window const SCREEN_WIDTH: i32 = 80; const SCREEN_HEIGHT: i32 = 50; // Size of the map in the window const MAP_WIDTH: i32 = 80; const MAP_HEIGHT: i32 = 45; // Parameters for the autodungeon generator const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 30; const LIMIT_FPS: i32 = 20; const COLOR_DARK_WALL: Color = Color { r: 0, g: 0, b: 100}; const COLOR_DARK_GROUND: Color = Color {r: 50, g:50, b: 150}; type Map = Vec<Vec<Tile>>; #[derive(Clone, Copy, Debug)] struct Tile { blocked: bool, block_sight: bool, } impl Tile { pub fn empty() -> Self { Tile {blocked: false, block_sight: false} } pub fn wall() -> Self { Tile {blocked: true, block_sight: true} } } #[derive(Clone, Copy, Debug)] struct Rect { x1: i32, y1: i32, x2: i32, y2: i32, } impl Rect { pub fn new(x: i32, y:i32, w: i32, h: i32) -> Self { Rect { x1: x, y1: y, x2: x + w, y2: y + h } } pub fn center(&self) -> (i32, i32) { let center_x=(self.x1 + self.x2) / 2; let center_y=(self.y1 + self.y2) / 2; (center_x, center_y) } pub fn intersects_with(&self, other: &Rect) -> bool { (self.x1 <= other.x2) && (self.x2 >= other.x1) && (self.y1 <= other.y2) && (self.y2 >= other.y1) } } #[derive(Debug)] struct Object { x: i32, y: i32, char: char, color: Color, } impl Object { pub fn new (x: i32, y: i32, char: char, color: Color) -> Self { Object { x: x, y: y, char: char, color: color, } } pub fn move_by(&mut self, dx: i32, dy: i32, map: &Map){ if !map[(self.x + dx) as usize][(self.y + dy) as usize].blocked { self.x += dx; self.y += dy; } } pub fn draw(&self, con: &mut Console) { con.set_default_foreground(self.color);
pub fn clear(&self, con: &mut Console) { con.put_char(self.x, self.y, ' ', BackgroundFlag::None) } } fn create_room(room: Rect, map: &mut Map) { for x in (room.x1 + 1)..room.x2 { for y in (room.y1 + 1)..room.y2 { map[x as usize][y as usize] = Tile::empty(); } } } fn create_h_tunnel(x1: i32, x2: i32, y: i32, map: &mut Map) { for x in cmp::min(x1, x2)..cmp::max(x1, x2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn create_v_tunnel(y1: i32, y2: i32, y: i32, map: &mut Map) { for x in cmp::min(y1, y2)..cmp::max(y1, y2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn make_map() -> (Map, (i32, i32)) { let mut map = vec![vec![Tile::wall(); MAP_HEIGHT as usize]; MAP_WIDTH as usize]; let mut rooms = vec![]; let mut starting_position = (0,0); for _ in 0..MAX_ROOMS { let w = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let x = rand::thread_rng().gen_range(0, MAP_WIDTH - w); let y = rand::thread_rng().gen_range(0, MAP_HEIGHT - h); let new_room = Rect::new(x, y, w, h); let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); if !failed { create_room(new_room, &mut map); let (new_x, new_y) = new_room.center(); if rooms.is_empty() { starting_position = (new_x, new_y); } else { let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); if rand::random() { create_h_tunnel(prev_x, new_x, prev_y, &mut map); create_v_tunnel(prev_x, new_x, new_y, &mut map); } } rooms.push(new_room); } } (map, starting_position) } fn render_all(root: &mut Root, con: &mut Offscreen, objects: &[Object], map: &Map) { for y in 0..MAP_HEIGHT { for x in 0..MAP_WIDTH { let wall = map[x as usize][y as usize].block_sight; if wall { con.set_char_background(x, y, COLOR_DARK_WALL, BackgroundFlag::Set); } else { con.set_char_background(x, y, COLOR_DARK_GROUND, BackgroundFlag::Set); } } } for object in objects { object.draw(con); } blit (con, (0,0), (MAP_WIDTH, MAP_HEIGHT), root, (0,0), 1.0, 1.0); } fn handle_keys(root: &mut Root, player: &mut Object, map: &Map) -> bool { use tcod::input::Key; use tcod::input::KeyCode::*; let key = root.wait_for_keypress(true); match key { Key { code: Enter, alt: true, .. } => { let fullscreen = root.is_fullscreen(); root.set_fullscreen(!fullscreen); } Key { code: Escape, ..} => return true, Key { code: Up, ..} => player.move_by(0, -1, map), Key { code: Down, .. } => player.move_by(0, 1, map), Key { code: Left, .. } => player.move_by(-1, 0, map), Key { code: Right, .. } => player.move_by(1, 0, map), _ => {}, } false } fn main (){ let mut root = Root::initializer() .font("arial10x10.png", FontLayout::Tcod) .font_type(FontType::Greyscale) .size(SCREEN_WIDTH, SCREEN_WIDTH) .title("Dungeon Crawler") .init(); tcod::system::set_fps(LIMIT_FPS); let mut con = Offscreen::new(MAP_WIDTH, MAP_HEIGHT); let (map, (player_x, player_y)) = make_map(); let player = Object::new(player_x, player_y, '@', colors::WHITE); let npc = Object::new(SCREEN_WIDTH /2 -5, SCREEN_HEIGHT /2, '@', colors::YELLOW); let mut objects = [player, npc]; while !root.window_closed() { render_all(&mut root, &mut con, &objects, &map); root.flush(); for object in &objects { object.clear(&mut con) } let player = &mut objects[0]; let exit = handle_keys(&mut root, player, &map); if exit { break } } }
con.put_char(self.x, self.y, self.char, BackgroundFlag::None); }
random_line_split
main.rs
extern crate tcod; extern crate rand; use std::cmp; use tcod::console::*; use tcod::colors::{self, Color}; use rand::Rng; // Actual size of the window const SCREEN_WIDTH: i32 = 80; const SCREEN_HEIGHT: i32 = 50; // Size of the map in the window const MAP_WIDTH: i32 = 80; const MAP_HEIGHT: i32 = 45; // Parameters for the autodungeon generator const ROOM_MAX_SIZE: i32 = 10; const ROOM_MIN_SIZE: i32 = 6; const MAX_ROOMS: i32 = 30; const LIMIT_FPS: i32 = 20; const COLOR_DARK_WALL: Color = Color { r: 0, g: 0, b: 100}; const COLOR_DARK_GROUND: Color = Color {r: 50, g:50, b: 150}; type Map = Vec<Vec<Tile>>; #[derive(Clone, Copy, Debug)] struct Tile { blocked: bool, block_sight: bool, } impl Tile { pub fn empty() -> Self { Tile {blocked: false, block_sight: false} } pub fn wall() -> Self { Tile {blocked: true, block_sight: true} } } #[derive(Clone, Copy, Debug)] struct Rect { x1: i32, y1: i32, x2: i32, y2: i32, } impl Rect { pub fn new(x: i32, y:i32, w: i32, h: i32) -> Self { Rect { x1: x, y1: y, x2: x + w, y2: y + h } } pub fn center(&self) -> (i32, i32) { let center_x=(self.x1 + self.x2) / 2; let center_y=(self.y1 + self.y2) / 2; (center_x, center_y) } pub fn intersects_with(&self, other: &Rect) -> bool { (self.x1 <= other.x2) && (self.x2 >= other.x1) && (self.y1 <= other.y2) && (self.y2 >= other.y1) } } #[derive(Debug)] struct Object { x: i32, y: i32, char: char, color: Color, } impl Object { pub fn new (x: i32, y: i32, char: char, color: Color) -> Self { Object { x: x, y: y, char: char, color: color, } } pub fn move_by(&mut self, dx: i32, dy: i32, map: &Map){ if !map[(self.x + dx) as usize][(self.y + dy) as usize].blocked { self.x += dx; self.y += dy; } } pub fn draw(&self, con: &mut Console) { con.set_default_foreground(self.color); con.put_char(self.x, self.y, self.char, BackgroundFlag::None); } pub fn clear(&self, con: &mut Console) { con.put_char(self.x, self.y, ' ', BackgroundFlag::None) } } fn create_room(room: Rect, map: &mut Map) { for x in (room.x1 + 1)..room.x2 { for y in (room.y1 + 1)..room.y2 { map[x as usize][y as usize] = Tile::empty(); } } } fn create_h_tunnel(x1: i32, x2: i32, y: i32, map: &mut Map) { for x in cmp::min(x1, x2)..cmp::max(x1, x2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn create_v_tunnel(y1: i32, y2: i32, y: i32, map: &mut Map) { for x in cmp::min(y1, y2)..cmp::max(y1, y2) + 1 { map[x as usize][y as usize] = Tile::empty(); } } fn make_map() -> (Map, (i32, i32)) { let mut map = vec![vec![Tile::wall(); MAP_HEIGHT as usize]; MAP_WIDTH as usize]; let mut rooms = vec![]; let mut starting_position = (0,0); for _ in 0..MAX_ROOMS { let w = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let h = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1); let x = rand::thread_rng().gen_range(0, MAP_WIDTH - w); let y = rand::thread_rng().gen_range(0, MAP_HEIGHT - h); let new_room = Rect::new(x, y, w, h); let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room)); if !failed { create_room(new_room, &mut map); let (new_x, new_y) = new_room.center(); if rooms.is_empty() { starting_position = (new_x, new_y); } else { let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); if rand::random() { create_h_tunnel(prev_x, new_x, prev_y, &mut map); create_v_tunnel(prev_x, new_x, new_y, &mut map); } } rooms.push(new_room); } } (map, starting_position) } fn render_all(root: &mut Root, con: &mut Offscreen, objects: &[Object], map: &Map) { for y in 0..MAP_HEIGHT { for x in 0..MAP_WIDTH { let wall = map[x as usize][y as usize].block_sight; if wall
else { con.set_char_background(x, y, COLOR_DARK_GROUND, BackgroundFlag::Set); } } } for object in objects { object.draw(con); } blit (con, (0,0), (MAP_WIDTH, MAP_HEIGHT), root, (0,0), 1.0, 1.0); } fn handle_keys(root: &mut Root, player: &mut Object, map: &Map) -> bool { use tcod::input::Key; use tcod::input::KeyCode::*; let key = root.wait_for_keypress(true); match key { Key { code: Enter, alt: true, .. } => { let fullscreen = root.is_fullscreen(); root.set_fullscreen(!fullscreen); } Key { code: Escape, ..} => return true, Key { code: Up, ..} => player.move_by(0, -1, map), Key { code: Down, .. } => player.move_by(0, 1, map), Key { code: Left, .. } => player.move_by(-1, 0, map), Key { code: Right, .. } => player.move_by(1, 0, map), _ => {}, } false } fn main (){ let mut root = Root::initializer() .font("arial10x10.png", FontLayout::Tcod) .font_type(FontType::Greyscale) .size(SCREEN_WIDTH, SCREEN_WIDTH) .title("Dungeon Crawler") .init(); tcod::system::set_fps(LIMIT_FPS); let mut con = Offscreen::new(MAP_WIDTH, MAP_HEIGHT); let (map, (player_x, player_y)) = make_map(); let player = Object::new(player_x, player_y, '@', colors::WHITE); let npc = Object::new(SCREEN_WIDTH /2 -5, SCREEN_HEIGHT /2, '@', colors::YELLOW); let mut objects = [player, npc]; while !root.window_closed() { render_all(&mut root, &mut con, &objects, &map); root.flush(); for object in &objects { object.clear(&mut con) } let player = &mut objects[0]; let exit = handle_keys(&mut root, player, &map); if exit { break } } }
{ con.set_char_background(x, y, COLOR_DARK_WALL, BackgroundFlag::Set); }
conditional_block
urls.py
"""simpleneed URL Configuration. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from .views import ( NeedLocationViewSet, ContactViewSet, MoodViewSet, GenderViewSet, NeedViewSet, RoamViewSet, StatsViewSet, LocatedElementViewSet, MessageViewSet, SupplyLocationViewSet ) from rest_framework import routers
router.register(r'genders', GenderViewSet) router.register(r'needlocations', NeedLocationViewSet) router.register(r'contacts', ContactViewSet) router.register(r'roams', RoamViewSet) router.register(r'stats', StatsViewSet) router.register(r'messages', MessageViewSet) router.register(r'locatedelements', LocatedElementViewSet) router.register(r'supplylocations', SupplyLocationViewSet) urlpatterns = [url(r'', include(router.urls))]
router = routers.DefaultRouter() router.register(r'moods', MoodViewSet) router.register(r'needs', NeedViewSet)
random_line_split
PlaylistsNav.tsx
/* eslint-disable jsx-a11y/no-autofocus */ import * as electron from 'electron'; import * as React from 'react'; import * as Icon from 'react-fontawesome'; import * as PlaylistsActions from '../../actions/PlaylistsActions'; import PlaylistsNavLink from '../PlaylistsNavLink/PlaylistsNavLink'; import { PlaylistModel } from '../../../shared/types/interfaces'; import * as styles from './PlaylistsNav.css'; const { Menu } = electron.remote; interface Props { playlists: PlaylistModel[]; } interface State { renamed: string | null; } class PlaylistsNav extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { renamed: null // the playlist being renamed if there's one }; this.blur = this.blur.bind(this); this.focus = this.focus.bind(this); this.keyDown = this.keyDown.bind(this); this.showContextMenu = this.showContextMenu.bind(this); this.createPlaylist = this.createPlaylist.bind(this); } showContextMenu(playlistId: string) { const template: electron.MenuItemConstructorOptions[] = [ { label: 'Rename', click: () => { this.setState({ renamed: playlistId }); } }, { label: 'Delete', click: async () => { await PlaylistsActions.remove(playlistId); } }, { type: 'separator' }, { label: 'Duplicate', click: async () => { await PlaylistsActions.duplicate(playlistId); } }, { type: 'separator' }, { label: 'Export', click: async () => { await PlaylistsActions.exportToM3u(playlistId); } } ]; const context = Menu.buildFromTemplate(template); context.popup({}); // Let it appear } async createPlaylist() { // Todo 'new playlist 1', 'new playlist 2' ... await PlaylistsActions.create('New playlist', [], false, true); } async rename(_id: string, name: string) { await PlaylistsActions.rename(_id, name); } async keyDown(e: React.KeyboardEvent<HTMLInputElement>) { e.persist(); switch (e.nativeEvent.code) { case 'Enter': { // Enter if (this.state.renamed && e.currentTarget) { await this.rename(this.state.renamed, e.currentTarget.value); this.setState({ renamed: null }); } break; } case 'Escape': { // Escape this.setState({ renamed: null }); break; } default: { break; } } } async
(e: React.FocusEvent<HTMLInputElement>) { if (this.state.renamed) { await this.rename(this.state.renamed, e.currentTarget.value); } this.setState({ renamed: null }); } focus(e: React.FocusEvent<HTMLInputElement>) { e.currentTarget.select(); } render() { const { playlists } = this.props; // TODO (y.solovyov): extract into separate method that returns items const nav = playlists.map((elem) => { let navItemContent; if (elem._id === this.state.renamed) { navItemContent = ( <input className={styles.item__input} type='text' defaultValue={elem.name} onKeyDown={this.keyDown} onBlur={this.blur} onFocus={this.focus} autoFocus /> ); } else { navItemContent = ( <PlaylistsNavLink className={styles.item__link} playlistId={elem._id} onContextMenu={this.showContextMenu}> {elem.name} </PlaylistsNavLink> ); } return <div key={`playlist-${elem._id}`}>{navItemContent}</div>; }); return ( <div className={styles.playlistsNav}> <div className={styles.playlistsNav__header}> <h4 className={styles.playlistsNav__title}>Playlists</h4> <div className={styles.actions}> <button className={styles.action} onClick={this.createPlaylist} title='New playlist'> <Icon name='plus' /> </button> </div> </div> <div className={styles.playlistsNav__body}>{nav}</div> </div> ); } } export default PlaylistsNav;
blur
identifier_name
PlaylistsNav.tsx
/* eslint-disable jsx-a11y/no-autofocus */ import * as electron from 'electron'; import * as React from 'react'; import * as Icon from 'react-fontawesome'; import * as PlaylistsActions from '../../actions/PlaylistsActions'; import PlaylistsNavLink from '../PlaylistsNavLink/PlaylistsNavLink'; import { PlaylistModel } from '../../../shared/types/interfaces'; import * as styles from './PlaylistsNav.css'; const { Menu } = electron.remote; interface Props { playlists: PlaylistModel[]; } interface State { renamed: string | null; } class PlaylistsNav extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { renamed: null // the playlist being renamed if there's one }; this.blur = this.blur.bind(this); this.focus = this.focus.bind(this); this.keyDown = this.keyDown.bind(this); this.showContextMenu = this.showContextMenu.bind(this); this.createPlaylist = this.createPlaylist.bind(this); } showContextMenu(playlistId: string)
async createPlaylist() { // Todo 'new playlist 1', 'new playlist 2' ... await PlaylistsActions.create('New playlist', [], false, true); } async rename(_id: string, name: string) { await PlaylistsActions.rename(_id, name); } async keyDown(e: React.KeyboardEvent<HTMLInputElement>) { e.persist(); switch (e.nativeEvent.code) { case 'Enter': { // Enter if (this.state.renamed && e.currentTarget) { await this.rename(this.state.renamed, e.currentTarget.value); this.setState({ renamed: null }); } break; } case 'Escape': { // Escape this.setState({ renamed: null }); break; } default: { break; } } } async blur(e: React.FocusEvent<HTMLInputElement>) { if (this.state.renamed) { await this.rename(this.state.renamed, e.currentTarget.value); } this.setState({ renamed: null }); } focus(e: React.FocusEvent<HTMLInputElement>) { e.currentTarget.select(); } render() { const { playlists } = this.props; // TODO (y.solovyov): extract into separate method that returns items const nav = playlists.map((elem) => { let navItemContent; if (elem._id === this.state.renamed) { navItemContent = ( <input className={styles.item__input} type='text' defaultValue={elem.name} onKeyDown={this.keyDown} onBlur={this.blur} onFocus={this.focus} autoFocus /> ); } else { navItemContent = ( <PlaylistsNavLink className={styles.item__link} playlistId={elem._id} onContextMenu={this.showContextMenu}> {elem.name} </PlaylistsNavLink> ); } return <div key={`playlist-${elem._id}`}>{navItemContent}</div>; }); return ( <div className={styles.playlistsNav}> <div className={styles.playlistsNav__header}> <h4 className={styles.playlistsNav__title}>Playlists</h4> <div className={styles.actions}> <button className={styles.action} onClick={this.createPlaylist} title='New playlist'> <Icon name='plus' /> </button> </div> </div> <div className={styles.playlistsNav__body}>{nav}</div> </div> ); } } export default PlaylistsNav;
{ const template: electron.MenuItemConstructorOptions[] = [ { label: 'Rename', click: () => { this.setState({ renamed: playlistId }); } }, { label: 'Delete', click: async () => { await PlaylistsActions.remove(playlistId); } }, { type: 'separator' }, { label: 'Duplicate', click: async () => { await PlaylistsActions.duplicate(playlistId); } }, { type: 'separator' }, { label: 'Export', click: async () => { await PlaylistsActions.exportToM3u(playlistId); } } ]; const context = Menu.buildFromTemplate(template); context.popup({}); // Let it appear }
identifier_body
PlaylistsNav.tsx
/* eslint-disable jsx-a11y/no-autofocus */ import * as electron from 'electron'; import * as React from 'react'; import * as Icon from 'react-fontawesome'; import * as PlaylistsActions from '../../actions/PlaylistsActions'; import PlaylistsNavLink from '../PlaylistsNavLink/PlaylistsNavLink'; import { PlaylistModel } from '../../../shared/types/interfaces'; import * as styles from './PlaylistsNav.css'; const { Menu } = electron.remote; interface Props { playlists: PlaylistModel[]; } interface State { renamed: string | null; } class PlaylistsNav extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { renamed: null // the playlist being renamed if there's one }; this.blur = this.blur.bind(this); this.focus = this.focus.bind(this); this.keyDown = this.keyDown.bind(this); this.showContextMenu = this.showContextMenu.bind(this); this.createPlaylist = this.createPlaylist.bind(this); } showContextMenu(playlistId: string) { const template: electron.MenuItemConstructorOptions[] = [ { label: 'Rename', click: () => { this.setState({ renamed: playlistId }); } }, { label: 'Delete', click: async () => { await PlaylistsActions.remove(playlistId); } }, { type: 'separator' }, { label: 'Duplicate', click: async () => { await PlaylistsActions.duplicate(playlistId); } }, { type: 'separator' }, { label: 'Export', click: async () => { await PlaylistsActions.exportToM3u(playlistId); } } ]; const context = Menu.buildFromTemplate(template); context.popup({}); // Let it appear } async createPlaylist() { // Todo 'new playlist 1', 'new playlist 2' ... await PlaylistsActions.create('New playlist', [], false, true); } async rename(_id: string, name: string) { await PlaylistsActions.rename(_id, name); } async keyDown(e: React.KeyboardEvent<HTMLInputElement>) { e.persist(); switch (e.nativeEvent.code) { case 'Enter': { // Enter if (this.state.renamed && e.currentTarget) { await this.rename(this.state.renamed, e.currentTarget.value); this.setState({ renamed: null }); } break; } case 'Escape': { // Escape this.setState({ renamed: null }); break; } default: { break; } } } async blur(e: React.FocusEvent<HTMLInputElement>) { if (this.state.renamed) { await this.rename(this.state.renamed, e.currentTarget.value); } this.setState({ renamed: null }); } focus(e: React.FocusEvent<HTMLInputElement>) { e.currentTarget.select(); } render() { const { playlists } = this.props; // TODO (y.solovyov): extract into separate method that returns items const nav = playlists.map((elem) => { let navItemContent; if (elem._id === this.state.renamed) { navItemContent = ( <input className={styles.item__input} type='text' defaultValue={elem.name} onKeyDown={this.keyDown} onBlur={this.blur} onFocus={this.focus} autoFocus /> ); } else { navItemContent = ( <PlaylistsNavLink className={styles.item__link} playlistId={elem._id} onContextMenu={this.showContextMenu}> {elem.name} </PlaylistsNavLink> );
return ( <div className={styles.playlistsNav}> <div className={styles.playlistsNav__header}> <h4 className={styles.playlistsNav__title}>Playlists</h4> <div className={styles.actions}> <button className={styles.action} onClick={this.createPlaylist} title='New playlist'> <Icon name='plus' /> </button> </div> </div> <div className={styles.playlistsNav__body}>{nav}</div> </div> ); } } export default PlaylistsNav;
} return <div key={`playlist-${elem._id}`}>{navItemContent}</div>; });
random_line_split
Details.tsx
import React from 'react'; import { UISref } from '@uirouter/react'; import { Spinner } from 'core/widgets/spinners/Spinner'; interface IDetailsProps { loading: boolean; } interface IDetailsHeaderProps { icon: React.ReactNode; name: string; } interface IDetailsSFCWithExtras extends React.SFC<IDetailsProps> { Header: React.SFC<IDetailsHeaderProps>; } const CloseButton = (
<UISref to="^"> <a className="btn btn-link"> <span className="glyphicon glyphicon-remove" /> </a> </UISref> </div> ); const DetailsHeader: React.SFC<IDetailsHeaderProps> = (props) => ( <div className="header"> {CloseButton} <div className="header-text horizontal middle"> {props.icon} <h3 className="horizontal middle space-between flex-1">{props.name}</h3> </div> <div>{props.children}</div> </div> ); const loading = ( <div className="header"> <div className="horizontal center middle spinner-container"> <Spinner /> </div> </div> ); const Details: IDetailsSFCWithExtras = (props) => ( <div className="details-panel">{props.loading ? loading : props.children}</div> ); Details.Header = DetailsHeader; export { Details };
<div className="close-button">
random_line_split
async_core.py
#!/usr/local/bin/python3.4 # -*- coding: utf-8 -*- import threading import time import sys import trace from inspect import isgeneratorfunction import format class KillableThread(threading.Thread): """A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line':
self.killed = True class FunctionExecutor(KillableThread): def __init__(self, _f: 'the function to execute', _callback, args, kwargs): super().__init__() self._f = _f self._callback = _callback self.args = args self.kwargs = kwargs def run(self): ret = self._f(*self.args, **self.kwargs) if ret is not None: if repr(type(ret)) == '<class \'generator\'>': for i in ret: self._callback(i.format(color=format.color)) else: # TODO: make function to be only generators, not normal functions print('DEPRECATED: function "', self._f.cmdname, '" is using the return statement', sep='') self._callback(ret.format(color=format.color)) class ControlThread(threading.Thread): def __init__(self, _f, _callback, *args, **kwargs): super().__init__() self.watched_thread = FunctionExecutor(_f, _callback, args, kwargs) self._callback = _callback def run(self): self.watched_thread.start() time.sleep(3) if self.watched_thread.is_alive(): self.watched_thread.kill() self._callback('timeout')
raise SystemExit() return self.localtrace def kill(self):
random_line_split
async_core.py
#!/usr/local/bin/python3.4 # -*- coding: utf-8 -*- import threading import time import sys import trace from inspect import isgeneratorfunction import format class KillableThread(threading.Thread): """A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True class FunctionExecutor(KillableThread): def __init__(self, _f: 'the function to execute', _callback, args, kwargs):
def run(self): ret = self._f(*self.args, **self.kwargs) if ret is not None: if repr(type(ret)) == '<class \'generator\'>': for i in ret: self._callback(i.format(color=format.color)) else: # TODO: make function to be only generators, not normal functions print('DEPRECATED: function "', self._f.cmdname, '" is using the return statement', sep='') self._callback(ret.format(color=format.color)) class ControlThread(threading.Thread): def __init__(self, _f, _callback, *args, **kwargs): super().__init__() self.watched_thread = FunctionExecutor(_f, _callback, args, kwargs) self._callback = _callback def run(self): self.watched_thread.start() time.sleep(3) if self.watched_thread.is_alive(): self.watched_thread.kill() self._callback('timeout')
super().__init__() self._f = _f self._callback = _callback self.args = args self.kwargs = kwargs
identifier_body
async_core.py
#!/usr/local/bin/python3.4 # -*- coding: utf-8 -*- import threading import time import sys import trace from inspect import isgeneratorfunction import format class KillableThread(threading.Thread): """A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True class FunctionExecutor(KillableThread): def __init__(self, _f: 'the function to execute', _callback, args, kwargs): super().__init__() self._f = _f self._callback = _callback self.args = args self.kwargs = kwargs def run(self): ret = self._f(*self.args, **self.kwargs) if ret is not None:
class ControlThread(threading.Thread): def __init__(self, _f, _callback, *args, **kwargs): super().__init__() self.watched_thread = FunctionExecutor(_f, _callback, args, kwargs) self._callback = _callback def run(self): self.watched_thread.start() time.sleep(3) if self.watched_thread.is_alive(): self.watched_thread.kill() self._callback('timeout')
if repr(type(ret)) == '<class \'generator\'>': for i in ret: self._callback(i.format(color=format.color)) else: # TODO: make function to be only generators, not normal functions print('DEPRECATED: function "', self._f.cmdname, '" is using the return statement', sep='') self._callback(ret.format(color=format.color))
conditional_block
async_core.py
#!/usr/local/bin/python3.4 # -*- coding: utf-8 -*- import threading import time import sys import trace from inspect import isgeneratorfunction import format class KillableThread(threading.Thread): """A subclass of threading.Thread, with a kill() method provided by courtsey of Connelly Barnes.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def
(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True class FunctionExecutor(KillableThread): def __init__(self, _f: 'the function to execute', _callback, args, kwargs): super().__init__() self._f = _f self._callback = _callback self.args = args self.kwargs = kwargs def run(self): ret = self._f(*self.args, **self.kwargs) if ret is not None: if repr(type(ret)) == '<class \'generator\'>': for i in ret: self._callback(i.format(color=format.color)) else: # TODO: make function to be only generators, not normal functions print('DEPRECATED: function "', self._f.cmdname, '" is using the return statement', sep='') self._callback(ret.format(color=format.color)) class ControlThread(threading.Thread): def __init__(self, _f, _callback, *args, **kwargs): super().__init__() self.watched_thread = FunctionExecutor(_f, _callback, args, kwargs) self._callback = _callback def run(self): self.watched_thread.start() time.sleep(3) if self.watched_thread.is_alive(): self.watched_thread.kill() self._callback('timeout')
start
identifier_name