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 |
|---|---|---|---|---|
GlobalSearch.js | import React, { Component, PropTypes } from 'react' | import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class GlobalSearch extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch | random_line_split | |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, propertyKey) {
registerDecorator({
name: 'mainTextMaxLength',
target: object.constructor,
propertyName: propertyKey.toString(),
constraints: [length],
options,
validator: {
validate(value: AnyObject, args: ValidationArguments) | ,
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
}
| {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
}
return true;
} | identifier_body |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, propertyKey) {
registerDecorator({
name: 'mainTextMaxLength',
target: object.constructor,
propertyName: propertyKey.toString(),
constraints: [length],
options,
validator: {
validate(value: AnyObject, args: ValidationArguments) {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) |
return true;
},
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
}
| {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
} | conditional_block |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, propertyKey) {
registerDecorator({
name: 'mainTextMaxLength',
target: object.constructor,
propertyName: propertyKey.toString(),
constraints: [length],
options,
validator: {
| (value: AnyObject, args: ValidationArguments) {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
}
return true;
},
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
}
| validate | identifier_name |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, propertyKey) {
registerDecorator({
name: 'mainTextMaxLength', | validate(value: AnyObject, args: ValidationArguments) {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
}
return true;
},
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
} | target: object.constructor,
propertyName: propertyKey.toString(),
constraints: [length],
options,
validator: { | random_line_split |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Rice University nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
######################################################################
# Author: Mark Moll
from math import sin, cos, tan
from functools import partial
try:
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
except:
# if the ompl module is not in the PYTHONPATH assume it is installed in a
# subdirectory of the parent directory called "py-bindings."
from os.path import abspath, dirname, join
import sys
sys.path.insert(0, join(dirname(dirname(abspath(__file__))),'py-bindings'))
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
def kinematicCarODE(q, u, qdot):
theta = q[2];
carLength = 0.2;
qdot[0] = u[0] * cos(theta)
qdot[1] = u[0] * sin(theta)
qdot[2] = u[0] * tan(u[1]) / carLength
def isStateValid(spaceInformation, state):
# perform collision checking or check if other constraints are
# satisfied
return spaceInformation.satisfiesBounds(state)
def plan():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace(space, 2)
# set the bounds for the control space
cbounds = ob.RealVectorBounds(2) |
# define a simple setup class
ss = oc.SimpleSetup(cspace)
validityChecker = ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation()))
ss.setStateValidityChecker(validityChecker)
ode = oc.ODE(kinematicCarODE)
odeSolver = oc.ODEBasicSolver(ss.getSpaceInformation(), ode)
propagator = oc.ODESolver.getStatePropagator(odeSolver)
ss.setStatePropagator(propagator)
# create a start state
start = ob.State(space)
start().setX(-0.5);
start().setY(0.0);
start().setYaw(0.0);
# create a goal state
goal = ob.State(space);
goal().setX(0.0);
goal().setY(0.5);
goal().setYaw(0.0);
# set the start and goal states
ss.setStartAndGoalStates(start, goal, 0.05)
# attempt to solve the problem
solved = ss.solve(120.0)
if solved:
# print the path to screen
print("Found solution:\n%s" % ss.getSolutionPath().asGeometric().printAsMatrix())
if __name__ == "__main__":
plan() | cbounds.setLow(-.3)
cbounds.setHigh(.3)
cspace.setBounds(cbounds) | random_line_split |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Rice University nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
######################################################################
# Author: Mark Moll
from math import sin, cos, tan
from functools import partial
try:
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
except:
# if the ompl module is not in the PYTHONPATH assume it is installed in a
# subdirectory of the parent directory called "py-bindings."
from os.path import abspath, dirname, join
import sys
sys.path.insert(0, join(dirname(dirname(abspath(__file__))),'py-bindings'))
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
def kinematicCarODE(q, u, qdot):
theta = q[2];
carLength = 0.2;
qdot[0] = u[0] * cos(theta)
qdot[1] = u[0] * sin(theta)
qdot[2] = u[0] * tan(u[1]) / carLength
def isStateValid(spaceInformation, state):
# perform collision checking or check if other constraints are
# satisfied
return spaceInformation.satisfiesBounds(state)
def | ():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace(space, 2)
# set the bounds for the control space
cbounds = ob.RealVectorBounds(2)
cbounds.setLow(-.3)
cbounds.setHigh(.3)
cspace.setBounds(cbounds)
# define a simple setup class
ss = oc.SimpleSetup(cspace)
validityChecker = ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation()))
ss.setStateValidityChecker(validityChecker)
ode = oc.ODE(kinematicCarODE)
odeSolver = oc.ODEBasicSolver(ss.getSpaceInformation(), ode)
propagator = oc.ODESolver.getStatePropagator(odeSolver)
ss.setStatePropagator(propagator)
# create a start state
start = ob.State(space)
start().setX(-0.5);
start().setY(0.0);
start().setYaw(0.0);
# create a goal state
goal = ob.State(space);
goal().setX(0.0);
goal().setY(0.5);
goal().setYaw(0.0);
# set the start and goal states
ss.setStartAndGoalStates(start, goal, 0.05)
# attempt to solve the problem
solved = ss.solve(120.0)
if solved:
# print the path to screen
print("Found solution:\n%s" % ss.getSolutionPath().asGeometric().printAsMatrix())
if __name__ == "__main__":
plan()
| plan | identifier_name |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Rice University nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
######################################################################
# Author: Mark Moll
from math import sin, cos, tan
from functools import partial
try:
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
except:
# if the ompl module is not in the PYTHONPATH assume it is installed in a
# subdirectory of the parent directory called "py-bindings."
from os.path import abspath, dirname, join
import sys
sys.path.insert(0, join(dirname(dirname(abspath(__file__))),'py-bindings'))
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
def kinematicCarODE(q, u, qdot):
theta = q[2];
carLength = 0.2;
qdot[0] = u[0] * cos(theta)
qdot[1] = u[0] * sin(theta)
qdot[2] = u[0] * tan(u[1]) / carLength
def isStateValid(spaceInformation, state):
# perform collision checking or check if other constraints are
# satisfied
|
def plan():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace(space, 2)
# set the bounds for the control space
cbounds = ob.RealVectorBounds(2)
cbounds.setLow(-.3)
cbounds.setHigh(.3)
cspace.setBounds(cbounds)
# define a simple setup class
ss = oc.SimpleSetup(cspace)
validityChecker = ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation()))
ss.setStateValidityChecker(validityChecker)
ode = oc.ODE(kinematicCarODE)
odeSolver = oc.ODEBasicSolver(ss.getSpaceInformation(), ode)
propagator = oc.ODESolver.getStatePropagator(odeSolver)
ss.setStatePropagator(propagator)
# create a start state
start = ob.State(space)
start().setX(-0.5);
start().setY(0.0);
start().setYaw(0.0);
# create a goal state
goal = ob.State(space);
goal().setX(0.0);
goal().setY(0.5);
goal().setYaw(0.0);
# set the start and goal states
ss.setStartAndGoalStates(start, goal, 0.05)
# attempt to solve the problem
solved = ss.solve(120.0)
if solved:
# print the path to screen
print("Found solution:\n%s" % ss.getSolutionPath().asGeometric().printAsMatrix())
if __name__ == "__main__":
plan()
| return spaceInformation.satisfiesBounds(state) | identifier_body |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Rice University nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
######################################################################
# Author: Mark Moll
from math import sin, cos, tan
from functools import partial
try:
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
except:
# if the ompl module is not in the PYTHONPATH assume it is installed in a
# subdirectory of the parent directory called "py-bindings."
from os.path import abspath, dirname, join
import sys
sys.path.insert(0, join(dirname(dirname(abspath(__file__))),'py-bindings'))
from ompl import base as ob
from ompl import control as oc
from ompl import geometric as og
def kinematicCarODE(q, u, qdot):
theta = q[2];
carLength = 0.2;
qdot[0] = u[0] * cos(theta)
qdot[1] = u[0] * sin(theta)
qdot[2] = u[0] * tan(u[1]) / carLength
def isStateValid(spaceInformation, state):
# perform collision checking or check if other constraints are
# satisfied
return spaceInformation.satisfiesBounds(state)
def plan():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace(space, 2)
# set the bounds for the control space
cbounds = ob.RealVectorBounds(2)
cbounds.setLow(-.3)
cbounds.setHigh(.3)
cspace.setBounds(cbounds)
# define a simple setup class
ss = oc.SimpleSetup(cspace)
validityChecker = ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation()))
ss.setStateValidityChecker(validityChecker)
ode = oc.ODE(kinematicCarODE)
odeSolver = oc.ODEBasicSolver(ss.getSpaceInformation(), ode)
propagator = oc.ODESolver.getStatePropagator(odeSolver)
ss.setStatePropagator(propagator)
# create a start state
start = ob.State(space)
start().setX(-0.5);
start().setY(0.0);
start().setYaw(0.0);
# create a goal state
goal = ob.State(space);
goal().setX(0.0);
goal().setY(0.5);
goal().setYaw(0.0);
# set the start and goal states
ss.setStartAndGoalStates(start, goal, 0.05)
# attempt to solve the problem
solved = ss.solve(120.0)
if solved:
# print the path to screen
print("Found solution:\n%s" % ss.getSolutionPath().asGeometric().printAsMatrix())
if __name__ == "__main__":
| plan() | conditional_block | |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use ignore::Match;
use ignore::gitignore::GitignoreBuilder;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoError, CargoResult, internal};
use util::Config;
pub struct PathSource<'cfg> {
source_id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
recursive: bool,
}
impl<'cfg> PathSource<'cfg> {
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
///
/// This source will only return the package at precisely the `path`
/// specified, and it will be an error if there's not a package at `path`.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
source_id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
recursive: false,
}
}
/// Creates a new source which is walked recursively to discover packages.
///
/// This is similar to the `new` method except that instead of requiring a
/// valid package to be present at `root` the folder is walked entirely to
/// crawl for packages.
///
/// Note that this should be used with care and likely shouldn't be chosen
/// by default!
pub fn new_recursive(root: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
recursive: true,
.. PathSource::new(root, id, config)
}
}
pub fn root_package(&mut self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
self.update()?;
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.recursive {
ops::read_packages(&self.path, &self.source_id, self.config)
} else {
let path = self.path.join("Cargo.toml");
let (pkg, _) = ops::read_package(&path, &self.source_id, self.config)?;
Ok(vec![pkg])
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine the
/// set of files underneath this source's directory which are relevant for
/// building `pkg`.
///
/// The basic assumption of this method is that all files in the directory
/// are relevant for building this package, but it also contains logic to
/// use other methods like .gitignore to filter the list of files.
///
/// ## Pattern matching strategy
///
/// Migrating from a glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package != ignore_should_package {
if glob_should_package {
if no_include_option | else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and .git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
// .gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and .git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
// .gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if !file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path != pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p| !p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn supports_checksums(&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if !self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if !self.updated {
return Err(internal("BUG: source was not updated"));
}
let mut max = FileTime::zero();
let mut max_path = PathBuf::from("");
for file in self.list_files(pkg)? {
// An fs::stat error here is either because path is a
// broken symlink, a permissions error, or a race
// condition where this path was rm'ed - either way,
// we can ignore the error and treat the path's mtime
// as 0.
let mtime = fs::metadata(&file).map(|meta| {
FileTime::from_last_modification_time(&meta)
}).unwrap_or(FileTime::zero());
warn!("{} {}", mtime, file.display());
if mtime > max {
max = mtime;
max_path = file;
}
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(format!("{} ({})", max, max_path.display()))
}
}
| {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} | conditional_block |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use ignore::Match;
use ignore::gitignore::GitignoreBuilder;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoError, CargoResult, internal};
use util::Config;
pub struct PathSource<'cfg> {
source_id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
recursive: bool,
}
impl<'cfg> PathSource<'cfg> {
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
///
/// This source will only return the package at precisely the `path`
/// specified, and it will be an error if there's not a package at `path`.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
source_id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
recursive: false,
}
}
/// Creates a new source which is walked recursively to discover packages.
///
/// This is similar to the `new` method except that instead of requiring a
/// valid package to be present at `root` the folder is walked entirely to
/// crawl for packages.
///
/// Note that this should be used with care and likely shouldn't be chosen
/// by default!
pub fn new_recursive(root: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
recursive: true,
.. PathSource::new(root, id, config)
}
}
pub fn root_package(&mut self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
self.update()?;
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.recursive {
ops::read_packages(&self.path, &self.source_id, self.config)
} else {
let path = self.path.join("Cargo.toml");
let (pkg, _) = ops::read_package(&path, &self.source_id, self.config)?;
Ok(vec![pkg])
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine the
/// set of files underneath this source's directory which are relevant for
/// building `pkg`.
///
/// The basic assumption of this method is that all files in the directory
/// are relevant for building this package, but it also contains logic to
/// use other methods like .gitignore to filter the list of files.
///
/// ## Pattern matching strategy
///
/// Migrating from a glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package != ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and .git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
// .gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and .git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
// .gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if !file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path != pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p| !p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn | (&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if !self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if !self.updated {
return Err(internal("BUG: source was not updated"));
}
let mut max = FileTime::zero();
let mut max_path = PathBuf::from("");
for file in self.list_files(pkg)? {
// An fs::stat error here is either because path is a
// broken symlink, a permissions error, or a race
// condition where this path was rm'ed - either way,
// we can ignore the error and treat the path's mtime
// as 0.
let mtime = fs::metadata(&file).map(|meta| {
FileTime::from_last_modification_time(&meta)
}).unwrap_or(FileTime::zero());
warn!("{} {}", mtime, file.display());
if mtime > max {
max = mtime;
max_path = file;
}
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(format!("{} ({})", max, max_path.display()))
}
}
| supports_checksums | identifier_name |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use ignore::Match;
use ignore::gitignore::GitignoreBuilder;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoError, CargoResult, internal};
use util::Config;
pub struct PathSource<'cfg> {
source_id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
recursive: bool,
}
impl<'cfg> PathSource<'cfg> {
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
///
/// This source will only return the package at precisely the `path`
/// specified, and it will be an error if there's not a package at `path`.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
source_id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
recursive: false,
}
}
/// Creates a new source which is walked recursively to discover packages.
///
/// This is similar to the `new` method except that instead of requiring a
/// valid package to be present at `root` the folder is walked entirely to
/// crawl for packages.
///
/// Note that this should be used with care and likely shouldn't be chosen
/// by default!
pub fn new_recursive(root: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
recursive: true,
.. PathSource::new(root, id, config)
}
}
pub fn root_package(&mut self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
self.update()?;
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.recursive {
ops::read_packages(&self.path, &self.source_id, self.config)
} else {
let path = self.path.join("Cargo.toml");
let (pkg, _) = ops::read_package(&path, &self.source_id, self.config)?;
Ok(vec![pkg])
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine the
/// set of files underneath this source's directory which are relevant for
/// building `pkg`.
///
/// The basic assumption of this method is that all files in the directory
/// are relevant for building this package, but it also contains logic to
/// use other methods like .gitignore to filter the list of files.
///
/// ## Pattern matching strategy
///
/// Migrating from a glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package != ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and .git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
// .gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and .git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
// .gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if !file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path != pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p| !p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn supports_checksums(&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if !self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> |
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if !self.updated {
return Err(internal("BUG: source was not updated"));
}
let mut max = FileTime::zero();
let mut max_path = PathBuf::from("");
for file in self.list_files(pkg)? {
// An fs::stat error here is either because path is a
// broken symlink, a permissions error, or a race
// condition where this path was rm'ed - either way,
// we can ignore the error and treat the path's mtime
// as 0.
let mtime = fs::metadata(&file).map(|meta| {
FileTime::from_last_modification_time(&meta)
}).unwrap_or(FileTime::zero());
warn!("{} {}", mtime, file.display());
if mtime > max {
max = mtime;
max_path = file;
}
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(format!("{} ({})", max, max_path.display()))
}
}
| {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
} | identifier_body |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use ignore::Match;
use ignore::gitignore::GitignoreBuilder;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoError, CargoResult, internal};
use util::Config;
pub struct PathSource<'cfg> {
source_id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
recursive: bool,
}
impl<'cfg> PathSource<'cfg> {
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
///
/// This source will only return the package at precisely the `path`
/// specified, and it will be an error if there's not a package at `path`.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
source_id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
recursive: false,
}
}
/// Creates a new source which is walked recursively to discover packages.
///
/// This is similar to the `new` method except that instead of requiring a
/// valid package to be present at `root` the folder is walked entirely to
/// crawl for packages.
///
/// Note that this should be used with care and likely shouldn't be chosen
/// by default!
pub fn new_recursive(root: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
PathSource {
recursive: true,
.. PathSource::new(root, id, config)
}
}
pub fn root_package(&mut self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
self.update()?;
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.recursive {
ops::read_packages(&self.path, &self.source_id, self.config)
} else {
let path = self.path.join("Cargo.toml");
let (pkg, _) = ops::read_package(&path, &self.source_id, self.config)?;
Ok(vec![pkg])
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine the
/// set of files underneath this source's directory which are relevant for
/// building `pkg`.
///
/// The basic assumption of this method is that all files in the directory
/// are relevant for building this package, but it also contains logic to
/// use other methods like .gitignore to filter the list of files.
///
/// ## Pattern matching strategy
///
/// Migrating from a glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package != ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and .git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
// .gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and .git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
// .gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if !file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path != pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p| !p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn supports_checksums(&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if !self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if !self.updated {
return Err(internal("BUG: source was not updated"));
}
let mut max = FileTime::zero();
let mut max_path = PathBuf::from("");
for file in self.list_files(pkg)? {
// An fs::stat error here is either because path is a
// broken symlink, a permissions error, or a race
// condition where this path was rm'ed - either way,
// we can ignore the error and treat the path's mtime
// as 0.
let mtime = fs::metadata(&file).map(|meta| {
FileTime::from_last_modification_time(&meta)
}).unwrap_or(FileTime::zero());
warn!("{} {}", mtime, file.display());
if mtime > max {
max = mtime;
max_path = file;
}
} | trace!("fingerprint {}: {}", self.path.display(), max);
Ok(format!("{} ({})", max, max_path.display()))
}
} | random_line_split | |
replViewer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction } from 'vs/base/common/actions';
import { isFullWidthCharacter, removeAnsiEscapeCodes, endsWith } from 'vs/base/common/strings';
import uri from 'vs/base/common/uri';
import { isMacintosh } from 'vs/base/common/platform';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { ITree, IAccessibilityProvider, IDataSource, IRenderer } from 'vs/base/parts/tree/browser/tree';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { ICancelableEvent } from 'vs/base/parts/tree/browser/treeDefaults';
import { IExpressionContainer, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Model, OutputNameValueElement, Expression, OutputElement, Variable } from 'vs/workbench/parts/debug/common/debugModel';
import { renderVariable, renderExpressionValue, IVariableTemplateData, BaseDebugController } from 'vs/workbench/parts/debug/electron-browser/debugViewer';
import { ClearReplAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
const $ = dom.$;
export class ReplExpressionsDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof Model || (<IExpressionContainer>element).hasChildren;
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof Model) {
return TPromise.as(element.getReplElements());
}
if (element instanceof OutputNameValueElement) {
return TPromise.as(element.getChildren());
}
if (element instanceof OutputElement) {
return TPromise.as(null);
}
return (<IExpression>element).getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExpressionTemplateData {
input: HTMLElement;
output: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
interface IValueOutputTemplateData {
container: HTMLElement;
counter: HTMLElement;
value: HTMLElement;
}
interface IKeyValueOutputTemplateData {
container: HTMLElement;
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
export class | implements IRenderer {
private static VARIABLE_TEMPLATE_ID = 'variable';
private static EXPRESSION_TEMPLATE_ID = 'inputOutputPair';
private static VALUE_OUTPUT_TEMPLATE_ID = 'outputValue';
private static NAME_VALUE_OUTPUT_TEMPLATE_ID = 'outputNameValue';
private static FILE_LOCATION_PATTERNS: RegExp[] = [
// group 0: the full thing :)
// group 1: absolute path
// group 2: drive letter on windows with trailing backslash or leading slash on mac/linux
// group 3: line number
// group 4: column number
// eg: at Context.<anonymous> (c:\Users\someone\Desktop\mocha-runner\test\test.js:26:11)
/((\/|[a-zA-Z]:\\)[^\(\)<>\'\"\[\]]+):(\d+):(\d+)/
];
private static LINE_HEIGHT_PX = 18;
private width: number;
private characterWidth: number;
constructor(
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
if (element instanceof Variable && (element.hasChildren || (element.name !== null))) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
if (element instanceof Expression && element.hasChildren) {
return 2 * ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
return this.getHeightForString(element.value) + (element instanceof Expression ? this.getHeightForString(element.name) : 0);
}
private getHeightForString(s: string): number {
if (!s || !s.length || !this.width || this.width <= 0 || !this.characterWidth || this.characterWidth <= 0) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
// Last new line should be ignored since the repl elements are by design split by rows
if (endsWith(s, '\n')) {
s = s.substr(0, s.length - 1);
}
const lines = removeAnsiEscapeCodes(s).split('\n');
const numLines = lines.reduce((lineCount: number, line: string) => {
let lineLength = 0;
for (let i = 0; i < line.length; i++) {
lineLength += isFullWidthCharacter(line.charCodeAt(i)) ? 2 : 1;
}
return lineCount + Math.floor(lineLength * this.characterWidth / this.width);
}, lines.length);
return ReplExpressionsRenderer.LINE_HEIGHT_PX * numLines;
}
public setWidth(fullWidth: number, characterWidth: number): void {
this.width = fullWidth;
this.characterWidth = characterWidth;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Variable && element.name) {
return ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
if (element instanceof Expression) {
return ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID;
}
if (element instanceof OutputElement || (element instanceof Variable && !element.name)) {
// Variable with no name is a top level variable which should be rendered like an output element #17404
return ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID;
}
if (element instanceof OutputNameValueElement) {
return ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
let data: IExpressionTemplateData = Object.create(null);
dom.addClass(container, 'input-output-pair');
data.input = dom.append(container, $('.input.expression'));
data.output = dom.append(container, $('.output.expression'));
data.value = dom.append(data.output, $('span.value'));
data.annotation = dom.append(data.output, $('span'));
return data;
}
if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
let data: IValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
let expression = dom.append(container, $('.output.expression'));
data.container = container;
data.counter = dom.append(expression, $('div.counter'));
data.value = dom.append(expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
let data: IKeyValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
data.container = container;
data.expression = dom.append(container, $('.output.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
data.annotation = dom.append(data.expression, $('span'));
return data;
}
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
renderVariable(tree, element, templateData, false);
} else if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
this.renderExpression(tree, element, templateData);
} else if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputValue(element, templateData);
} else if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputNameValue(tree, element, templateData);
}
}
private renderExpression(tree: ITree, expression: IExpression, templateData: IExpressionTemplateData): void {
templateData.input.textContent = expression.name;
renderExpressionValue(expression, templateData.value, {
preserveWhitespace: !expression.hasChildren,
showHover: false
});
if (expression.hasChildren) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = nls.localize('stateCapture', "Object state is captured from first evaluation");
}
}
private renderOutputValue(output: OutputElement, templateData: IValueOutputTemplateData): void {
// counter
if (output.counter > 1) {
templateData.counter.textContent = String(output.counter);
templateData.counter.className = (output.severity === severity.Warning) ? 'counter warn' : (output.severity === severity.Error) ? 'counter error' : 'counter info';
} else {
templateData.counter.textContent = '';
templateData.counter.className = 'counter';
}
// value
dom.clearNode(templateData.value);
templateData.value.className = '';
let result = this.handleANSIOutput(output.value);
if (typeof result === 'string') {
renderExpressionValue(result, templateData.value, {
preserveWhitespace: true,
showHover: false
});
} else {
templateData.value.appendChild(result);
}
dom.addClass(templateData.value, (output.severity === severity.Warning) ? 'warn' : (output.severity === severity.Error) ? 'error' : 'info');
}
private renderOutputNameValue(tree: ITree, output: OutputNameValueElement, templateData: IKeyValueOutputTemplateData): void {
// key
if (output.name) {
templateData.name.textContent = `${output.name}:`;
} else {
templateData.name.textContent = '';
}
// value
renderExpressionValue(output.value, templateData.value, {
preserveWhitespace: true,
showHover: false
});
// annotation if any
if (output.annotation) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = output.annotation;
} else {
templateData.annotation.className = '';
templateData.annotation.title = '';
}
}
private handleANSIOutput(text: string): HTMLElement | string {
let tokensContainer: HTMLSpanElement;
let currentToken: HTMLSpanElement;
let buffer: string = '';
for (let i = 0, len = text.length; i < len; i++) {
// start of ANSI escape sequence (see http://ascii-table.com/ansi-escape-sequences.php)
if (text.charCodeAt(i) === 27) {
let index = i;
let chr = (++index < len ? text.charAt(index) : null);
if (chr && chr === '[') {
let code: string = null;
chr = (++index < len ? text.charAt(index) : null);
if (chr && chr >= '0' && chr <= '9') {
code = chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (chr && chr >= '0' && chr <= '9') {
code += chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (code === null) {
code = '0';
}
if (chr === 'm') { // set text color/mode.
// only respect text-foreground ranges and ignore the values for "black" & "white" because those
// only make sense in combination with text-background ranges which we currently not support
let parsedMode = parseInt(code, 10);
let token = document.createElement('span');
if ((parsedMode >= 30 && parsedMode <= 37) || (parsedMode >= 90 && parsedMode <= 97)) {
token.className = 'code' + parsedMode;
} else if (parsedMode === 1) {
token.className = 'code-bold';
}
// we need a tokens container now
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
// flush text buffer if we have any
if (buffer) {
this.insert(this.handleLinks(buffer), currentToken || tokensContainer);
buffer = '';
}
currentToken = token;
tokensContainer.appendChild(token);
i = index;
}
}
}
// normal text
else {
buffer += text[i];
}
}
// flush remaining text buffer if we have any
if (buffer) {
let res = this.handleLinks(buffer);
if (typeof res !== 'string' || currentToken) {
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
this.insert(res, currentToken || tokensContainer);
}
}
return tokensContainer || buffer;
}
private insert(arg: HTMLElement | string, target: HTMLElement): void {
if (typeof arg === 'string') {
target.textContent = arg;
} else {
target.appendChild(arg);
}
}
private handleLinks(text: string): HTMLElement | string {
let linkContainer: HTMLElement;
for (let pattern of ReplExpressionsRenderer.FILE_LOCATION_PATTERNS) {
pattern.lastIndex = 0; // the holy grail of software development
const match = pattern.exec(text);
let resource: uri = null;
try {
resource = match && uri.file(match[1]);
} catch (e) { }
if (resource) {
linkContainer = document.createElement('span');
let textBeforeLink = text.substr(0, match.index);
if (textBeforeLink) {
let span = document.createElement('span');
span.textContent = textBeforeLink;
linkContainer.appendChild(span);
}
const link = document.createElement('a');
link.textContent = text.substr(match.index, match[0].length);
link.title = isMacintosh ? nls.localize('fileLinkMac', "Click to follow (Cmd + click opens to the side)") : nls.localize('fileLink', "Click to follow (Ctrl + click opens to the side)");
linkContainer.appendChild(link);
link.onclick = (e) => this.onLinkClick(new StandardMouseEvent(e), resource, Number(match[3]), Number(match[4]));
let textAfterLink = text.substr(match.index + match[0].length);
if (textAfterLink) {
let span = document.createElement('span');
span.textContent = textAfterLink;
linkContainer.appendChild(span);
}
break; // support one link per line for now
}
}
return linkContainer || text;
}
private onLinkClick(event: IMouseEvent, resource: uri, line: number, column: number): void {
const selection = window.getSelection();
if (selection.type === 'Range') {
return; // do not navigate when user is selecting
}
event.preventDefault();
this.editorService.openEditor({
resource,
options: {
selection: {
startLineNumber: line,
startColumn: column
}
}
}, event.ctrlKey || event.metaKey).done(null, errors.onUnexpectedError);
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
export class ReplExpressionsAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Variable) {
return nls.localize('replVariableAriaLabel', "Variable {0} has value {1}, read eval print loop, debug", (<Variable>element).name, (<Variable>element).value);
}
if (element instanceof Expression) {
return nls.localize('replExpressionAriaLabel', "Expression {0} has value {1}, read eval print loop, debug", (<Expression>element).name, (<Expression>element).value);
}
if (element instanceof OutputElement) {
return nls.localize('replValueOutputAriaLabel', "{0}, read eval print loop, debug", (<OutputElement>element).value);
}
if (element instanceof OutputNameValueElement) {
return nls.localize('replKeyValueOutputAriaLabel', "Output variable {0} has value {1}, read eval print loop, debug", (<OutputNameValueElement>element).name, (<OutputNameValueElement>element).value);
}
return null;
}
}
export class ReplExpressionsActionProvider implements IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
return true;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
actions.push(new CopyAction(CopyAction.ID, CopyAction.LABEL));
actions.push(this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class ReplExpressionsController extends BaseDebugController {
private lastSelectedString: string = null;
public toFocusOnClick: { focus(): void };
protected onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean {
const mouseEvent = <IMouseEvent>eventish;
// input and output are one element in the tree => we only expand if the user clicked on the output.
if ((element.reference > 0 || (element instanceof OutputNameValueElement && element.hasChildren)) && mouseEvent.target.className.indexOf('input expression') === -1) {
super.onLeftClick(tree, element, eventish, origin);
tree.clearFocus();
tree.deselect(element);
}
const selection = window.getSelection();
if (selection.type !== 'Range' || this.lastSelectedString === selection.toString()) {
// only focus the input if the user is not currently selecting.
this.toFocusOnClick.focus();
}
this.lastSelectedString = selection.toString();
return true;
}
protected onDown(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getFocus()) {
return super.onDown(tree, event);
}
const payload = { origin: 'keyboard', originalEvent: event };
tree.focusLast(payload);
tree.reveal(tree.getFocus()).done(null, errors.onUnexpectedError);
return true;
}
}
| ReplExpressionsRenderer | identifier_name |
replViewer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction } from 'vs/base/common/actions';
import { isFullWidthCharacter, removeAnsiEscapeCodes, endsWith } from 'vs/base/common/strings';
import uri from 'vs/base/common/uri';
import { isMacintosh } from 'vs/base/common/platform';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { ITree, IAccessibilityProvider, IDataSource, IRenderer } from 'vs/base/parts/tree/browser/tree';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { ICancelableEvent } from 'vs/base/parts/tree/browser/treeDefaults';
import { IExpressionContainer, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Model, OutputNameValueElement, Expression, OutputElement, Variable } from 'vs/workbench/parts/debug/common/debugModel';
import { renderVariable, renderExpressionValue, IVariableTemplateData, BaseDebugController } from 'vs/workbench/parts/debug/electron-browser/debugViewer';
import { ClearReplAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
const $ = dom.$;
export class ReplExpressionsDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof Model || (<IExpressionContainer>element).hasChildren;
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof Model) {
return TPromise.as(element.getReplElements());
}
if (element instanceof OutputNameValueElement) {
return TPromise.as(element.getChildren());
}
if (element instanceof OutputElement) {
return TPromise.as(null);
}
return (<IExpression>element).getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExpressionTemplateData {
input: HTMLElement;
output: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
interface IValueOutputTemplateData {
container: HTMLElement;
counter: HTMLElement;
value: HTMLElement;
}
interface IKeyValueOutputTemplateData {
container: HTMLElement;
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
export class ReplExpressionsRenderer implements IRenderer {
private static VARIABLE_TEMPLATE_ID = 'variable';
private static EXPRESSION_TEMPLATE_ID = 'inputOutputPair';
private static VALUE_OUTPUT_TEMPLATE_ID = 'outputValue';
private static NAME_VALUE_OUTPUT_TEMPLATE_ID = 'outputNameValue';
private static FILE_LOCATION_PATTERNS: RegExp[] = [
// group 0: the full thing :)
// group 1: absolute path
// group 2: drive letter on windows with trailing backslash or leading slash on mac/linux
// group 3: line number
// group 4: column number
// eg: at Context.<anonymous> (c:\Users\someone\Desktop\mocha-runner\test\test.js:26:11)
/((\/|[a-zA-Z]:\\)[^\(\)<>\'\"\[\]]+):(\d+):(\d+)/
];
private static LINE_HEIGHT_PX = 18;
private width: number;
private characterWidth: number;
constructor(
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
if (element instanceof Variable && (element.hasChildren || (element.name !== null))) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
if (element instanceof Expression && element.hasChildren) {
return 2 * ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
return this.getHeightForString(element.value) + (element instanceof Expression ? this.getHeightForString(element.name) : 0);
}
private getHeightForString(s: string): number {
if (!s || !s.length || !this.width || this.width <= 0 || !this.characterWidth || this.characterWidth <= 0) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
// Last new line should be ignored since the repl elements are by design split by rows
if (endsWith(s, '\n')) {
s = s.substr(0, s.length - 1);
}
const lines = removeAnsiEscapeCodes(s).split('\n');
const numLines = lines.reduce((lineCount: number, line: string) => {
let lineLength = 0;
for (let i = 0; i < line.length; i++) {
lineLength += isFullWidthCharacter(line.charCodeAt(i)) ? 2 : 1;
}
return lineCount + Math.floor(lineLength * this.characterWidth / this.width);
}, lines.length);
return ReplExpressionsRenderer.LINE_HEIGHT_PX * numLines;
}
public setWidth(fullWidth: number, characterWidth: number): void {
this.width = fullWidth;
this.characterWidth = characterWidth;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Variable && element.name) {
return ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
if (element instanceof Expression) {
return ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID;
}
if (element instanceof OutputElement || (element instanceof Variable && !element.name)) {
// Variable with no name is a top level variable which should be rendered like an output element #17404
return ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID;
}
if (element instanceof OutputNameValueElement) {
return ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
let data: IExpressionTemplateData = Object.create(null);
dom.addClass(container, 'input-output-pair');
data.input = dom.append(container, $('.input.expression'));
data.output = dom.append(container, $('.output.expression'));
data.value = dom.append(data.output, $('span.value'));
data.annotation = dom.append(data.output, $('span'));
return data;
}
if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
let data: IValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
let expression = dom.append(container, $('.output.expression'));
data.container = container;
data.counter = dom.append(expression, $('div.counter'));
data.value = dom.append(expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
let data: IKeyValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
data.container = container;
data.expression = dom.append(container, $('.output.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
data.annotation = dom.append(data.expression, $('span'));
return data;
}
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
renderVariable(tree, element, templateData, false);
} else if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
this.renderExpression(tree, element, templateData);
} else if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputValue(element, templateData);
} else if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputNameValue(tree, element, templateData);
}
}
private renderExpression(tree: ITree, expression: IExpression, templateData: IExpressionTemplateData): void {
templateData.input.textContent = expression.name;
renderExpressionValue(expression, templateData.value, {
preserveWhitespace: !expression.hasChildren,
showHover: false
});
if (expression.hasChildren) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = nls.localize('stateCapture', "Object state is captured from first evaluation");
}
}
private renderOutputValue(output: OutputElement, templateData: IValueOutputTemplateData): void {
// counter
if (output.counter > 1) {
templateData.counter.textContent = String(output.counter);
templateData.counter.className = (output.severity === severity.Warning) ? 'counter warn' : (output.severity === severity.Error) ? 'counter error' : 'counter info';
} else {
templateData.counter.textContent = '';
templateData.counter.className = 'counter';
}
// value
dom.clearNode(templateData.value);
templateData.value.className = '';
let result = this.handleANSIOutput(output.value);
if (typeof result === 'string') {
renderExpressionValue(result, templateData.value, {
preserveWhitespace: true,
showHover: false
});
} else {
templateData.value.appendChild(result);
}
dom.addClass(templateData.value, (output.severity === severity.Warning) ? 'warn' : (output.severity === severity.Error) ? 'error' : 'info');
}
private renderOutputNameValue(tree: ITree, output: OutputNameValueElement, templateData: IKeyValueOutputTemplateData): void {
// key
if (output.name) {
templateData.name.textContent = `${output.name}:`;
} else {
templateData.name.textContent = '';
}
// value
renderExpressionValue(output.value, templateData.value, {
preserveWhitespace: true,
showHover: false
});
// annotation if any
if (output.annotation) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = output.annotation;
} else {
templateData.annotation.className = '';
templateData.annotation.title = '';
}
}
private handleANSIOutput(text: string): HTMLElement | string {
let tokensContainer: HTMLSpanElement;
let currentToken: HTMLSpanElement;
let buffer: string = '';
for (let i = 0, len = text.length; i < len; i++) {
// start of ANSI escape sequence (see http://ascii-table.com/ansi-escape-sequences.php)
if (text.charCodeAt(i) === 27) {
let index = i;
let chr = (++index < len ? text.charAt(index) : null);
if (chr && chr === '[') {
let code: string = null;
chr = (++index < len ? text.charAt(index) : null);
if (chr && chr >= '0' && chr <= '9') {
code = chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (chr && chr >= '0' && chr <= '9') {
code += chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (code === null) {
code = '0';
}
if (chr === 'm') { // set text color/mode.
// only respect text-foreground ranges and ignore the values for "black" & "white" because those
// only make sense in combination with text-background ranges which we currently not support
let parsedMode = parseInt(code, 10);
let token = document.createElement('span');
if ((parsedMode >= 30 && parsedMode <= 37) || (parsedMode >= 90 && parsedMode <= 97)) {
token.className = 'code' + parsedMode;
} else if (parsedMode === 1) {
token.className = 'code-bold';
}
// we need a tokens container now
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
// flush text buffer if we have any
if (buffer) {
this.insert(this.handleLinks(buffer), currentToken || tokensContainer);
buffer = '';
}
currentToken = token;
tokensContainer.appendChild(token);
i = index;
}
}
}
// normal text
else {
buffer += text[i];
}
}
// flush remaining text buffer if we have any
if (buffer) {
let res = this.handleLinks(buffer);
if (typeof res !== 'string' || currentToken) {
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
this.insert(res, currentToken || tokensContainer);
}
}
return tokensContainer || buffer;
}
private insert(arg: HTMLElement | string, target: HTMLElement): void {
if (typeof arg === 'string') {
target.textContent = arg;
} else {
target.appendChild(arg);
}
}
private handleLinks(text: string): HTMLElement | string {
let linkContainer: HTMLElement;
for (let pattern of ReplExpressionsRenderer.FILE_LOCATION_PATTERNS) {
pattern.lastIndex = 0; // the holy grail of software development
const match = pattern.exec(text);
let resource: uri = null;
try {
resource = match && uri.file(match[1]);
} catch (e) { }
if (resource) {
linkContainer = document.createElement('span');
let textBeforeLink = text.substr(0, match.index);
if (textBeforeLink) |
const link = document.createElement('a');
link.textContent = text.substr(match.index, match[0].length);
link.title = isMacintosh ? nls.localize('fileLinkMac', "Click to follow (Cmd + click opens to the side)") : nls.localize('fileLink', "Click to follow (Ctrl + click opens to the side)");
linkContainer.appendChild(link);
link.onclick = (e) => this.onLinkClick(new StandardMouseEvent(e), resource, Number(match[3]), Number(match[4]));
let textAfterLink = text.substr(match.index + match[0].length);
if (textAfterLink) {
let span = document.createElement('span');
span.textContent = textAfterLink;
linkContainer.appendChild(span);
}
break; // support one link per line for now
}
}
return linkContainer || text;
}
private onLinkClick(event: IMouseEvent, resource: uri, line: number, column: number): void {
const selection = window.getSelection();
if (selection.type === 'Range') {
return; // do not navigate when user is selecting
}
event.preventDefault();
this.editorService.openEditor({
resource,
options: {
selection: {
startLineNumber: line,
startColumn: column
}
}
}, event.ctrlKey || event.metaKey).done(null, errors.onUnexpectedError);
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
export class ReplExpressionsAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Variable) {
return nls.localize('replVariableAriaLabel', "Variable {0} has value {1}, read eval print loop, debug", (<Variable>element).name, (<Variable>element).value);
}
if (element instanceof Expression) {
return nls.localize('replExpressionAriaLabel', "Expression {0} has value {1}, read eval print loop, debug", (<Expression>element).name, (<Expression>element).value);
}
if (element instanceof OutputElement) {
return nls.localize('replValueOutputAriaLabel', "{0}, read eval print loop, debug", (<OutputElement>element).value);
}
if (element instanceof OutputNameValueElement) {
return nls.localize('replKeyValueOutputAriaLabel', "Output variable {0} has value {1}, read eval print loop, debug", (<OutputNameValueElement>element).name, (<OutputNameValueElement>element).value);
}
return null;
}
}
export class ReplExpressionsActionProvider implements IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
return true;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
actions.push(new CopyAction(CopyAction.ID, CopyAction.LABEL));
actions.push(this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class ReplExpressionsController extends BaseDebugController {
private lastSelectedString: string = null;
public toFocusOnClick: { focus(): void };
protected onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean {
const mouseEvent = <IMouseEvent>eventish;
// input and output are one element in the tree => we only expand if the user clicked on the output.
if ((element.reference > 0 || (element instanceof OutputNameValueElement && element.hasChildren)) && mouseEvent.target.className.indexOf('input expression') === -1) {
super.onLeftClick(tree, element, eventish, origin);
tree.clearFocus();
tree.deselect(element);
}
const selection = window.getSelection();
if (selection.type !== 'Range' || this.lastSelectedString === selection.toString()) {
// only focus the input if the user is not currently selecting.
this.toFocusOnClick.focus();
}
this.lastSelectedString = selection.toString();
return true;
}
protected onDown(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getFocus()) {
return super.onDown(tree, event);
}
const payload = { origin: 'keyboard', originalEvent: event };
tree.focusLast(payload);
tree.reveal(tree.getFocus()).done(null, errors.onUnexpectedError);
return true;
}
}
| {
let span = document.createElement('span');
span.textContent = textBeforeLink;
linkContainer.appendChild(span);
} | conditional_block |
replViewer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction } from 'vs/base/common/actions';
import { isFullWidthCharacter, removeAnsiEscapeCodes, endsWith } from 'vs/base/common/strings';
import uri from 'vs/base/common/uri';
import { isMacintosh } from 'vs/base/common/platform';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { ITree, IAccessibilityProvider, IDataSource, IRenderer } from 'vs/base/parts/tree/browser/tree';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { ICancelableEvent } from 'vs/base/parts/tree/browser/treeDefaults';
import { IExpressionContainer, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Model, OutputNameValueElement, Expression, OutputElement, Variable } from 'vs/workbench/parts/debug/common/debugModel';
import { renderVariable, renderExpressionValue, IVariableTemplateData, BaseDebugController } from 'vs/workbench/parts/debug/electron-browser/debugViewer';
import { ClearReplAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
const $ = dom.$;
export class ReplExpressionsDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof Model || (<IExpressionContainer>element).hasChildren;
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof Model) {
return TPromise.as(element.getReplElements());
}
if (element instanceof OutputNameValueElement) {
return TPromise.as(element.getChildren());
}
if (element instanceof OutputElement) {
return TPromise.as(null);
}
return (<IExpression>element).getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> {
return TPromise.as(null);
}
}
interface IExpressionTemplateData {
input: HTMLElement;
output: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
interface IValueOutputTemplateData {
container: HTMLElement;
counter: HTMLElement;
value: HTMLElement;
}
interface IKeyValueOutputTemplateData {
container: HTMLElement;
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
export class ReplExpressionsRenderer implements IRenderer {
private static VARIABLE_TEMPLATE_ID = 'variable';
private static EXPRESSION_TEMPLATE_ID = 'inputOutputPair';
private static VALUE_OUTPUT_TEMPLATE_ID = 'outputValue';
private static NAME_VALUE_OUTPUT_TEMPLATE_ID = 'outputNameValue';
private static FILE_LOCATION_PATTERNS: RegExp[] = [
// group 0: the full thing :)
// group 1: absolute path
// group 2: drive letter on windows with trailing backslash or leading slash on mac/linux
// group 3: line number
// group 4: column number
// eg: at Context.<anonymous> (c:\Users\someone\Desktop\mocha-runner\test\test.js:26:11)
/((\/|[a-zA-Z]:\\)[^\(\)<>\'\"\[\]]+):(\d+):(\d+)/
];
private static LINE_HEIGHT_PX = 18;
private width: number;
private characterWidth: number;
constructor(
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
if (element instanceof Variable && (element.hasChildren || (element.name !== null))) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
if (element instanceof Expression && element.hasChildren) {
return 2 * ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
return this.getHeightForString(element.value) + (element instanceof Expression ? this.getHeightForString(element.name) : 0);
}
private getHeightForString(s: string): number {
if (!s || !s.length || !this.width || this.width <= 0 || !this.characterWidth || this.characterWidth <= 0) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
// Last new line should be ignored since the repl elements are by design split by rows
if (endsWith(s, '\n')) {
s = s.substr(0, s.length - 1);
}
const lines = removeAnsiEscapeCodes(s).split('\n');
const numLines = lines.reduce((lineCount: number, line: string) => {
let lineLength = 0;
for (let i = 0; i < line.length; i++) {
lineLength += isFullWidthCharacter(line.charCodeAt(i)) ? 2 : 1;
}
return lineCount + Math.floor(lineLength * this.characterWidth / this.width);
}, lines.length);
return ReplExpressionsRenderer.LINE_HEIGHT_PX * numLines;
}
public setWidth(fullWidth: number, characterWidth: number): void {
this.width = fullWidth;
this.characterWidth = characterWidth;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Variable && element.name) {
return ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
if (element instanceof Expression) {
return ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID;
}
if (element instanceof OutputElement || (element instanceof Variable && !element.name)) {
// Variable with no name is a top level variable which should be rendered like an output element #17404
return ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID;
}
if (element instanceof OutputNameValueElement) {
return ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
let data: IExpressionTemplateData = Object.create(null);
dom.addClass(container, 'input-output-pair');
data.input = dom.append(container, $('.input.expression'));
data.output = dom.append(container, $('.output.expression'));
data.value = dom.append(data.output, $('span.value'));
data.annotation = dom.append(data.output, $('span'));
return data;
}
if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
let data: IValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
let expression = dom.append(container, $('.output.expression'));
data.container = container;
data.counter = dom.append(expression, $('div.counter'));
data.value = dom.append(expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
let data: IKeyValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
data.container = container;
data.expression = dom.append(container, $('.output.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
data.annotation = dom.append(data.expression, $('span'));
return data;
}
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
renderVariable(tree, element, templateData, false);
} else if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
this.renderExpression(tree, element, templateData);
} else if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputValue(element, templateData);
} else if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputNameValue(tree, element, templateData);
}
}
private renderExpression(tree: ITree, expression: IExpression, templateData: IExpressionTemplateData): void {
templateData.input.textContent = expression.name;
renderExpressionValue(expression, templateData.value, {
preserveWhitespace: !expression.hasChildren,
showHover: false
});
if (expression.hasChildren) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = nls.localize('stateCapture', "Object state is captured from first evaluation");
}
}
private renderOutputValue(output: OutputElement, templateData: IValueOutputTemplateData): void {
// counter
if (output.counter > 1) {
templateData.counter.textContent = String(output.counter);
templateData.counter.className = (output.severity === severity.Warning) ? 'counter warn' : (output.severity === severity.Error) ? 'counter error' : 'counter info';
} else {
templateData.counter.textContent = '';
templateData.counter.className = 'counter';
}
// value
dom.clearNode(templateData.value);
templateData.value.className = '';
let result = this.handleANSIOutput(output.value);
if (typeof result === 'string') {
renderExpressionValue(result, templateData.value, {
preserveWhitespace: true,
showHover: false
});
} else {
templateData.value.appendChild(result);
}
dom.addClass(templateData.value, (output.severity === severity.Warning) ? 'warn' : (output.severity === severity.Error) ? 'error' : 'info');
}
private renderOutputNameValue(tree: ITree, output: OutputNameValueElement, templateData: IKeyValueOutputTemplateData): void {
// key
if (output.name) {
templateData.name.textContent = `${output.name}:`;
} else {
templateData.name.textContent = '';
}
// value
renderExpressionValue(output.value, templateData.value, {
preserveWhitespace: true,
showHover: false
});
// annotation if any
if (output.annotation) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = output.annotation;
} else {
templateData.annotation.className = '';
templateData.annotation.title = '';
}
}
private handleANSIOutput(text: string): HTMLElement | string {
let tokensContainer: HTMLSpanElement;
let currentToken: HTMLSpanElement;
let buffer: string = '';
for (let i = 0, len = text.length; i < len; i++) {
// start of ANSI escape sequence (see http://ascii-table.com/ansi-escape-sequences.php)
if (text.charCodeAt(i) === 27) {
let index = i;
let chr = (++index < len ? text.charAt(index) : null);
if (chr && chr === '[') {
let code: string = null;
chr = (++index < len ? text.charAt(index) : null);
if (chr && chr >= '0' && chr <= '9') {
code = chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (chr && chr >= '0' && chr <= '9') {
code += chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (code === null) {
code = '0';
}
if (chr === 'm') { // set text color/mode.
// only respect text-foreground ranges and ignore the values for "black" & "white" because those
// only make sense in combination with text-background ranges which we currently not support
let parsedMode = parseInt(code, 10);
let token = document.createElement('span');
if ((parsedMode >= 30 && parsedMode <= 37) || (parsedMode >= 90 && parsedMode <= 97)) {
token.className = 'code' + parsedMode;
} else if (parsedMode === 1) {
token.className = 'code-bold';
}
// we need a tokens container now
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
// flush text buffer if we have any
if (buffer) {
this.insert(this.handleLinks(buffer), currentToken || tokensContainer);
buffer = '';
}
currentToken = token;
tokensContainer.appendChild(token);
i = index;
}
}
}
// normal text
else {
buffer += text[i];
}
}
// flush remaining text buffer if we have any
if (buffer) {
let res = this.handleLinks(buffer);
if (typeof res !== 'string' || currentToken) {
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
this.insert(res, currentToken || tokensContainer);
}
}
return tokensContainer || buffer;
}
private insert(arg: HTMLElement | string, target: HTMLElement): void {
if (typeof arg === 'string') {
target.textContent = arg;
} else {
target.appendChild(arg);
}
}
private handleLinks(text: string): HTMLElement | string {
let linkContainer: HTMLElement;
for (let pattern of ReplExpressionsRenderer.FILE_LOCATION_PATTERNS) {
pattern.lastIndex = 0; // the holy grail of software development
const match = pattern.exec(text);
let resource: uri = null;
try {
resource = match && uri.file(match[1]);
} catch (e) { }
if (resource) {
linkContainer = document.createElement('span');
let textBeforeLink = text.substr(0, match.index);
if (textBeforeLink) {
let span = document.createElement('span');
span.textContent = textBeforeLink;
linkContainer.appendChild(span);
}
const link = document.createElement('a');
link.textContent = text.substr(match.index, match[0].length);
link.title = isMacintosh ? nls.localize('fileLinkMac', "Click to follow (Cmd + click opens to the side)") : nls.localize('fileLink', "Click to follow (Ctrl + click opens to the side)");
linkContainer.appendChild(link);
link.onclick = (e) => this.onLinkClick(new StandardMouseEvent(e), resource, Number(match[3]), Number(match[4]));
let textAfterLink = text.substr(match.index + match[0].length);
if (textAfterLink) {
let span = document.createElement('span');
span.textContent = textAfterLink;
linkContainer.appendChild(span);
}
break; // support one link per line for now
}
}
return linkContainer || text;
}
private onLinkClick(event: IMouseEvent, resource: uri, line: number, column: number): void {
const selection = window.getSelection();
if (selection.type === 'Range') {
return; // do not navigate when user is selecting
}
event.preventDefault();
this.editorService.openEditor({
resource,
options: {
selection: {
startLineNumber: line,
startColumn: column
}
}
}, event.ctrlKey || event.metaKey).done(null, errors.onUnexpectedError);
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
export class ReplExpressionsAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Variable) {
return nls.localize('replVariableAriaLabel', "Variable {0} has value {1}, read eval print loop, debug", (<Variable>element).name, (<Variable>element).value);
}
if (element instanceof Expression) {
return nls.localize('replExpressionAriaLabel', "Expression {0} has value {1}, read eval print loop, debug", (<Expression>element).name, (<Expression>element).value);
}
if (element instanceof OutputElement) {
return nls.localize('replValueOutputAriaLabel', "{0}, read eval print loop, debug", (<OutputElement>element).value);
}
if (element instanceof OutputNameValueElement) { | }
}
export class ReplExpressionsActionProvider implements IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
return true;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
actions.push(new CopyAction(CopyAction.ID, CopyAction.LABEL));
actions.push(this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class ReplExpressionsController extends BaseDebugController {
private lastSelectedString: string = null;
public toFocusOnClick: { focus(): void };
protected onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean {
const mouseEvent = <IMouseEvent>eventish;
// input and output are one element in the tree => we only expand if the user clicked on the output.
if ((element.reference > 0 || (element instanceof OutputNameValueElement && element.hasChildren)) && mouseEvent.target.className.indexOf('input expression') === -1) {
super.onLeftClick(tree, element, eventish, origin);
tree.clearFocus();
tree.deselect(element);
}
const selection = window.getSelection();
if (selection.type !== 'Range' || this.lastSelectedString === selection.toString()) {
// only focus the input if the user is not currently selecting.
this.toFocusOnClick.focus();
}
this.lastSelectedString = selection.toString();
return true;
}
protected onDown(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getFocus()) {
return super.onDown(tree, event);
}
const payload = { origin: 'keyboard', originalEvent: event };
tree.focusLast(payload);
tree.reveal(tree.getFocus()).done(null, errors.onUnexpectedError);
return true;
}
} | return nls.localize('replKeyValueOutputAriaLabel', "Output variable {0} has value {1}, read eval print loop, debug", (<OutputNameValueElement>element).name, (<OutputNameValueElement>element).value);
}
return null; | random_line_split |
replViewer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction } from 'vs/base/common/actions';
import { isFullWidthCharacter, removeAnsiEscapeCodes, endsWith } from 'vs/base/common/strings';
import uri from 'vs/base/common/uri';
import { isMacintosh } from 'vs/base/common/platform';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { ITree, IAccessibilityProvider, IDataSource, IRenderer } from 'vs/base/parts/tree/browser/tree';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { ICancelableEvent } from 'vs/base/parts/tree/browser/treeDefaults';
import { IExpressionContainer, IExpression } from 'vs/workbench/parts/debug/common/debug';
import { Model, OutputNameValueElement, Expression, OutputElement, Variable } from 'vs/workbench/parts/debug/common/debugModel';
import { renderVariable, renderExpressionValue, IVariableTemplateData, BaseDebugController } from 'vs/workbench/parts/debug/electron-browser/debugViewer';
import { ClearReplAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { CopyAction } from 'vs/workbench/parts/debug/electron-browser/electronDebugActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
const $ = dom.$;
export class ReplExpressionsDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
return element.getId();
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof Model || (<IExpressionContainer>element).hasChildren;
}
public getChildren(tree: ITree, element: any): TPromise<any> {
if (element instanceof Model) {
return TPromise.as(element.getReplElements());
}
if (element instanceof OutputNameValueElement) {
return TPromise.as(element.getChildren());
}
if (element instanceof OutputElement) {
return TPromise.as(null);
}
return (<IExpression>element).getChildren();
}
public getParent(tree: ITree, element: any): TPromise<any> |
}
interface IExpressionTemplateData {
input: HTMLElement;
output: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
interface IValueOutputTemplateData {
container: HTMLElement;
counter: HTMLElement;
value: HTMLElement;
}
interface IKeyValueOutputTemplateData {
container: HTMLElement;
expression: HTMLElement;
name: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
export class ReplExpressionsRenderer implements IRenderer {
private static VARIABLE_TEMPLATE_ID = 'variable';
private static EXPRESSION_TEMPLATE_ID = 'inputOutputPair';
private static VALUE_OUTPUT_TEMPLATE_ID = 'outputValue';
private static NAME_VALUE_OUTPUT_TEMPLATE_ID = 'outputNameValue';
private static FILE_LOCATION_PATTERNS: RegExp[] = [
// group 0: the full thing :)
// group 1: absolute path
// group 2: drive letter on windows with trailing backslash or leading slash on mac/linux
// group 3: line number
// group 4: column number
// eg: at Context.<anonymous> (c:\Users\someone\Desktop\mocha-runner\test\test.js:26:11)
/((\/|[a-zA-Z]:\\)[^\(\)<>\'\"\[\]]+):(\d+):(\d+)/
];
private static LINE_HEIGHT_PX = 18;
private width: number;
private characterWidth: number;
constructor(
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
// noop
}
public getHeight(tree: ITree, element: any): number {
if (element instanceof Variable && (element.hasChildren || (element.name !== null))) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
if (element instanceof Expression && element.hasChildren) {
return 2 * ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
return this.getHeightForString(element.value) + (element instanceof Expression ? this.getHeightForString(element.name) : 0);
}
private getHeightForString(s: string): number {
if (!s || !s.length || !this.width || this.width <= 0 || !this.characterWidth || this.characterWidth <= 0) {
return ReplExpressionsRenderer.LINE_HEIGHT_PX;
}
// Last new line should be ignored since the repl elements are by design split by rows
if (endsWith(s, '\n')) {
s = s.substr(0, s.length - 1);
}
const lines = removeAnsiEscapeCodes(s).split('\n');
const numLines = lines.reduce((lineCount: number, line: string) => {
let lineLength = 0;
for (let i = 0; i < line.length; i++) {
lineLength += isFullWidthCharacter(line.charCodeAt(i)) ? 2 : 1;
}
return lineCount + Math.floor(lineLength * this.characterWidth / this.width);
}, lines.length);
return ReplExpressionsRenderer.LINE_HEIGHT_PX * numLines;
}
public setWidth(fullWidth: number, characterWidth: number): void {
this.width = fullWidth;
this.characterWidth = characterWidth;
}
public getTemplateId(tree: ITree, element: any): string {
if (element instanceof Variable && element.name) {
return ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID;
}
if (element instanceof Expression) {
return ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID;
}
if (element instanceof OutputElement || (element instanceof Variable && !element.name)) {
// Variable with no name is a top level variable which should be rendered like an output element #17404
return ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID;
}
if (element instanceof OutputNameValueElement) {
return ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID;
}
return null;
}
public renderTemplate(tree: ITree, templateId: string, container: HTMLElement): any {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
let data: IVariableTemplateData = Object.create(null);
data.expression = dom.append(container, $('.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
let data: IExpressionTemplateData = Object.create(null);
dom.addClass(container, 'input-output-pair');
data.input = dom.append(container, $('.input.expression'));
data.output = dom.append(container, $('.output.expression'));
data.value = dom.append(data.output, $('span.value'));
data.annotation = dom.append(data.output, $('span'));
return data;
}
if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
let data: IValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
let expression = dom.append(container, $('.output.expression'));
data.container = container;
data.counter = dom.append(expression, $('div.counter'));
data.value = dom.append(expression, $('span.value'));
return data;
}
if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
let data: IKeyValueOutputTemplateData = Object.create(null);
dom.addClass(container, 'output');
data.container = container;
data.expression = dom.append(container, $('.output.expression'));
data.name = dom.append(data.expression, $('span.name'));
data.value = dom.append(data.expression, $('span.value'));
data.annotation = dom.append(data.expression, $('span'));
return data;
}
}
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
renderVariable(tree, element, templateData, false);
} else if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
this.renderExpression(tree, element, templateData);
} else if (templateId === ReplExpressionsRenderer.VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputValue(element, templateData);
} else if (templateId === ReplExpressionsRenderer.NAME_VALUE_OUTPUT_TEMPLATE_ID) {
this.renderOutputNameValue(tree, element, templateData);
}
}
private renderExpression(tree: ITree, expression: IExpression, templateData: IExpressionTemplateData): void {
templateData.input.textContent = expression.name;
renderExpressionValue(expression, templateData.value, {
preserveWhitespace: !expression.hasChildren,
showHover: false
});
if (expression.hasChildren) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = nls.localize('stateCapture', "Object state is captured from first evaluation");
}
}
private renderOutputValue(output: OutputElement, templateData: IValueOutputTemplateData): void {
// counter
if (output.counter > 1) {
templateData.counter.textContent = String(output.counter);
templateData.counter.className = (output.severity === severity.Warning) ? 'counter warn' : (output.severity === severity.Error) ? 'counter error' : 'counter info';
} else {
templateData.counter.textContent = '';
templateData.counter.className = 'counter';
}
// value
dom.clearNode(templateData.value);
templateData.value.className = '';
let result = this.handleANSIOutput(output.value);
if (typeof result === 'string') {
renderExpressionValue(result, templateData.value, {
preserveWhitespace: true,
showHover: false
});
} else {
templateData.value.appendChild(result);
}
dom.addClass(templateData.value, (output.severity === severity.Warning) ? 'warn' : (output.severity === severity.Error) ? 'error' : 'info');
}
private renderOutputNameValue(tree: ITree, output: OutputNameValueElement, templateData: IKeyValueOutputTemplateData): void {
// key
if (output.name) {
templateData.name.textContent = `${output.name}:`;
} else {
templateData.name.textContent = '';
}
// value
renderExpressionValue(output.value, templateData.value, {
preserveWhitespace: true,
showHover: false
});
// annotation if any
if (output.annotation) {
templateData.annotation.className = 'annotation octicon octicon-info';
templateData.annotation.title = output.annotation;
} else {
templateData.annotation.className = '';
templateData.annotation.title = '';
}
}
private handleANSIOutput(text: string): HTMLElement | string {
let tokensContainer: HTMLSpanElement;
let currentToken: HTMLSpanElement;
let buffer: string = '';
for (let i = 0, len = text.length; i < len; i++) {
// start of ANSI escape sequence (see http://ascii-table.com/ansi-escape-sequences.php)
if (text.charCodeAt(i) === 27) {
let index = i;
let chr = (++index < len ? text.charAt(index) : null);
if (chr && chr === '[') {
let code: string = null;
chr = (++index < len ? text.charAt(index) : null);
if (chr && chr >= '0' && chr <= '9') {
code = chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (chr && chr >= '0' && chr <= '9') {
code += chr;
chr = (++index < len ? text.charAt(index) : null);
}
if (code === null) {
code = '0';
}
if (chr === 'm') { // set text color/mode.
// only respect text-foreground ranges and ignore the values for "black" & "white" because those
// only make sense in combination with text-background ranges which we currently not support
let parsedMode = parseInt(code, 10);
let token = document.createElement('span');
if ((parsedMode >= 30 && parsedMode <= 37) || (parsedMode >= 90 && parsedMode <= 97)) {
token.className = 'code' + parsedMode;
} else if (parsedMode === 1) {
token.className = 'code-bold';
}
// we need a tokens container now
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
// flush text buffer if we have any
if (buffer) {
this.insert(this.handleLinks(buffer), currentToken || tokensContainer);
buffer = '';
}
currentToken = token;
tokensContainer.appendChild(token);
i = index;
}
}
}
// normal text
else {
buffer += text[i];
}
}
// flush remaining text buffer if we have any
if (buffer) {
let res = this.handleLinks(buffer);
if (typeof res !== 'string' || currentToken) {
if (!tokensContainer) {
tokensContainer = document.createElement('span');
}
this.insert(res, currentToken || tokensContainer);
}
}
return tokensContainer || buffer;
}
private insert(arg: HTMLElement | string, target: HTMLElement): void {
if (typeof arg === 'string') {
target.textContent = arg;
} else {
target.appendChild(arg);
}
}
private handleLinks(text: string): HTMLElement | string {
let linkContainer: HTMLElement;
for (let pattern of ReplExpressionsRenderer.FILE_LOCATION_PATTERNS) {
pattern.lastIndex = 0; // the holy grail of software development
const match = pattern.exec(text);
let resource: uri = null;
try {
resource = match && uri.file(match[1]);
} catch (e) { }
if (resource) {
linkContainer = document.createElement('span');
let textBeforeLink = text.substr(0, match.index);
if (textBeforeLink) {
let span = document.createElement('span');
span.textContent = textBeforeLink;
linkContainer.appendChild(span);
}
const link = document.createElement('a');
link.textContent = text.substr(match.index, match[0].length);
link.title = isMacintosh ? nls.localize('fileLinkMac', "Click to follow (Cmd + click opens to the side)") : nls.localize('fileLink', "Click to follow (Ctrl + click opens to the side)");
linkContainer.appendChild(link);
link.onclick = (e) => this.onLinkClick(new StandardMouseEvent(e), resource, Number(match[3]), Number(match[4]));
let textAfterLink = text.substr(match.index + match[0].length);
if (textAfterLink) {
let span = document.createElement('span');
span.textContent = textAfterLink;
linkContainer.appendChild(span);
}
break; // support one link per line for now
}
}
return linkContainer || text;
}
private onLinkClick(event: IMouseEvent, resource: uri, line: number, column: number): void {
const selection = window.getSelection();
if (selection.type === 'Range') {
return; // do not navigate when user is selecting
}
event.preventDefault();
this.editorService.openEditor({
resource,
options: {
selection: {
startLineNumber: line,
startColumn: column
}
}
}, event.ctrlKey || event.metaKey).done(null, errors.onUnexpectedError);
}
public disposeTemplate(tree: ITree, templateId: string, templateData: any): void {
// noop
}
}
export class ReplExpressionsAccessibilityProvider implements IAccessibilityProvider {
public getAriaLabel(tree: ITree, element: any): string {
if (element instanceof Variable) {
return nls.localize('replVariableAriaLabel', "Variable {0} has value {1}, read eval print loop, debug", (<Variable>element).name, (<Variable>element).value);
}
if (element instanceof Expression) {
return nls.localize('replExpressionAriaLabel', "Expression {0} has value {1}, read eval print loop, debug", (<Expression>element).name, (<Expression>element).value);
}
if (element instanceof OutputElement) {
return nls.localize('replValueOutputAriaLabel', "{0}, read eval print loop, debug", (<OutputElement>element).value);
}
if (element instanceof OutputNameValueElement) {
return nls.localize('replKeyValueOutputAriaLabel', "Output variable {0} has value {1}, read eval print loop, debug", (<OutputNameValueElement>element).name, (<OutputNameValueElement>element).value);
}
return null;
}
}
export class ReplExpressionsActionProvider implements IActionProvider {
constructor(private instantiationService: IInstantiationService) {
// noop
}
public hasActions(tree: ITree, element: any): boolean {
return false;
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return TPromise.as([]);
}
public hasSecondaryActions(tree: ITree, element: any): boolean {
return true;
}
public getSecondaryActions(tree: ITree, element: any): TPromise<IAction[]> {
const actions: IAction[] = [];
actions.push(new CopyAction(CopyAction.ID, CopyAction.LABEL));
actions.push(this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL));
return TPromise.as(actions);
}
public getActionItem(tree: ITree, element: any, action: IAction): IActionItem {
return null;
}
}
export class ReplExpressionsController extends BaseDebugController {
private lastSelectedString: string = null;
public toFocusOnClick: { focus(): void };
protected onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean {
const mouseEvent = <IMouseEvent>eventish;
// input and output are one element in the tree => we only expand if the user clicked on the output.
if ((element.reference > 0 || (element instanceof OutputNameValueElement && element.hasChildren)) && mouseEvent.target.className.indexOf('input expression') === -1) {
super.onLeftClick(tree, element, eventish, origin);
tree.clearFocus();
tree.deselect(element);
}
const selection = window.getSelection();
if (selection.type !== 'Range' || this.lastSelectedString === selection.toString()) {
// only focus the input if the user is not currently selecting.
this.toFocusOnClick.focus();
}
this.lastSelectedString = selection.toString();
return true;
}
protected onDown(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getFocus()) {
return super.onDown(tree, event);
}
const payload = { origin: 'keyboard', originalEvent: event };
tree.focusLast(payload);
tree.reveal(tree.getFocus()).done(null, errors.onUnexpectedError);
return true;
}
}
| {
return TPromise.as(null);
} | identifier_body |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import MODULE_IDENTITY, OBJECT_TYPE, snmpModules
from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from SNMPv2_TC import RowStatus, StorageType
from SNMP_TARGET_MIB import SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup
from SNMP_FRAMEWORK_MIB import SnmpEngineID, SnmpAdminString
class SNMP_PROXY_MIB(ModuleObject):
path = '/usr/share/mibs/ietf/SNMP-PROXY-MIB'
name = 'SNMP-PROXY-MIB'
language = 2
description = 'This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.'
# nodes
class | (NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14])
name = 'snmpProxyMIB'
class snmpProxyObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1])
name = 'snmpProxyObjects'
class snmpProxyConformance(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3])
name = 'snmpProxyConformance'
class snmpProxyCompliances(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 1])
name = 'snmpProxyCompliances'
class snmpProxyGroups(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2])
name = 'snmpProxyGroups'
# macros
# types
# scalars
# columns
class snmpProxyName(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1])
syntaxobject = SnmpAdminString
class snmpProxyType(ColumnObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'read'), Enum(2, 'write'), Enum(3, 'trap'), Enum(4, 'inform')]
class snmpProxyContextEngineID(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 3])
syntaxobject = SnmpEngineID
class snmpProxyContextName(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4])
syntaxobject = SnmpAdminString
class snmpProxyTargetParamsIn(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 5])
syntaxobject = SnmpAdminString
class snmpProxySingleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 6])
syntaxobject = SnmpAdminString
class snmpProxyMultipleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7])
syntaxobject = SnmpTagValue
class snmpProxyStorageType(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.StorageType
class snmpProxyRowStatus(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9])
syntaxobject = pycopia.SMI.Basetypes.RowStatus
# rows
class snmpProxyEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([snmpProxyName], True)
create = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1])
access = 2
rowstatus = snmpProxyRowStatus
columns = {'snmpProxyName': snmpProxyName, 'snmpProxyType': snmpProxyType, 'snmpProxyContextEngineID': snmpProxyContextEngineID, 'snmpProxyContextName': snmpProxyContextName, 'snmpProxyTargetParamsIn': snmpProxyTargetParamsIn, 'snmpProxySingleTargetOut': snmpProxySingleTargetOut, 'snmpProxyMultipleTargetOut': snmpProxyMultipleTargetOut, 'snmpProxyStorageType': snmpProxyStorageType, 'snmpProxyRowStatus': snmpProxyRowStatus}
# notifications (traps)
# groups
class snmpProxyGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2, 3])
group = [snmpProxyType, snmpProxyContextEngineID, snmpProxyContextName, snmpProxyTargetParamsIn, snmpProxySingleTargetOut, snmpProxyMultipleTargetOut, snmpProxyStorageType, snmpProxyRowStatus]
# capabilities
# special additions
# Add to master OIDMAP.
from pycopia import SMI
SMI.update_oidmap(__name__)
| snmpProxyMIB | identifier_name |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
| from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from SNMPv2_TC import RowStatus, StorageType
from SNMP_TARGET_MIB import SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup
from SNMP_FRAMEWORK_MIB import SnmpEngineID, SnmpAdminString
class SNMP_PROXY_MIB(ModuleObject):
path = '/usr/share/mibs/ietf/SNMP-PROXY-MIB'
name = 'SNMP-PROXY-MIB'
language = 2
description = 'This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.'
# nodes
class snmpProxyMIB(NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14])
name = 'snmpProxyMIB'
class snmpProxyObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1])
name = 'snmpProxyObjects'
class snmpProxyConformance(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3])
name = 'snmpProxyConformance'
class snmpProxyCompliances(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 1])
name = 'snmpProxyCompliances'
class snmpProxyGroups(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2])
name = 'snmpProxyGroups'
# macros
# types
# scalars
# columns
class snmpProxyName(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1])
syntaxobject = SnmpAdminString
class snmpProxyType(ColumnObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'read'), Enum(2, 'write'), Enum(3, 'trap'), Enum(4, 'inform')]
class snmpProxyContextEngineID(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 3])
syntaxobject = SnmpEngineID
class snmpProxyContextName(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4])
syntaxobject = SnmpAdminString
class snmpProxyTargetParamsIn(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 5])
syntaxobject = SnmpAdminString
class snmpProxySingleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 6])
syntaxobject = SnmpAdminString
class snmpProxyMultipleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7])
syntaxobject = SnmpTagValue
class snmpProxyStorageType(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.StorageType
class snmpProxyRowStatus(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9])
syntaxobject = pycopia.SMI.Basetypes.RowStatus
# rows
class snmpProxyEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([snmpProxyName], True)
create = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1])
access = 2
rowstatus = snmpProxyRowStatus
columns = {'snmpProxyName': snmpProxyName, 'snmpProxyType': snmpProxyType, 'snmpProxyContextEngineID': snmpProxyContextEngineID, 'snmpProxyContextName': snmpProxyContextName, 'snmpProxyTargetParamsIn': snmpProxyTargetParamsIn, 'snmpProxySingleTargetOut': snmpProxySingleTargetOut, 'snmpProxyMultipleTargetOut': snmpProxyMultipleTargetOut, 'snmpProxyStorageType': snmpProxyStorageType, 'snmpProxyRowStatus': snmpProxyRowStatus}
# notifications (traps)
# groups
class snmpProxyGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2, 3])
group = [snmpProxyType, snmpProxyContextEngineID, snmpProxyContextName, snmpProxyTargetParamsIn, snmpProxySingleTargetOut, snmpProxyMultipleTargetOut, snmpProxyStorageType, snmpProxyRowStatus]
# capabilities
# special additions
# Add to master OIDMAP.
from pycopia import SMI
SMI.update_oidmap(__name__) | from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import MODULE_IDENTITY, OBJECT_TYPE, snmpModules | random_line_split |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import MODULE_IDENTITY, OBJECT_TYPE, snmpModules
from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from SNMPv2_TC import RowStatus, StorageType
from SNMP_TARGET_MIB import SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup
from SNMP_FRAMEWORK_MIB import SnmpEngineID, SnmpAdminString
class SNMP_PROXY_MIB(ModuleObject):
|
# nodes
class snmpProxyMIB(NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14])
name = 'snmpProxyMIB'
class snmpProxyObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1])
name = 'snmpProxyObjects'
class snmpProxyConformance(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3])
name = 'snmpProxyConformance'
class snmpProxyCompliances(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 1])
name = 'snmpProxyCompliances'
class snmpProxyGroups(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2])
name = 'snmpProxyGroups'
# macros
# types
# scalars
# columns
class snmpProxyName(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1])
syntaxobject = SnmpAdminString
class snmpProxyType(ColumnObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'read'), Enum(2, 'write'), Enum(3, 'trap'), Enum(4, 'inform')]
class snmpProxyContextEngineID(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 3])
syntaxobject = SnmpEngineID
class snmpProxyContextName(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4])
syntaxobject = SnmpAdminString
class snmpProxyTargetParamsIn(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 5])
syntaxobject = SnmpAdminString
class snmpProxySingleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 6])
syntaxobject = SnmpAdminString
class snmpProxyMultipleTargetOut(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7])
syntaxobject = SnmpTagValue
class snmpProxyStorageType(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.StorageType
class snmpProxyRowStatus(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9])
syntaxobject = pycopia.SMI.Basetypes.RowStatus
# rows
class snmpProxyEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([snmpProxyName], True)
create = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1])
access = 2
rowstatus = snmpProxyRowStatus
columns = {'snmpProxyName': snmpProxyName, 'snmpProxyType': snmpProxyType, 'snmpProxyContextEngineID': snmpProxyContextEngineID, 'snmpProxyContextName': snmpProxyContextName, 'snmpProxyTargetParamsIn': snmpProxyTargetParamsIn, 'snmpProxySingleTargetOut': snmpProxySingleTargetOut, 'snmpProxyMultipleTargetOut': snmpProxyMultipleTargetOut, 'snmpProxyStorageType': snmpProxyStorageType, 'snmpProxyRowStatus': snmpProxyRowStatus}
# notifications (traps)
# groups
class snmpProxyGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 3, 2, 3])
group = [snmpProxyType, snmpProxyContextEngineID, snmpProxyContextName, snmpProxyTargetParamsIn, snmpProxySingleTargetOut, snmpProxyMultipleTargetOut, snmpProxyStorageType, snmpProxyRowStatus]
# capabilities
# special additions
# Add to master OIDMAP.
from pycopia import SMI
SMI.update_oidmap(__name__)
| path = '/usr/share/mibs/ietf/SNMP-PROXY-MIB'
name = 'SNMP-PROXY-MIB'
language = 2
description = 'This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.' | identifier_body |
matrix_inverse_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matrix_inverse."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import benchmark
from tensorflow.python.platform import test
class InverseOpTest(test.TestCase):
def _verifyInverse(self, x, np_type):
for adjoint in False, True:
y = x.astype(np_type)
with self.cached_session(use_gpu=True):
# Verify that x^{-1} * x == Identity matrix.
inv = linalg_ops.matrix_inverse(y, adjoint=adjoint)
tf_ans = test_util.matmul_without_tf32(inv, y, adjoint_b=adjoint)
np_ans = np.identity(y.shape[-1])
if x.ndim > 2:
tiling = list(y.shape)
tiling[-2:] = [1, 1]
np_ans = np.tile(np_ans, tiling)
out = self.evaluate(tf_ans)
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-3)
self.assertShapeEqual(y, tf_ans)
def _verifyInverseReal(self, x):
for np_type in [np.float32, np.float64]:
self._verifyInverse(x, np_type)
def _verifyInverseComplex(self, x):
for np_type in [np.complex64, np.complex128]:
self._verifyInverse(x, np_type)
def _makeBatch(self, matrix1, matrix2):
matrix_batch = np.concatenate(
[np.expand_dims(matrix1, 0),
np.expand_dims(matrix2, 0)])
matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1])
return matrix_batch
def testNonsymmetric(self):
# 2x2 matrices
matrix1 = np.array([[1., 2.], [3., 4.]])
matrix2 = np.array([[1., 3.], [3., 5.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
def testSymmetricPositiveDefinite(self):
# 2x2 matrices
matrix1 = np.array([[2., 1.], [1., 2.]])
matrix2 = np.array([[3., -1.], [-1., 3.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
@test_util.deprecated_graph_mode_only
def testNonSquareMatrix(self):
# When the inverse of a non-square matrix is attempted we should return
# an error
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(np.array([[1., 2., 3.], [3., 4., 5.]]))
@test_util.deprecated_graph_mode_only
def testWrongDimensions(self):
# The input to the inverse should be at least a 2-dimensional tensor.
tensor3 = constant_op.constant([1., 2.])
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(tensor3)
def testNotInvertible(self):
# The input should be invertible.
with self.cached_session():
with self.assertRaisesOpError("Input is not invertible."):
# All rows of the matrix below add to zero.
tensor3 = constant_op.constant([[1., 0., -1.], [-1., 1., 0.],
[0., -1., 1.]])
linalg_ops.matrix_inverse(tensor3).eval()
def testEmpty(self):
self._verifyInverseReal(np.empty([0, 2, 2]))
self._verifyInverseReal(np.empty([2, 0, 0]))
def testRandomSmallAndLarge(self):
np.random.seed(42)
for dtype in np.float32, np.float64, np.complex64, np.complex128:
for batch_dims in [(), (1,), (3,), (2, 2)]:
for size in 8, 31, 32:
shape = batch_dims + (size, size)
matrix = np.random.uniform(
low=-1.0, high=1.0,
size=np.prod(shape)).reshape(shape).astype(dtype)
self._verifyInverseReal(matrix)
@test_util.deprecated_graph_mode_only
def | (self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_)
inv2 = linalg_ops.matrix_inverse(matrix2, adjoint=adjoint_)
all_ops += [inv1, inv2]
inv = self.evaluate(all_ops)
self.assertAllEqual(inv[0], inv[1])
self.assertAllEqual(inv[2], inv[3])
class MatrixInverseBenchmark(test.Benchmark):
shapes = [
(4, 4),
(10, 10),
(16, 16),
(101, 101),
(256, 256),
(1000, 1000),
(1024, 1024),
(2048, 2048),
(513, 4, 4),
(513, 16, 16),
(513, 256, 256),
]
def _GenerateMatrix(self, shape):
batch_shape = shape[:-2]
shape = shape[-2:]
assert shape[0] == shape[1]
n = shape[0]
matrix = np.ones(shape).astype(np.float32) / (
2.0 * n) + np.diag(np.ones(n).astype(np.float32))
return variables.Variable(np.tile(matrix, batch_shape + (1, 1)))
def benchmarkMatrixInverseOp(self):
for adjoint in False, True:
for shape in self.shapes:
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/cpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_cpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if test.is_gpu_available(True):
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/gpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_gpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if __name__ == "__main__":
test.main()
| testConcurrentExecutesWithoutError | identifier_name |
matrix_inverse_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matrix_inverse."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import benchmark
from tensorflow.python.platform import test
class InverseOpTest(test.TestCase):
def _verifyInverse(self, x, np_type):
for adjoint in False, True:
y = x.astype(np_type)
with self.cached_session(use_gpu=True):
# Verify that x^{-1} * x == Identity matrix.
inv = linalg_ops.matrix_inverse(y, adjoint=adjoint)
tf_ans = test_util.matmul_without_tf32(inv, y, adjoint_b=adjoint)
np_ans = np.identity(y.shape[-1])
if x.ndim > 2:
tiling = list(y.shape)
tiling[-2:] = [1, 1]
np_ans = np.tile(np_ans, tiling)
out = self.evaluate(tf_ans)
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-3)
self.assertShapeEqual(y, tf_ans)
def _verifyInverseReal(self, x):
|
def _verifyInverseComplex(self, x):
for np_type in [np.complex64, np.complex128]:
self._verifyInverse(x, np_type)
def _makeBatch(self, matrix1, matrix2):
matrix_batch = np.concatenate(
[np.expand_dims(matrix1, 0),
np.expand_dims(matrix2, 0)])
matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1])
return matrix_batch
def testNonsymmetric(self):
# 2x2 matrices
matrix1 = np.array([[1., 2.], [3., 4.]])
matrix2 = np.array([[1., 3.], [3., 5.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
def testSymmetricPositiveDefinite(self):
# 2x2 matrices
matrix1 = np.array([[2., 1.], [1., 2.]])
matrix2 = np.array([[3., -1.], [-1., 3.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
@test_util.deprecated_graph_mode_only
def testNonSquareMatrix(self):
# When the inverse of a non-square matrix is attempted we should return
# an error
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(np.array([[1., 2., 3.], [3., 4., 5.]]))
@test_util.deprecated_graph_mode_only
def testWrongDimensions(self):
# The input to the inverse should be at least a 2-dimensional tensor.
tensor3 = constant_op.constant([1., 2.])
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(tensor3)
def testNotInvertible(self):
# The input should be invertible.
with self.cached_session():
with self.assertRaisesOpError("Input is not invertible."):
# All rows of the matrix below add to zero.
tensor3 = constant_op.constant([[1., 0., -1.], [-1., 1., 0.],
[0., -1., 1.]])
linalg_ops.matrix_inverse(tensor3).eval()
def testEmpty(self):
self._verifyInverseReal(np.empty([0, 2, 2]))
self._verifyInverseReal(np.empty([2, 0, 0]))
def testRandomSmallAndLarge(self):
np.random.seed(42)
for dtype in np.float32, np.float64, np.complex64, np.complex128:
for batch_dims in [(), (1,), (3,), (2, 2)]:
for size in 8, 31, 32:
shape = batch_dims + (size, size)
matrix = np.random.uniform(
low=-1.0, high=1.0,
size=np.prod(shape)).reshape(shape).astype(dtype)
self._verifyInverseReal(matrix)
@test_util.deprecated_graph_mode_only
def testConcurrentExecutesWithoutError(self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_)
inv2 = linalg_ops.matrix_inverse(matrix2, adjoint=adjoint_)
all_ops += [inv1, inv2]
inv = self.evaluate(all_ops)
self.assertAllEqual(inv[0], inv[1])
self.assertAllEqual(inv[2], inv[3])
class MatrixInverseBenchmark(test.Benchmark):
shapes = [
(4, 4),
(10, 10),
(16, 16),
(101, 101),
(256, 256),
(1000, 1000),
(1024, 1024),
(2048, 2048),
(513, 4, 4),
(513, 16, 16),
(513, 256, 256),
]
def _GenerateMatrix(self, shape):
batch_shape = shape[:-2]
shape = shape[-2:]
assert shape[0] == shape[1]
n = shape[0]
matrix = np.ones(shape).astype(np.float32) / (
2.0 * n) + np.diag(np.ones(n).astype(np.float32))
return variables.Variable(np.tile(matrix, batch_shape + (1, 1)))
def benchmarkMatrixInverseOp(self):
for adjoint in False, True:
for shape in self.shapes:
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/cpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_cpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if test.is_gpu_available(True):
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/gpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_gpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if __name__ == "__main__":
test.main()
| for np_type in [np.float32, np.float64]:
self._verifyInverse(x, np_type) | identifier_body |
matrix_inverse_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matrix_inverse."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import benchmark
from tensorflow.python.platform import test
class InverseOpTest(test.TestCase):
def _verifyInverse(self, x, np_type):
for adjoint in False, True:
y = x.astype(np_type)
with self.cached_session(use_gpu=True):
# Verify that x^{-1} * x == Identity matrix.
inv = linalg_ops.matrix_inverse(y, adjoint=adjoint)
tf_ans = test_util.matmul_without_tf32(inv, y, adjoint_b=adjoint)
np_ans = np.identity(y.shape[-1])
if x.ndim > 2:
tiling = list(y.shape)
tiling[-2:] = [1, 1]
np_ans = np.tile(np_ans, tiling)
out = self.evaluate(tf_ans)
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-3)
self.assertShapeEqual(y, tf_ans)
def _verifyInverseReal(self, x):
for np_type in [np.float32, np.float64]:
self._verifyInverse(x, np_type)
def _verifyInverseComplex(self, x):
for np_type in [np.complex64, np.complex128]:
self._verifyInverse(x, np_type)
def _makeBatch(self, matrix1, matrix2):
matrix_batch = np.concatenate(
[np.expand_dims(matrix1, 0),
np.expand_dims(matrix2, 0)])
matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1])
return matrix_batch
def testNonsymmetric(self):
# 2x2 matrices
matrix1 = np.array([[1., 2.], [3., 4.]])
matrix2 = np.array([[1., 3.], [3., 5.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
def testSymmetricPositiveDefinite(self):
# 2x2 matrices
matrix1 = np.array([[2., 1.], [1., 2.]])
matrix2 = np.array([[3., -1.], [-1., 3.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
@test_util.deprecated_graph_mode_only
def testNonSquareMatrix(self):
# When the inverse of a non-square matrix is attempted we should return
# an error
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(np.array([[1., 2., 3.], [3., 4., 5.]]))
@test_util.deprecated_graph_mode_only
def testWrongDimensions(self):
# The input to the inverse should be at least a 2-dimensional tensor.
tensor3 = constant_op.constant([1., 2.])
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(tensor3)
def testNotInvertible(self):
# The input should be invertible.
with self.cached_session():
with self.assertRaisesOpError("Input is not invertible."):
# All rows of the matrix below add to zero.
tensor3 = constant_op.constant([[1., 0., -1.], [-1., 1., 0.],
[0., -1., 1.]])
linalg_ops.matrix_inverse(tensor3).eval()
def testEmpty(self):
self._verifyInverseReal(np.empty([0, 2, 2]))
self._verifyInverseReal(np.empty([2, 0, 0]))
def testRandomSmallAndLarge(self):
np.random.seed(42)
for dtype in np.float32, np.float64, np.complex64, np.complex128:
|
@test_util.deprecated_graph_mode_only
def testConcurrentExecutesWithoutError(self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_)
inv2 = linalg_ops.matrix_inverse(matrix2, adjoint=adjoint_)
all_ops += [inv1, inv2]
inv = self.evaluate(all_ops)
self.assertAllEqual(inv[0], inv[1])
self.assertAllEqual(inv[2], inv[3])
class MatrixInverseBenchmark(test.Benchmark):
shapes = [
(4, 4),
(10, 10),
(16, 16),
(101, 101),
(256, 256),
(1000, 1000),
(1024, 1024),
(2048, 2048),
(513, 4, 4),
(513, 16, 16),
(513, 256, 256),
]
def _GenerateMatrix(self, shape):
batch_shape = shape[:-2]
shape = shape[-2:]
assert shape[0] == shape[1]
n = shape[0]
matrix = np.ones(shape).astype(np.float32) / (
2.0 * n) + np.diag(np.ones(n).astype(np.float32))
return variables.Variable(np.tile(matrix, batch_shape + (1, 1)))
def benchmarkMatrixInverseOp(self):
for adjoint in False, True:
for shape in self.shapes:
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/cpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_cpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if test.is_gpu_available(True):
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/gpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_gpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if __name__ == "__main__":
test.main()
| for batch_dims in [(), (1,), (3,), (2, 2)]:
for size in 8, 31, 32:
shape = batch_dims + (size, size)
matrix = np.random.uniform(
low=-1.0, high=1.0,
size=np.prod(shape)).reshape(shape).astype(dtype)
self._verifyInverseReal(matrix) | conditional_block |
matrix_inverse_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matrix_inverse."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import benchmark
from tensorflow.python.platform import test
class InverseOpTest(test.TestCase):
def _verifyInverse(self, x, np_type):
for adjoint in False, True:
y = x.astype(np_type)
with self.cached_session(use_gpu=True):
# Verify that x^{-1} * x == Identity matrix.
inv = linalg_ops.matrix_inverse(y, adjoint=adjoint)
tf_ans = test_util.matmul_without_tf32(inv, y, adjoint_b=adjoint)
np_ans = np.identity(y.shape[-1])
if x.ndim > 2:
tiling = list(y.shape)
tiling[-2:] = [1, 1]
np_ans = np.tile(np_ans, tiling)
out = self.evaluate(tf_ans)
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-3)
self.assertShapeEqual(y, tf_ans)
def _verifyInverseReal(self, x):
for np_type in [np.float32, np.float64]:
self._verifyInverse(x, np_type)
def _verifyInverseComplex(self, x):
for np_type in [np.complex64, np.complex128]:
self._verifyInverse(x, np_type)
def _makeBatch(self, matrix1, matrix2):
matrix_batch = np.concatenate(
[np.expand_dims(matrix1, 0),
np.expand_dims(matrix2, 0)])
matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1])
return matrix_batch
def testNonsymmetric(self):
# 2x2 matrices
matrix1 = np.array([[1., 2.], [3., 4.]])
matrix2 = np.array([[1., 3.], [3., 5.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1
matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2
self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
def testSymmetricPositiveDefinite(self):
# 2x2 matrices
matrix1 = np.array([[2., 1.], [1., 2.]])
matrix2 = np.array([[3., -1.], [-1., 3.]])
self._verifyInverseReal(matrix1)
self._verifyInverseReal(matrix2)
# A multidimensional batch of 2x2 matrices
self._verifyInverseReal(self._makeBatch(matrix1, matrix2))
matrix1 = matrix1.astype(np.complex64)
matrix1 += 1j * matrix1 | self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
@test_util.deprecated_graph_mode_only
def testNonSquareMatrix(self):
# When the inverse of a non-square matrix is attempted we should return
# an error
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(np.array([[1., 2., 3.], [3., 4., 5.]]))
@test_util.deprecated_graph_mode_only
def testWrongDimensions(self):
# The input to the inverse should be at least a 2-dimensional tensor.
tensor3 = constant_op.constant([1., 2.])
with self.assertRaises(ValueError):
linalg_ops.matrix_inverse(tensor3)
def testNotInvertible(self):
# The input should be invertible.
with self.cached_session():
with self.assertRaisesOpError("Input is not invertible."):
# All rows of the matrix below add to zero.
tensor3 = constant_op.constant([[1., 0., -1.], [-1., 1., 0.],
[0., -1., 1.]])
linalg_ops.matrix_inverse(tensor3).eval()
def testEmpty(self):
self._verifyInverseReal(np.empty([0, 2, 2]))
self._verifyInverseReal(np.empty([2, 0, 0]))
def testRandomSmallAndLarge(self):
np.random.seed(42)
for dtype in np.float32, np.float64, np.complex64, np.complex128:
for batch_dims in [(), (1,), (3,), (2, 2)]:
for size in 8, 31, 32:
shape = batch_dims + (size, size)
matrix = np.random.uniform(
low=-1.0, high=1.0,
size=np.prod(shape)).reshape(shape).astype(dtype)
self._verifyInverseReal(matrix)
@test_util.deprecated_graph_mode_only
def testConcurrentExecutesWithoutError(self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_)
inv2 = linalg_ops.matrix_inverse(matrix2, adjoint=adjoint_)
all_ops += [inv1, inv2]
inv = self.evaluate(all_ops)
self.assertAllEqual(inv[0], inv[1])
self.assertAllEqual(inv[2], inv[3])
class MatrixInverseBenchmark(test.Benchmark):
shapes = [
(4, 4),
(10, 10),
(16, 16),
(101, 101),
(256, 256),
(1000, 1000),
(1024, 1024),
(2048, 2048),
(513, 4, 4),
(513, 16, 16),
(513, 256, 256),
]
def _GenerateMatrix(self, shape):
batch_shape = shape[:-2]
shape = shape[-2:]
assert shape[0] == shape[1]
n = shape[0]
matrix = np.ones(shape).astype(np.float32) / (
2.0 * n) + np.diag(np.ones(n).astype(np.float32))
return variables.Variable(np.tile(matrix, batch_shape + (1, 1)))
def benchmarkMatrixInverseOp(self):
for adjoint in False, True:
for shape in self.shapes:
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/cpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_cpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if test.is_gpu_available(True):
with ops.Graph().as_default(), \
session.Session(config=benchmark.benchmark_config()) as sess, \
ops.device("/gpu:0"):
matrix = self._GenerateMatrix(shape)
inv = linalg_ops.matrix_inverse(matrix, adjoint=adjoint)
self.evaluate(variables.global_variables_initializer())
self.run_op_benchmark(
sess,
control_flow_ops.group(inv),
min_iters=25,
name="matrix_inverse_gpu_{shape}_adjoint_{adjoint}".format(
shape=shape, adjoint=adjoint))
if __name__ == "__main__":
test.main() | matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2 | random_line_split |
app_routing_selectors.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {createFeatureSelector, createSelector} from '@ngrx/store';
import {ExperimentAlias} from '../../experiments/types';
import {getExperimentIdsFromRouteParams} from '../internal_utils';
import {
getCompareExperimentIdAliasSpec,
getCompareExperimentIdAliasWithNumberSpec,
} from '../store_only_utils';
import {
CompareRouteParams,
RehydratedDeepLink,
Route,
RouteKind,
} from '../types';
import {
AppRoutingState,
APP_ROUTING_FEATURE_KEY,
State,
} from './app_routing_types';
const getAppRoutingState = createFeatureSelector<State, AppRoutingState>(
APP_ROUTING_FEATURE_KEY
);
export const getActiveRoute = createSelector(
getAppRoutingState,
(state: AppRoutingState) => {
return state.activeRoute;
}
);
export const getNextRouteForRouterOutletOnly = createSelector(
getAppRoutingState,
(state: AppRoutingState): Route | null => {
return state.nextRoute;
}
);
export const getActiveNamespaceId = createSelector(
getAppRoutingState,
(state): string | null => {
return state.activeNamespaceId;
}
);
export const getRehydratedDeepLinks = createSelector(
getAppRoutingState,
(state): RehydratedDeepLink[] => {
return state.rehydratedDeepLinks;
}
);
export const getRegisteredRouteKinds = createSelector<
State,
AppRoutingState,
Set<RouteKind>
>(getAppRoutingState, (state) => {
return state.registeredRouteKeys;
});
/**
* Returns current RouteKind or returns `null` if route is not set at all
* (e.g., an application does not define any routes).
*/
export const getRouteKind = createSelector(getActiveRoute, (activeRoute) => {
return activeRoute ? activeRoute.routeKind : RouteKind.NOT_SET;
});
export const getRouteParams = createSelector(getActiveRoute, (activeRoute) => {
return activeRoute ? activeRoute.params : {};
});
/**
* Returns experiment ids activated by route. The value can be null if current
* route does not have eids.
*/
export const getExperimentIdsFromRoute = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): string[] | null => {
return getExperimentIdsFromRouteParams(routeKind, routeParams);
}
);
/**
* @deprecated
*/
export const getExperimentIdToAliasMap = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): {[id: string]: string} => {
if (routeKind !== RouteKind.COMPARE_EXPERIMENT) |
const compareParams = routeParams as CompareRouteParams;
const userDefinedAliasMap = getCompareExperimentIdAliasSpec(compareParams);
return Object.fromEntries(userDefinedAliasMap.entries());
}
);
export const getExperimentIdToExperimentAliasMap = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): {[id: string]: ExperimentAlias} => {
if (routeKind !== RouteKind.COMPARE_EXPERIMENT) {
return {};
}
const compareParams = routeParams as CompareRouteParams;
const map = getCompareExperimentIdAliasWithNumberSpec(compareParams);
return Object.fromEntries(map.entries());
}
);
| {
return {};
} | conditional_block |
app_routing_selectors.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {createFeatureSelector, createSelector} from '@ngrx/store';
import {ExperimentAlias} from '../../experiments/types';
import {getExperimentIdsFromRouteParams} from '../internal_utils';
import {
getCompareExperimentIdAliasSpec,
getCompareExperimentIdAliasWithNumberSpec,
} from '../store_only_utils';
import {
CompareRouteParams,
RehydratedDeepLink,
Route,
RouteKind,
} from '../types';
import {
AppRoutingState,
APP_ROUTING_FEATURE_KEY,
State,
} from './app_routing_types';
const getAppRoutingState = createFeatureSelector<State, AppRoutingState>(
APP_ROUTING_FEATURE_KEY
);
export const getActiveRoute = createSelector(
getAppRoutingState,
(state: AppRoutingState) => {
return state.activeRoute;
}
);
export const getNextRouteForRouterOutletOnly = createSelector(
getAppRoutingState,
(state: AppRoutingState): Route | null => {
return state.nextRoute;
}
);
export const getActiveNamespaceId = createSelector(
getAppRoutingState,
(state): string | null => {
return state.activeNamespaceId;
}
);
export const getRehydratedDeepLinks = createSelector(
getAppRoutingState,
(state): RehydratedDeepLink[] => {
return state.rehydratedDeepLinks;
}
);
export const getRegisteredRouteKinds = createSelector<
State,
AppRoutingState,
Set<RouteKind>
>(getAppRoutingState, (state) => {
return state.registeredRouteKeys;
});
/**
* Returns current RouteKind or returns `null` if route is not set at all
* (e.g., an application does not define any routes).
*/
export const getRouteKind = createSelector(getActiveRoute, (activeRoute) => {
return activeRoute ? activeRoute.routeKind : RouteKind.NOT_SET;
});
export const getRouteParams = createSelector(getActiveRoute, (activeRoute) => {
return activeRoute ? activeRoute.params : {};
});
/**
* Returns experiment ids activated by route. The value can be null if current
* route does not have eids.
*/
export const getExperimentIdsFromRoute = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): string[] | null => {
return getExperimentIdsFromRouteParams(routeKind, routeParams);
}
);
/**
* @deprecated
*/
export const getExperimentIdToAliasMap = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): {[id: string]: string} => {
if (routeKind !== RouteKind.COMPARE_EXPERIMENT) {
return {}; | }
const compareParams = routeParams as CompareRouteParams;
const userDefinedAliasMap = getCompareExperimentIdAliasSpec(compareParams);
return Object.fromEntries(userDefinedAliasMap.entries());
}
);
export const getExperimentIdToExperimentAliasMap = createSelector(
getRouteKind,
getRouteParams,
(routeKind, routeParams): {[id: string]: ExperimentAlias} => {
if (routeKind !== RouteKind.COMPARE_EXPERIMENT) {
return {};
}
const compareParams = routeParams as CompareRouteParams;
const map = getCompareExperimentIdAliasWithNumberSpec(compareParams);
return Object.fromEntries(map.entries());
}
); | random_line_split | |
ajax.ts | import { Log } from './log';
//import Url = require('./url');
import { Url } from './url';
import { HashString } from './lib';
/**
* Делаем HTTP (Ajax) запрос.
*
* @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().
* @see {@link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings}
*/
export const Ajax = (opts: JQueryAjaxSettings) => {
// обязательно добавить в запрос тип возвращаемых данных
if (opts.dataType == 'json') {
if (opts.data == null) {
opts.data = { datatype: 'json' }
} else if (typeof opts.data === "string") { // opts.data - строка
let params: HashString = Url.SplitUrlParams(opts.data);
params['datatype'] = 'json';
opts.data = Url.JoinUrlParams(params);
} else { // opts.data - объект
opts.data.datatype = 'json';
}
}
if (opts.xhrFields == null || opts.xhrFields == undefined) {
opts.xhrFields = {
withCredentials: true
};
}
if (opts.error == null || typeof opts.error !== 'function') {
opts.error = function (jqXHR, textStatus, errorThrown) {
Log('error:', textStatus, errorThrown);
}; | // никаких call, apply надо сохранить контекст вызова иногда это важно
original(jqXHR, textStatus, errorThrown);
Log('Ajax.error()', textStatus, errorThrown);
};
}
return $.ajax(opts);
}; | } else {
let original = opts.error;
opts.error = function (jqXHR, textStatus, errorThrown) { | random_line_split |
ajax.ts | import { Log } from './log';
//import Url = require('./url');
import { Url } from './url';
import { HashString } from './lib';
/**
* Делаем HTTP (Ajax) запрос.
*
* @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().
* @see {@link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings}
*/
export const Ajax = (opts: JQueryAjaxSettings) => {
// обязательно добавить в запрос тип возвращаемых данных
if (opts.dataType == 'json') {
if (opts.data == null) {
opts.data = { datatype: 'json' }
} else if (typeof opts.data === "string") { // opts.data - строка
let params: HashString = Url.SplitUrlParams(opts.data);
params['datatype'] = 'json';
opts.data = Url.JoinUrlParams(params);
} else { // opts.data - объект
opts.data.datatype = 'json';
}
}
if (opts.xhrFields == null || opts.xhrFields == undefined) {
opts.xhrFields = {
withCredentials: true
};
}
if (opts.error == null || typeof opts.error !== 'function') {
opts.error = function (jqXHR, textStatus, errorThrown) {
Log('error:', textStatus, errorThrown);
};
} else {
let original = opts.error;
opts.error = function (jqXHR, textStat | us, errorThrown) {
// никаких call, apply надо сохранить контекст вызова иногда это важно
original(jqXHR, textStatus, errorThrown);
Log('Ajax.error()', textStatus, errorThrown);
};
}
return $.ajax(opts);
};
| conditional_block | |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__metaclass__ = PoolMeta
class Event:
__name__ = 'calendar.event'
@classmethod
def __setup__(cls):
super(Event, cls).__setup__()
cls._error_messages.update({
'transparent': 'Free',
'opaque': 'Busy',
})
@classmethod
def search(cls, domain, offset=0, limit=None, order=None, count=False,
query=False):
if Transaction().user:
domain = domain[:]
domain = [domain,
['OR',
[
('classification', '=', 'private'),
['OR',
('calendar.owner', '=', Transaction().user),
('calendar.write_users', '=', Transaction().user),
],
],
('classification', '!=', 'private'),
],
]
records = super(Event, cls).search(domain, offset=offset, limit=limit,
order=order, count=count, query=query)
if Transaction().user:
# Clear the cache as it was not cleaned for confidential
cache = Transaction().get_cache()
cache.pop(cls.__name__, None)
return records
@classmethod
def create(cls, vlist):
events = super(Event, cls).create(vlist)
if (cls.search([('id', 'in', [x.id for x in events])], count=True)
!= len(events)):
cls.raise_user_error('access_error', cls.__doc__)
return events
@classmethod
def _clean_confidential(cls, record, transp):
'''
Clean confidential record
'''
summary = cls.raise_user_error(transp, raise_exception=False)
if 'summary' in record:
record['summary'] = summary
vevent = None
if 'vevent' in record:
vevent = record['vevent']
if vevent:
vevent = vobject.readOne(str(vevent))
if hasattr(vevent, 'summary'):
vevent.summary.value = summary
for field, value in (
('description', ''),
('categories', []),
('location', None),
('status', ''),
('organizer', ''),
('attendees', []),
('alarms', [])):
if field in record:
record[field] = value
if field + '.rec_name' in record:
record[field + '.rec_name'] = ''
if vevent:
if hasattr(vevent, field):
delattr(vevent, field)
if vevent:
record['vevent'] = vevent.serialize()
@classmethod
def read(cls, ids, fields_names=None):
Rule = Pool().get('ir.rule')
cursor = Transaction().connection.cursor()
table = cls.__table__()
if len(set(ids)) != cls.search([('id', 'in', ids)],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
writable_ids = []
domain = Rule.query_get(cls.__name__, mode='write')
if domain:
for sub_ids in grouped_slice(ids): | red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id,
where=red_sql & table.id.in_(domain)))
writable_ids.extend(x[0] for x in cursor.fetchall())
else:
writable_ids = ids
writable_ids = set(writable_ids)
if fields_names is None:
fields_names = []
fields_names = fields_names[:]
to_remove = set()
for field in ('classification', 'calendar', 'transp'):
if field not in fields_names:
fields_names.append(field)
to_remove.add(field)
res = super(Event, cls).read(ids, fields_names=fields_names)
for record in res:
if record['classification'] == 'confidential' \
and record['id'] not in writable_ids:
cls._clean_confidential(record, record['transp'])
for field in to_remove:
del record[field]
return res
@classmethod
def write(cls, *args):
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).write(*args)
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
@classmethod
def delete(cls, events):
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events) | random_line_split | |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__metaclass__ = PoolMeta
class Event:
__name__ = 'calendar.event'
@classmethod
def __setup__(cls):
super(Event, cls).__setup__()
cls._error_messages.update({
'transparent': 'Free',
'opaque': 'Busy',
})
@classmethod
def search(cls, domain, offset=0, limit=None, order=None, count=False,
query=False):
if Transaction().user:
domain = domain[:]
domain = [domain,
['OR',
[
('classification', '=', 'private'),
['OR',
('calendar.owner', '=', Transaction().user),
('calendar.write_users', '=', Transaction().user),
],
],
('classification', '!=', 'private'),
],
]
records = super(Event, cls).search(domain, offset=offset, limit=limit,
order=order, count=count, query=query)
if Transaction().user:
# Clear the cache as it was not cleaned for confidential
cache = Transaction().get_cache()
cache.pop(cls.__name__, None)
return records
@classmethod
def create(cls, vlist):
events = super(Event, cls).create(vlist)
if (cls.search([('id', 'in', [x.id for x in events])], count=True)
!= len(events)):
cls.raise_user_error('access_error', cls.__doc__)
return events
@classmethod
def _clean_confidential(cls, record, transp):
'''
Clean confidential record
'''
summary = cls.raise_user_error(transp, raise_exception=False)
if 'summary' in record:
record['summary'] = summary
vevent = None
if 'vevent' in record:
vevent = record['vevent']
if vevent:
vevent = vobject.readOne(str(vevent))
if hasattr(vevent, 'summary'):
vevent.summary.value = summary
for field, value in (
('description', ''),
('categories', []),
('location', None),
('status', ''),
('organizer', ''),
('attendees', []),
('alarms', [])):
if field in record:
record[field] = value
if field + '.rec_name' in record:
record[field + '.rec_name'] = ''
if vevent:
if hasattr(vevent, field):
delattr(vevent, field)
if vevent:
record['vevent'] = vevent.serialize()
@classmethod
def read(cls, ids, fields_names=None):
Rule = Pool().get('ir.rule')
cursor = Transaction().connection.cursor()
table = cls.__table__()
if len(set(ids)) != cls.search([('id', 'in', ids)],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
writable_ids = []
domain = Rule.query_get(cls.__name__, mode='write')
if domain:
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id,
where=red_sql & table.id.in_(domain)))
writable_ids.extend(x[0] for x in cursor.fetchall())
else:
writable_ids = ids
writable_ids = set(writable_ids)
if fields_names is None:
fields_names = []
fields_names = fields_names[:]
to_remove = set()
for field in ('classification', 'calendar', 'transp'):
if field not in fields_names:
fields_names.append(field)
to_remove.add(field)
res = super(Event, cls).read(ids, fields_names=fields_names)
for record in res:
if record['classification'] == 'confidential' \
and record['id'] not in writable_ids:
cls._clean_confidential(record, record['transp'])
for field in to_remove:
del record[field]
return res
@classmethod
def write(cls, *args):
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).write(*args)
for events in args[::2]:
|
@classmethod
def delete(cls, events):
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events)
| if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__) | conditional_block |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__metaclass__ = PoolMeta
class Event:
__name__ = 'calendar.event'
@classmethod
def __setup__(cls):
super(Event, cls).__setup__()
cls._error_messages.update({
'transparent': 'Free',
'opaque': 'Busy',
})
@classmethod
def | (cls, domain, offset=0, limit=None, order=None, count=False,
query=False):
if Transaction().user:
domain = domain[:]
domain = [domain,
['OR',
[
('classification', '=', 'private'),
['OR',
('calendar.owner', '=', Transaction().user),
('calendar.write_users', '=', Transaction().user),
],
],
('classification', '!=', 'private'),
],
]
records = super(Event, cls).search(domain, offset=offset, limit=limit,
order=order, count=count, query=query)
if Transaction().user:
# Clear the cache as it was not cleaned for confidential
cache = Transaction().get_cache()
cache.pop(cls.__name__, None)
return records
@classmethod
def create(cls, vlist):
events = super(Event, cls).create(vlist)
if (cls.search([('id', 'in', [x.id for x in events])], count=True)
!= len(events)):
cls.raise_user_error('access_error', cls.__doc__)
return events
@classmethod
def _clean_confidential(cls, record, transp):
'''
Clean confidential record
'''
summary = cls.raise_user_error(transp, raise_exception=False)
if 'summary' in record:
record['summary'] = summary
vevent = None
if 'vevent' in record:
vevent = record['vevent']
if vevent:
vevent = vobject.readOne(str(vevent))
if hasattr(vevent, 'summary'):
vevent.summary.value = summary
for field, value in (
('description', ''),
('categories', []),
('location', None),
('status', ''),
('organizer', ''),
('attendees', []),
('alarms', [])):
if field in record:
record[field] = value
if field + '.rec_name' in record:
record[field + '.rec_name'] = ''
if vevent:
if hasattr(vevent, field):
delattr(vevent, field)
if vevent:
record['vevent'] = vevent.serialize()
@classmethod
def read(cls, ids, fields_names=None):
Rule = Pool().get('ir.rule')
cursor = Transaction().connection.cursor()
table = cls.__table__()
if len(set(ids)) != cls.search([('id', 'in', ids)],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
writable_ids = []
domain = Rule.query_get(cls.__name__, mode='write')
if domain:
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id,
where=red_sql & table.id.in_(domain)))
writable_ids.extend(x[0] for x in cursor.fetchall())
else:
writable_ids = ids
writable_ids = set(writable_ids)
if fields_names is None:
fields_names = []
fields_names = fields_names[:]
to_remove = set()
for field in ('classification', 'calendar', 'transp'):
if field not in fields_names:
fields_names.append(field)
to_remove.add(field)
res = super(Event, cls).read(ids, fields_names=fields_names)
for record in res:
if record['classification'] == 'confidential' \
and record['id'] not in writable_ids:
cls._clean_confidential(record, record['transp'])
for field in to_remove:
del record[field]
return res
@classmethod
def write(cls, *args):
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).write(*args)
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
@classmethod
def delete(cls, events):
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events)
| search | identifier_name |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__metaclass__ = PoolMeta
class Event:
__name__ = 'calendar.event'
@classmethod
def __setup__(cls):
super(Event, cls).__setup__()
cls._error_messages.update({
'transparent': 'Free',
'opaque': 'Busy',
})
@classmethod
def search(cls, domain, offset=0, limit=None, order=None, count=False,
query=False):
if Transaction().user:
domain = domain[:]
domain = [domain,
['OR',
[
('classification', '=', 'private'),
['OR',
('calendar.owner', '=', Transaction().user),
('calendar.write_users', '=', Transaction().user),
],
],
('classification', '!=', 'private'),
],
]
records = super(Event, cls).search(domain, offset=offset, limit=limit,
order=order, count=count, query=query)
if Transaction().user:
# Clear the cache as it was not cleaned for confidential
cache = Transaction().get_cache()
cache.pop(cls.__name__, None)
return records
@classmethod
def create(cls, vlist):
events = super(Event, cls).create(vlist)
if (cls.search([('id', 'in', [x.id for x in events])], count=True)
!= len(events)):
cls.raise_user_error('access_error', cls.__doc__)
return events
@classmethod
def _clean_confidential(cls, record, transp):
'''
Clean confidential record
'''
summary = cls.raise_user_error(transp, raise_exception=False)
if 'summary' in record:
record['summary'] = summary
vevent = None
if 'vevent' in record:
vevent = record['vevent']
if vevent:
vevent = vobject.readOne(str(vevent))
if hasattr(vevent, 'summary'):
vevent.summary.value = summary
for field, value in (
('description', ''),
('categories', []),
('location', None),
('status', ''),
('organizer', ''),
('attendees', []),
('alarms', [])):
if field in record:
record[field] = value
if field + '.rec_name' in record:
record[field + '.rec_name'] = ''
if vevent:
if hasattr(vevent, field):
delattr(vevent, field)
if vevent:
record['vevent'] = vevent.serialize()
@classmethod
def read(cls, ids, fields_names=None):
Rule = Pool().get('ir.rule')
cursor = Transaction().connection.cursor()
table = cls.__table__()
if len(set(ids)) != cls.search([('id', 'in', ids)],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
writable_ids = []
domain = Rule.query_get(cls.__name__, mode='write')
if domain:
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id,
where=red_sql & table.id.in_(domain)))
writable_ids.extend(x[0] for x in cursor.fetchall())
else:
writable_ids = ids
writable_ids = set(writable_ids)
if fields_names is None:
fields_names = []
fields_names = fields_names[:]
to_remove = set()
for field in ('classification', 'calendar', 'transp'):
if field not in fields_names:
fields_names.append(field)
to_remove.add(field)
res = super(Event, cls).read(ids, fields_names=fields_names)
for record in res:
if record['classification'] == 'confidential' \
and record['id'] not in writable_ids:
cls._clean_confidential(record, record['transp'])
for field in to_remove:
del record[field]
return res
@classmethod
def write(cls, *args):
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).write(*args)
for events in args[::2]:
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
@classmethod
def delete(cls, events):
| if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events) | identifier_body | |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF_WHITELIST): cv.entity_ids,
vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else:
if req.status_code != 200:
|
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
payload_dict[entity_id] = state_helper.state_as_number(state)
except ValueError:
continue
if payload_dict:
payload = "{%s}" % ",".join("{}:{}".format(key, val)
for key, val in
payload_dict.items())
send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True
| _LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code) | conditional_block |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF_WHITELIST): cv.entity_ids,
vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
|
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
payload_dict[entity_id] = state_helper.state_as_number(state)
except ValueError:
continue
if payload_dict:
payload = "{%s}" % ",".join("{}:{}".format(key, val)
for key, val in
payload_dict.items())
send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True
| """Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else:
if req.status_code != 200:
_LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code) | identifier_body |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import dt as dt_util | _LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF_WHITELIST): cv.entity_ids,
vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else:
if req.status_code != 200:
_LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code)
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
payload_dict[entity_id] = state_helper.state_as_number(state)
except ValueError:
continue
if payload_dict:
payload = "{%s}" % ",".join("{}:{}".format(key, val)
for key, val in
payload_dict.items())
send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True | random_line_split | |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import state as state_helper
from homeassistant.helpers.event import track_point_in_time
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF_WHITELIST): cv.entity_ids,
vol.Optional(CONF_SCAN_INTERVAL, default=30): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def | (hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
timeout=5)
except requests.exceptions.RequestException:
_LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl)
else:
if req.status_code != 200:
_LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code)
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
continue
try:
payload_dict[entity_id] = state_helper.state_as_number(state)
except ValueError:
continue
if payload_dict:
payload = "{%s}" % ",".join("{}:{}".format(key, val)
for key, val in
payload_dict.items())
send_data(conf.get(CONF_URL), conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)), payload)
track_point_in_time(hass, update_emoncms, time +
timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)))
update_emoncms(dt_util.utcnow())
return True
| setup | identifier_name |
typings.d.ts | interface AutoNumericOptions {
aSep?: string
dGroup?: number
aDec?: string
altDec?: string
aSign?: string
pSign?: "p" | "s"
vMin?: number
vMax?: number
mDec?: number
mRound?: "S" | "A" | "s" | "a" | "B" | "U" | "D" | "C" | "F" | "CHF"
aPad?: boolean
nBracket?: string
wEmpty?: "empty" | "zero" | "sign"
lZero?: "allow" | "deny" | "keep"
aForm?: boolean
anDefault?: string
}
interface Serialized {
name: string
value: string
}
type AutoNumericMethod = "init" | "destroy" | "update" | "set" | "get"
| "getString" | "getArray" | "getSettings"
interface JQuery {
autoNumeric(): JQuery
autoNumeric(options: AutoNumericOptions): JQuery
autoNumeric(method: AutoNumericMethod, options?: AutoNumericOptions): JQuery
| string | Serialized[] | AutoNumericOptions | autoNumeric(method: "set", value: string): JQuery
autoNumeric(method: "get"): string
autoNumeric(method: "getString"): string
autoNumeric(method: "getArray"): Serialized[]
autoNumeric(method: "getSettings"): AutoNumericOptions
} | autoNumeric(method: "init", options?: AutoNumericOptions): JQuery
autoNumeric(method: "destroy"): JQuery
autoNumeric(method: "update", options: AutoNumericOptions): JQuery | random_line_split |
operations.py | from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def fill_v0_vx(context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
|
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256
context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y]
context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
}
| context.pc += 2 | conditional_block |
operations.py | from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def | (context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256
context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y]
context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
}
| fill_v0_vx | identifier_name |
operations.py | from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def fill_v0_vx(context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256 | context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
} | context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y] | random_line_split |
operations.py | from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def fill_v0_vx(context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
|
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256
context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y]
context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
}
| import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2 | identifier_body |
torrentEngine.ts | import { createServer, connect, Socket } from "net";
import { wrtcCreateServer, wrtcConnect } from "webrtc-socket";
import { EventEmitter } from "events";
import * as inherits from "inherits";
import { Hash } from "crypto";
import { parse } from "url";
import * as fs from "fs";
import { Client } from "peer-tracker";
import binaryBitfield from "../modules/binary-bitfield";
import * as _ from "lodash";
import * as extend from "extend";
const debug = require("debug")("torrent-engine"),
mkdirp = require("mkdirp"),
TPH = require("torrent-piece-handler").default,
Wire = require("bittorrent-wire").default;
interface PeerData {
bitfield: string; // Pieces this peer has
index: number; // Index of current piece project
piece: number;
}
interface File {
path: string;
name: string;
length: number;
offset: number;
}
interface Torrent {
info: {
name: string
"piece length": number
pieces: Array<string>
};
name: string;
infoHash: string;
created: string;
createdBy: string;
urlList: Array<string>;
files: Array<File>;
length: number;
pieceLength: number;
lastPieceLength: number;
pieces: Array<string>;
uploaded: number;
downloaded: number;
bitfieldDL: string;
finished: Boolean;
left: number;
}
interface Request {
index: number;
begin: number;
length: number;
}
const PeerData = {
bitfield: "00",
index: 0,
piece: 0
};
const MAX_PEERS = 55;
class TorrentHandler extends EventEmitter {
peerID: string;
_debugId: number;
finished: Boolean;
torrent: Torrent;
pieces: Array<string>;
port: number;
trackers: Object;
trackerData: Object;
connectQueue: Array<string>;
haveStack: Array<number>;
bitfieldDL: string;
bitfield: binaryBitfield;
tph: any;
peers: any;
peerCount: number;
wires: any;
incomingPeers: any;
incomingWrtcPeers: any;
inRequests: Array<Request>;
constructor(torrent: any) {
super();
if (!(this instanceof TorrentHandler))
return new TorrentHandler(torrent);
const self = this;
self._debugId = ~~((Math.random() * 100000) + 1);
self.peerID = "-EM0012-ABCDEFGHIJKL";
self.finished = torrent.finished;
self.torrent = torrent;
self.port = null;
// self.port = ~~( ( Math.random() * (65535-1000) ) + 1000 ); // Random port for speeeed.
self.trackers = {};
self.trackerData = {};
self.peers = {};
self.peerCount = 0;
self.wires = {};
self.connectQueue = [];
self.haveStack = [];
self.bitfieldDL = torrent.bitfieldDL || "00";
self.bitfield = (!torrent.pieces) ? null : new binaryBitfield(torrent.pieces.length, torrent.bitfieldDL);
self.tph = (!torrent.pieces) ? null : new TPH(torrent.files, torrent.length, torrent.pieceLength, torrent.pieces.length, torrent.lastPieceLength);
// Health Insurrance:
process.on("uncaughtException", function (err) {
self._debug(err);
});
// Incoming (TCP)
self.incomingPeers = createServer((socket) => {
self.createIncomingPeer(socket);
}).listen(0, () => {
self.port = self.incomingPeers.address().port;
self._debug("Listening on port:", self.port);
});
// Eventually add WS support
self.incomingWrtcPeers = wrtcCreateServer((socket) => {
self.createIncomingPeer(socket);
});
self.incomingWrtcPeers.listen(9001);
// Trackers (WSS/UDP)
self.torrent["announce"].forEach((tracker: string) => {
let pt = parse(tracker);
if (pt.protocol === "udp:") {
self.trackers[tracker] = Client.udp("scrape", pt.hostname, pt.port, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "wss:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 443, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "ws:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 80, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
}
self.trackers[tracker].on("announce", (interval, leechers, seeders, peers) => {
peers = peers.map((peer) => { return peer + ":" + ( (self.trackers[tracker].TYPE === "udp") ? "tcp" : "ws" ); });
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.trackers[tracker].on("error", () => {
self.trackerData[tracker + ":failure"] = true;
});
self.trackers[tracker].on("scrape", (seeders, completed, leechers, timeTillNextScrape) => {
self.trackerData[tracker + ":seeders"] = seeders;
self.trackerData[tracker + ":completed"] = completed;
self.trackerData[tracker + ":leechers"] = leechers;
self.trackerData[tracker + ":nextReq"] = timeTillNextScrape;
});
});
}
newConnectionRequests() {
const self = this;
// Determine how much room we have to add peers and connect.
while (self.peerCount < MAX_PEERS && (self.connectQueue.length)) {
let peer = self.connectQueue.shift().split(":");
self.createPeer(Number(peer[1]), peer[0], peer[2]);
}
}
createIncomingPeer(socket) {
const self = this;
let host = (socket.remoteAddress) ? socket.remoteAddress : socket.host,
port = (socket.remotePort) ? socket.remotePort : socket.port,
family = (socket.remoteFamily) ? socket.remoteFamily : socket.family,
wire = self.wires[host] = new Wire(self.torrent.infoHash, self.peerID);
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family, wire, socket, bitfield: "00", position: 0, piece: (-1), mode: 2, activeCount: 0 };
socket.pipe(wire).pipe(socket);
// TODO: SET BITFIELDDL DURING DOWNLOAD
wire.on("handshake", (infoHash: Buffer, peerID: string) => {
if (self.torrent.infoHash !== infoHash.toString("hex"))
return;
// Send handshake, metadata handshake, and bitfield.
wire.sendHandshake();
wire.sendBitfield(self.bitfieldDL);
});
wire.on("request", () => {
if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) {
let request = wire.inRequests.shift();
self.tph.prepareUpload(request.index, request.begin, request.length, (piece: Buffer) => {
process.nextTick(() => {
wire.sendPiece(piece);
});
});
}
wire.reqBusy = false;
}
});
wire.on("have", (pieceIndex: number) => {
// TODO: If new piece and not a seeder, switch to download phase and grab
});
self.peers[host + port].socket.on("close", () => {
self._debug("the socket decided to leave");
// Destroy the wire and delete the Object
self.peers[host + port] = null;
delete self.peers[host + port];
});
}
createPeer(port: number, host: string, type: string) {
const self = this;
self._debug("Create new peer");
self.peerCount++;
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family: "ipv4", wire: new Wire(self.torrent.infoHash, self.peerID), socket: null, bitfield: "00", position: 0, piece: (-1), mode: 0, activeCount: 0 };
if (type === "tcp")
self.peers[host + port].socket = connect(port, host);
else if (type === "ws")
self.peers[host + port].socket = wrtcConnect(port, host);
self.peers[host + port].socket.once("connect", () => {
self.peers[host + port]["socket"].pipe(self.peers[host + port].wire).pipe(self.peers[host + port]["socket"]);
self.peers[host + port].wire.sendHandshake();
});
self.peers[host + port].socket.on("error", (err) => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
self.peers[host + port].wire.closeConnection();
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.newConnectionRequests();
});
self.peers[host + port].socket.on("close", () => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
if (self.peers[host + port].socket)
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.peerCount--;
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("metadata", (torrent) => {
self._debug("Incoming metadata");
// Add the data to our torrent
extend(self.torrent, torrent);
// Prepare bitfield, files, and block handler
self.bitfield = new binaryBitfield(self.torrent.pieces.length, self.torrent.bitfieldDL);
self.manageFiles();
self.tph = new TPH(self.torrent.files, self.torrent.length, self.torrent.pieceLength, self.torrent.pieces.length, self.torrent.lastPieceLength);
// Convert all peers who are currently in meta_data mode to download mode
self._debug("Download phase");
self.downloadPhase(); // (from mode: 3, to: 1)
});
self.peers[host + port]["wire"].on("pex_added", (peers) => {
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("bitfield", (payload) => {
self._debug("peer's bitfield");
// Add the bitfield to the host+port
self.peers[host + port].bitfield = payload;
// Check that we have a connection:
if (self.peers[host + port]["wire"].isChoked)
self.peers[host + port]["wire"].sendInterested();
// Fetch some data if torrent. Otherwise ut_metadata (magnet)
if (self.torrent.pieces) {
self.peers[host + port].mode = 1;
self.fetchNewPiece(self.peers[host + port]); // Get some blocks!
} else {
self.peers[host + port].mode = 3;
self.peers[host + port]["wire"].metaDataRequest(); // Get metadata
}
});
self.peers[host + port]["wire"].on("have", (payload) => {
if (!self.bitfield)
return;
// UPDATE bitfield here
self.peers[host + port].bitfield = self.bitfield.onHave(payload, self.peers[host + port].bitfield);
// IF we are already sending a request and recieving a piece... hold your horses
let busy = self.peers[host + port]["wire"].isBusy();
// Additionally, if we don't get have torrent data or we have already finished the projet, ignore.
if (!busy && !self.finished && self.torrent.pieces.length) {
self.peers[host + port]["wire"].setBusy();
self.fetchNewPiece(self.peers[host + port]);
}
});
self.peers[host + port]["wire"].on("finished_piece", (index: number, block: Buffer, hash: Hash) => {
self._debug("finished piece");
self._debug("peerCount: ", self.peerCount);
let speed = 0;
for (let p in self.peers) {
speed += self.peers[p]["wire"].downloadSpeed();
}
// Check the hash
let blockHash = hash.digest("hex");
let percent = 0;
if (blockHash === self.torrent.pieces[index]) {
// Update downloaded:
self.torrent.downloaded += block.length;
self.torrent.left -= block.length;
// Place the buffer in its proper home
self.tph.saveBlock(self.peers[host + port].position, block);
// Check the percent of downloaded
percent = self.bitfield.setDownloaded(self.peers[host + port].piece);
// Emit up.
// self.emit('finished_piece', percent, );
} else {
self._debug("failed hash");
// Remove piece and try again
self.bitfield.set(self.peers[host + port].piece, false);
}
self._debug("index downloaded: ", index);
self._debug("percent: ", percent);
if (percent === 1) {
self.finished = true;
self.finish();
self.cleanupSeeders();
} else {
// Start a new request sequence
process.nextTick(() => {
self.fetchNewPiece(self.peers[host + port]);
});
}
});
}
fetchNewPiece(peer) {
const self = this;
self.bitfield.findNewPieces(peer.bitfield, (result, downloading, which) => {
if (which !== (-1)) {
// Set the peers piece number and index of piece
peer.piece = which;
peer.position = self.tph.pieceIndex(which);
// Prepare a request for the pieces
self.tph.prepareRequest(which, (buf, count) => {
// Send to wire.
this._debug(`send ${count} piece request(s)`);
peer["wire"].sendRequest(buf, count);
});
} else {
// A have might be sent instead...
peer["wire"].unsetBusy();
}
});
}
// MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata
downloadPhase() {
const self = this;
for (let host in self.peers) {
// Convert metadata peers to downloaders:
if (self.peers[host].mode === 3) {
// Kill the metadata instance
self.peers[host]["wire"].removeMeta();
}
// Change the mode
self.peers[host].mode = 1;
// Fetch new pieces
self.fetchNewPiece(self.peers[host]);
}
}
finish() {
const self = this;
self._debug("DONE");
// for (let tracker in self.trackers) {
// if (!self.trackers[tracker + ":failure"])
// self.trackers[tracker].completed(self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
// }
}
cleanupSeeders() {
const self = this;
for (let host in self.peers) {
if ( self.bitfield.isSeeder(self.peers[host].bitfield) ) {
self.peers[host].wire.closeConnection();
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
}
| () {
const self = this;
for (let host in self.peers) {
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
manageFiles() {
this.torrent["files"] = this.torrent["files"].map((file) => {
// TODO: Setup the proper location to download
let downloadDirectory = "Downloads";
let folders = __dirname + "/" + downloadDirectory + "/" + file.path;
let f = folders.split("/");
let fileName = f.splice(-1);
folders = f.join("/");
mkdirp(folders, function (err) {
if (err) console.error(err);
else fs.writeFileSync(folders + "/" + fileName, new Buffer(file.length));
});
file.path = folders + "/" + fileName;
return file;
});
}
_debug = (...args: any[]) => {
args[0] = "[" + this._debugId + "] " + args[0];
debug.apply(null, args);
}
}
export default TorrentHandler;
| cleanupAll | identifier_name |
torrentEngine.ts | import { createServer, connect, Socket } from "net";
import { wrtcCreateServer, wrtcConnect } from "webrtc-socket";
import { EventEmitter } from "events";
import * as inherits from "inherits";
import { Hash } from "crypto";
import { parse } from "url";
import * as fs from "fs";
import { Client } from "peer-tracker";
import binaryBitfield from "../modules/binary-bitfield";
import * as _ from "lodash";
import * as extend from "extend";
const debug = require("debug")("torrent-engine"),
mkdirp = require("mkdirp"),
TPH = require("torrent-piece-handler").default,
Wire = require("bittorrent-wire").default;
interface PeerData {
bitfield: string; // Pieces this peer has
index: number; // Index of current piece project
piece: number;
}
interface File {
path: string;
name: string;
length: number;
offset: number;
}
interface Torrent {
info: {
name: string
"piece length": number
pieces: Array<string>
};
name: string;
infoHash: string;
created: string;
createdBy: string;
urlList: Array<string>;
files: Array<File>;
length: number;
pieceLength: number;
lastPieceLength: number;
pieces: Array<string>;
uploaded: number;
downloaded: number;
bitfieldDL: string;
finished: Boolean;
left: number;
}
interface Request {
index: number;
begin: number;
length: number;
}
const PeerData = {
bitfield: "00",
index: 0,
piece: 0
};
const MAX_PEERS = 55;
class TorrentHandler extends EventEmitter {
peerID: string;
_debugId: number;
finished: Boolean;
torrent: Torrent;
pieces: Array<string>;
port: number;
trackers: Object;
trackerData: Object;
connectQueue: Array<string>;
haveStack: Array<number>;
bitfieldDL: string;
bitfield: binaryBitfield;
tph: any;
peers: any;
peerCount: number;
wires: any;
incomingPeers: any;
incomingWrtcPeers: any;
inRequests: Array<Request>;
constructor(torrent: any) {
super();
if (!(this instanceof TorrentHandler))
return new TorrentHandler(torrent);
const self = this;
self._debugId = ~~((Math.random() * 100000) + 1);
self.peerID = "-EM0012-ABCDEFGHIJKL";
self.finished = torrent.finished;
self.torrent = torrent;
self.port = null;
// self.port = ~~( ( Math.random() * (65535-1000) ) + 1000 ); // Random port for speeeed.
self.trackers = {};
self.trackerData = {};
self.peers = {};
self.peerCount = 0;
self.wires = {};
self.connectQueue = [];
self.haveStack = [];
self.bitfieldDL = torrent.bitfieldDL || "00";
self.bitfield = (!torrent.pieces) ? null : new binaryBitfield(torrent.pieces.length, torrent.bitfieldDL);
self.tph = (!torrent.pieces) ? null : new TPH(torrent.files, torrent.length, torrent.pieceLength, torrent.pieces.length, torrent.lastPieceLength);
// Health Insurrance:
process.on("uncaughtException", function (err) {
self._debug(err);
});
// Incoming (TCP)
self.incomingPeers = createServer((socket) => {
self.createIncomingPeer(socket);
}).listen(0, () => {
self.port = self.incomingPeers.address().port;
self._debug("Listening on port:", self.port);
});
// Eventually add WS support
self.incomingWrtcPeers = wrtcCreateServer((socket) => {
self.createIncomingPeer(socket);
});
self.incomingWrtcPeers.listen(9001);
// Trackers (WSS/UDP)
self.torrent["announce"].forEach((tracker: string) => {
let pt = parse(tracker);
if (pt.protocol === "udp:") {
self.trackers[tracker] = Client.udp("scrape", pt.hostname, pt.port, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "wss:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 443, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "ws:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 80, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
}
self.trackers[tracker].on("announce", (interval, leechers, seeders, peers) => {
peers = peers.map((peer) => { return peer + ":" + ( (self.trackers[tracker].TYPE === "udp") ? "tcp" : "ws" ); });
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.trackers[tracker].on("error", () => {
self.trackerData[tracker + ":failure"] = true;
});
self.trackers[tracker].on("scrape", (seeders, completed, leechers, timeTillNextScrape) => {
self.trackerData[tracker + ":seeders"] = seeders;
self.trackerData[tracker + ":completed"] = completed;
self.trackerData[tracker + ":leechers"] = leechers;
self.trackerData[tracker + ":nextReq"] = timeTillNextScrape;
});
});
}
newConnectionRequests() {
const self = this;
// Determine how much room we have to add peers and connect.
while (self.peerCount < MAX_PEERS && (self.connectQueue.length)) {
let peer = self.connectQueue.shift().split(":");
self.createPeer(Number(peer[1]), peer[0], peer[2]);
}
}
createIncomingPeer(socket) {
const self = this;
let host = (socket.remoteAddress) ? socket.remoteAddress : socket.host,
port = (socket.remotePort) ? socket.remotePort : socket.port,
family = (socket.remoteFamily) ? socket.remoteFamily : socket.family,
wire = self.wires[host] = new Wire(self.torrent.infoHash, self.peerID);
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family, wire, socket, bitfield: "00", position: 0, piece: (-1), mode: 2, activeCount: 0 };
socket.pipe(wire).pipe(socket);
// TODO: SET BITFIELDDL DURING DOWNLOAD
wire.on("handshake", (infoHash: Buffer, peerID: string) => {
if (self.torrent.infoHash !== infoHash.toString("hex"))
return;
// Send handshake, metadata handshake, and bitfield.
wire.sendHandshake();
wire.sendBitfield(self.bitfieldDL);
});
wire.on("request", () => {
if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) {
let request = wire.inRequests.shift();
self.tph.prepareUpload(request.index, request.begin, request.length, (piece: Buffer) => {
process.nextTick(() => {
wire.sendPiece(piece);
});
});
}
wire.reqBusy = false;
}
});
wire.on("have", (pieceIndex: number) => {
// TODO: If new piece and not a seeder, switch to download phase and grab
});
self.peers[host + port].socket.on("close", () => {
self._debug("the socket decided to leave");
// Destroy the wire and delete the Object
self.peers[host + port] = null;
delete self.peers[host + port];
});
}
createPeer(port: number, host: string, type: string) {
const self = this;
self._debug("Create new peer");
self.peerCount++;
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family: "ipv4", wire: new Wire(self.torrent.infoHash, self.peerID), socket: null, bitfield: "00", position: 0, piece: (-1), mode: 0, activeCount: 0 };
if (type === "tcp")
self.peers[host + port].socket = connect(port, host);
else if (type === "ws")
self.peers[host + port].socket = wrtcConnect(port, host);
self.peers[host + port].socket.once("connect", () => {
self.peers[host + port]["socket"].pipe(self.peers[host + port].wire).pipe(self.peers[host + port]["socket"]);
self.peers[host + port].wire.sendHandshake();
});
self.peers[host + port].socket.on("error", (err) => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
self.peers[host + port].wire.closeConnection();
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.newConnectionRequests();
});
self.peers[host + port].socket.on("close", () => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
if (self.peers[host + port].socket)
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.peerCount--;
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("metadata", (torrent) => {
self._debug("Incoming metadata");
// Add the data to our torrent
extend(self.torrent, torrent);
// Prepare bitfield, files, and block handler
self.bitfield = new binaryBitfield(self.torrent.pieces.length, self.torrent.bitfieldDL);
self.manageFiles();
self.tph = new TPH(self.torrent.files, self.torrent.length, self.torrent.pieceLength, self.torrent.pieces.length, self.torrent.lastPieceLength);
// Convert all peers who are currently in meta_data mode to download mode
self._debug("Download phase");
self.downloadPhase(); // (from mode: 3, to: 1)
});
self.peers[host + port]["wire"].on("pex_added", (peers) => {
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("bitfield", (payload) => {
self._debug("peer's bitfield");
// Add the bitfield to the host+port
self.peers[host + port].bitfield = payload;
// Check that we have a connection:
if (self.peers[host + port]["wire"].isChoked)
self.peers[host + port]["wire"].sendInterested();
// Fetch some data if torrent. Otherwise ut_metadata (magnet)
if (self.torrent.pieces) {
self.peers[host + port].mode = 1;
self.fetchNewPiece(self.peers[host + port]); // Get some blocks!
} else {
self.peers[host + port].mode = 3;
self.peers[host + port]["wire"].metaDataRequest(); // Get metadata
}
});
self.peers[host + port]["wire"].on("have", (payload) => {
if (!self.bitfield)
return;
// UPDATE bitfield here
self.peers[host + port].bitfield = self.bitfield.onHave(payload, self.peers[host + port].bitfield);
// IF we are already sending a request and recieving a piece... hold your horses
let busy = self.peers[host + port]["wire"].isBusy();
// Additionally, if we don't get have torrent data or we have already finished the projet, ignore.
if (!busy && !self.finished && self.torrent.pieces.length) {
self.peers[host + port]["wire"].setBusy();
self.fetchNewPiece(self.peers[host + port]);
}
});
self.peers[host + port]["wire"].on("finished_piece", (index: number, block: Buffer, hash: Hash) => {
self._debug("finished piece");
self._debug("peerCount: ", self.peerCount);
let speed = 0;
for (let p in self.peers) {
speed += self.peers[p]["wire"].downloadSpeed();
}
// Check the hash
let blockHash = hash.digest("hex");
let percent = 0;
if (blockHash === self.torrent.pieces[index]) {
// Update downloaded:
self.torrent.downloaded += block.length;
self.torrent.left -= block.length;
// Place the buffer in its proper home
self.tph.saveBlock(self.peers[host + port].position, block);
// Check the percent of downloaded
percent = self.bitfield.setDownloaded(self.peers[host + port].piece);
// Emit up.
// self.emit('finished_piece', percent, );
} else {
self._debug("failed hash");
// Remove piece and try again
self.bitfield.set(self.peers[host + port].piece, false);
}
self._debug("index downloaded: ", index);
self._debug("percent: ", percent);
if (percent === 1) {
self.finished = true;
self.finish();
self.cleanupSeeders();
} else {
// Start a new request sequence
process.nextTick(() => {
self.fetchNewPiece(self.peers[host + port]);
});
}
});
}
fetchNewPiece(peer) {
const self = this;
self.bitfield.findNewPieces(peer.bitfield, (result, downloading, which) => {
if (which !== (-1)) { | peer.piece = which;
peer.position = self.tph.pieceIndex(which);
// Prepare a request for the pieces
self.tph.prepareRequest(which, (buf, count) => {
// Send to wire.
this._debug(`send ${count} piece request(s)`);
peer["wire"].sendRequest(buf, count);
});
} else {
// A have might be sent instead...
peer["wire"].unsetBusy();
}
});
}
// MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata
downloadPhase() {
const self = this;
for (let host in self.peers) {
// Convert metadata peers to downloaders:
if (self.peers[host].mode === 3) {
// Kill the metadata instance
self.peers[host]["wire"].removeMeta();
}
// Change the mode
self.peers[host].mode = 1;
// Fetch new pieces
self.fetchNewPiece(self.peers[host]);
}
}
finish() {
const self = this;
self._debug("DONE");
// for (let tracker in self.trackers) {
// if (!self.trackers[tracker + ":failure"])
// self.trackers[tracker].completed(self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
// }
}
cleanupSeeders() {
const self = this;
for (let host in self.peers) {
if ( self.bitfield.isSeeder(self.peers[host].bitfield) ) {
self.peers[host].wire.closeConnection();
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
}
cleanupAll() {
const self = this;
for (let host in self.peers) {
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
manageFiles() {
this.torrent["files"] = this.torrent["files"].map((file) => {
// TODO: Setup the proper location to download
let downloadDirectory = "Downloads";
let folders = __dirname + "/" + downloadDirectory + "/" + file.path;
let f = folders.split("/");
let fileName = f.splice(-1);
folders = f.join("/");
mkdirp(folders, function (err) {
if (err) console.error(err);
else fs.writeFileSync(folders + "/" + fileName, new Buffer(file.length));
});
file.path = folders + "/" + fileName;
return file;
});
}
_debug = (...args: any[]) => {
args[0] = "[" + this._debugId + "] " + args[0];
debug.apply(null, args);
}
}
export default TorrentHandler; | // Set the peers piece number and index of piece | random_line_split |
torrentEngine.ts | import { createServer, connect, Socket } from "net";
import { wrtcCreateServer, wrtcConnect } from "webrtc-socket";
import { EventEmitter } from "events";
import * as inherits from "inherits";
import { Hash } from "crypto";
import { parse } from "url";
import * as fs from "fs";
import { Client } from "peer-tracker";
import binaryBitfield from "../modules/binary-bitfield";
import * as _ from "lodash";
import * as extend from "extend";
const debug = require("debug")("torrent-engine"),
mkdirp = require("mkdirp"),
TPH = require("torrent-piece-handler").default,
Wire = require("bittorrent-wire").default;
interface PeerData {
bitfield: string; // Pieces this peer has
index: number; // Index of current piece project
piece: number;
}
interface File {
path: string;
name: string;
length: number;
offset: number;
}
interface Torrent {
info: {
name: string
"piece length": number
pieces: Array<string>
};
name: string;
infoHash: string;
created: string;
createdBy: string;
urlList: Array<string>;
files: Array<File>;
length: number;
pieceLength: number;
lastPieceLength: number;
pieces: Array<string>;
uploaded: number;
downloaded: number;
bitfieldDL: string;
finished: Boolean;
left: number;
}
interface Request {
index: number;
begin: number;
length: number;
}
const PeerData = {
bitfield: "00",
index: 0,
piece: 0
};
const MAX_PEERS = 55;
class TorrentHandler extends EventEmitter {
peerID: string;
_debugId: number;
finished: Boolean;
torrent: Torrent;
pieces: Array<string>;
port: number;
trackers: Object;
trackerData: Object;
connectQueue: Array<string>;
haveStack: Array<number>;
bitfieldDL: string;
bitfield: binaryBitfield;
tph: any;
peers: any;
peerCount: number;
wires: any;
incomingPeers: any;
incomingWrtcPeers: any;
inRequests: Array<Request>;
constructor(torrent: any) {
super();
if (!(this instanceof TorrentHandler))
return new TorrentHandler(torrent);
const self = this;
self._debugId = ~~((Math.random() * 100000) + 1);
self.peerID = "-EM0012-ABCDEFGHIJKL";
self.finished = torrent.finished;
self.torrent = torrent;
self.port = null;
// self.port = ~~( ( Math.random() * (65535-1000) ) + 1000 ); // Random port for speeeed.
self.trackers = {};
self.trackerData = {};
self.peers = {};
self.peerCount = 0;
self.wires = {};
self.connectQueue = [];
self.haveStack = [];
self.bitfieldDL = torrent.bitfieldDL || "00";
self.bitfield = (!torrent.pieces) ? null : new binaryBitfield(torrent.pieces.length, torrent.bitfieldDL);
self.tph = (!torrent.pieces) ? null : new TPH(torrent.files, torrent.length, torrent.pieceLength, torrent.pieces.length, torrent.lastPieceLength);
// Health Insurrance:
process.on("uncaughtException", function (err) {
self._debug(err);
});
// Incoming (TCP)
self.incomingPeers = createServer((socket) => {
self.createIncomingPeer(socket);
}).listen(0, () => {
self.port = self.incomingPeers.address().port;
self._debug("Listening on port:", self.port);
});
// Eventually add WS support
self.incomingWrtcPeers = wrtcCreateServer((socket) => {
self.createIncomingPeer(socket);
});
self.incomingWrtcPeers.listen(9001);
// Trackers (WSS/UDP)
self.torrent["announce"].forEach((tracker: string) => {
let pt = parse(tracker);
if (pt.protocol === "udp:") {
self.trackers[tracker] = Client.udp("scrape", pt.hostname, pt.port, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "wss:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 443, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "ws:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 80, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
}
self.trackers[tracker].on("announce", (interval, leechers, seeders, peers) => {
peers = peers.map((peer) => { return peer + ":" + ( (self.trackers[tracker].TYPE === "udp") ? "tcp" : "ws" ); });
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.trackers[tracker].on("error", () => {
self.trackerData[tracker + ":failure"] = true;
});
self.trackers[tracker].on("scrape", (seeders, completed, leechers, timeTillNextScrape) => {
self.trackerData[tracker + ":seeders"] = seeders;
self.trackerData[tracker + ":completed"] = completed;
self.trackerData[tracker + ":leechers"] = leechers;
self.trackerData[tracker + ":nextReq"] = timeTillNextScrape;
});
});
}
newConnectionRequests() {
const self = this;
// Determine how much room we have to add peers and connect.
while (self.peerCount < MAX_PEERS && (self.connectQueue.length)) {
let peer = self.connectQueue.shift().split(":");
self.createPeer(Number(peer[1]), peer[0], peer[2]);
}
}
createIncomingPeer(socket) {
const self = this;
let host = (socket.remoteAddress) ? socket.remoteAddress : socket.host,
port = (socket.remotePort) ? socket.remotePort : socket.port,
family = (socket.remoteFamily) ? socket.remoteFamily : socket.family,
wire = self.wires[host] = new Wire(self.torrent.infoHash, self.peerID);
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family, wire, socket, bitfield: "00", position: 0, piece: (-1), mode: 2, activeCount: 0 };
socket.pipe(wire).pipe(socket);
// TODO: SET BITFIELDDL DURING DOWNLOAD
wire.on("handshake", (infoHash: Buffer, peerID: string) => {
if (self.torrent.infoHash !== infoHash.toString("hex"))
return;
// Send handshake, metadata handshake, and bitfield.
wire.sendHandshake();
wire.sendBitfield(self.bitfieldDL);
});
wire.on("request", () => {
if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) {
let request = wire.inRequests.shift();
self.tph.prepareUpload(request.index, request.begin, request.length, (piece: Buffer) => {
process.nextTick(() => {
wire.sendPiece(piece);
});
});
}
wire.reqBusy = false;
}
});
wire.on("have", (pieceIndex: number) => {
// TODO: If new piece and not a seeder, switch to download phase and grab
});
self.peers[host + port].socket.on("close", () => {
self._debug("the socket decided to leave");
// Destroy the wire and delete the Object
self.peers[host + port] = null;
delete self.peers[host + port];
});
}
createPeer(port: number, host: string, type: string) {
const self = this;
self._debug("Create new peer");
self.peerCount++;
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family: "ipv4", wire: new Wire(self.torrent.infoHash, self.peerID), socket: null, bitfield: "00", position: 0, piece: (-1), mode: 0, activeCount: 0 };
if (type === "tcp")
self.peers[host + port].socket = connect(port, host);
else if (type === "ws")
self.peers[host + port].socket = wrtcConnect(port, host);
self.peers[host + port].socket.once("connect", () => {
self.peers[host + port]["socket"].pipe(self.peers[host + port].wire).pipe(self.peers[host + port]["socket"]);
self.peers[host + port].wire.sendHandshake();
});
self.peers[host + port].socket.on("error", (err) => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
self.peers[host + port].wire.closeConnection();
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.newConnectionRequests();
});
self.peers[host + port].socket.on("close", () => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
if (self.peers[host + port].socket)
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.peerCount--;
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("metadata", (torrent) => {
self._debug("Incoming metadata");
// Add the data to our torrent
extend(self.torrent, torrent);
// Prepare bitfield, files, and block handler
self.bitfield = new binaryBitfield(self.torrent.pieces.length, self.torrent.bitfieldDL);
self.manageFiles();
self.tph = new TPH(self.torrent.files, self.torrent.length, self.torrent.pieceLength, self.torrent.pieces.length, self.torrent.lastPieceLength);
// Convert all peers who are currently in meta_data mode to download mode
self._debug("Download phase");
self.downloadPhase(); // (from mode: 3, to: 1)
});
self.peers[host + port]["wire"].on("pex_added", (peers) => {
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("bitfield", (payload) => {
self._debug("peer's bitfield");
// Add the bitfield to the host+port
self.peers[host + port].bitfield = payload;
// Check that we have a connection:
if (self.peers[host + port]["wire"].isChoked)
self.peers[host + port]["wire"].sendInterested();
// Fetch some data if torrent. Otherwise ut_metadata (magnet)
if (self.torrent.pieces) {
self.peers[host + port].mode = 1;
self.fetchNewPiece(self.peers[host + port]); // Get some blocks!
} else {
self.peers[host + port].mode = 3;
self.peers[host + port]["wire"].metaDataRequest(); // Get metadata
}
});
self.peers[host + port]["wire"].on("have", (payload) => {
if (!self.bitfield)
return;
// UPDATE bitfield here
self.peers[host + port].bitfield = self.bitfield.onHave(payload, self.peers[host + port].bitfield);
// IF we are already sending a request and recieving a piece... hold your horses
let busy = self.peers[host + port]["wire"].isBusy();
// Additionally, if we don't get have torrent data or we have already finished the projet, ignore.
if (!busy && !self.finished && self.torrent.pieces.length) {
self.peers[host + port]["wire"].setBusy();
self.fetchNewPiece(self.peers[host + port]);
}
});
self.peers[host + port]["wire"].on("finished_piece", (index: number, block: Buffer, hash: Hash) => {
self._debug("finished piece");
self._debug("peerCount: ", self.peerCount);
let speed = 0;
for (let p in self.peers) {
speed += self.peers[p]["wire"].downloadSpeed();
}
// Check the hash
let blockHash = hash.digest("hex");
let percent = 0;
if (blockHash === self.torrent.pieces[index]) {
// Update downloaded:
self.torrent.downloaded += block.length;
self.torrent.left -= block.length;
// Place the buffer in its proper home
self.tph.saveBlock(self.peers[host + port].position, block);
// Check the percent of downloaded
percent = self.bitfield.setDownloaded(self.peers[host + port].piece);
// Emit up.
// self.emit('finished_piece', percent, );
} else {
self._debug("failed hash");
// Remove piece and try again
self.bitfield.set(self.peers[host + port].piece, false);
}
self._debug("index downloaded: ", index);
self._debug("percent: ", percent);
if (percent === 1) {
self.finished = true;
self.finish();
self.cleanupSeeders();
} else {
// Start a new request sequence
process.nextTick(() => {
self.fetchNewPiece(self.peers[host + port]);
});
}
});
}
fetchNewPiece(peer) {
const self = this;
self.bitfield.findNewPieces(peer.bitfield, (result, downloading, which) => {
if (which !== (-1)) {
// Set the peers piece number and index of piece
peer.piece = which;
peer.position = self.tph.pieceIndex(which);
// Prepare a request for the pieces
self.tph.prepareRequest(which, (buf, count) => {
// Send to wire.
this._debug(`send ${count} piece request(s)`);
peer["wire"].sendRequest(buf, count);
});
} else {
// A have might be sent instead...
peer["wire"].unsetBusy();
}
});
}
// MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata
downloadPhase() {
const self = this;
for (let host in self.peers) {
// Convert metadata peers to downloaders:
if (self.peers[host].mode === 3) {
// Kill the metadata instance
self.peers[host]["wire"].removeMeta();
}
// Change the mode
self.peers[host].mode = 1;
// Fetch new pieces
self.fetchNewPiece(self.peers[host]);
}
}
finish() {
const self = this;
self._debug("DONE");
// for (let tracker in self.trackers) {
// if (!self.trackers[tracker + ":failure"])
// self.trackers[tracker].completed(self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
// }
}
cleanupSeeders() {
const self = this;
for (let host in self.peers) {
if ( self.bitfield.isSeeder(self.peers[host].bitfield) ) {
self.peers[host].wire.closeConnection();
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
}
cleanupAll() |
manageFiles() {
this.torrent["files"] = this.torrent["files"].map((file) => {
// TODO: Setup the proper location to download
let downloadDirectory = "Downloads";
let folders = __dirname + "/" + downloadDirectory + "/" + file.path;
let f = folders.split("/");
let fileName = f.splice(-1);
folders = f.join("/");
mkdirp(folders, function (err) {
if (err) console.error(err);
else fs.writeFileSync(folders + "/" + fileName, new Buffer(file.length));
});
file.path = folders + "/" + fileName;
return file;
});
}
_debug = (...args: any[]) => {
args[0] = "[" + this._debugId + "] " + args[0];
debug.apply(null, args);
}
}
export default TorrentHandler;
| {
const self = this;
for (let host in self.peers) {
self.peers[host].socket.destroy();
delete self.peers[host];
}
} | identifier_body |
torrentEngine.ts | import { createServer, connect, Socket } from "net";
import { wrtcCreateServer, wrtcConnect } from "webrtc-socket";
import { EventEmitter } from "events";
import * as inherits from "inherits";
import { Hash } from "crypto";
import { parse } from "url";
import * as fs from "fs";
import { Client } from "peer-tracker";
import binaryBitfield from "../modules/binary-bitfield";
import * as _ from "lodash";
import * as extend from "extend";
const debug = require("debug")("torrent-engine"),
mkdirp = require("mkdirp"),
TPH = require("torrent-piece-handler").default,
Wire = require("bittorrent-wire").default;
interface PeerData {
bitfield: string; // Pieces this peer has
index: number; // Index of current piece project
piece: number;
}
interface File {
path: string;
name: string;
length: number;
offset: number;
}
interface Torrent {
info: {
name: string
"piece length": number
pieces: Array<string>
};
name: string;
infoHash: string;
created: string;
createdBy: string;
urlList: Array<string>;
files: Array<File>;
length: number;
pieceLength: number;
lastPieceLength: number;
pieces: Array<string>;
uploaded: number;
downloaded: number;
bitfieldDL: string;
finished: Boolean;
left: number;
}
interface Request {
index: number;
begin: number;
length: number;
}
const PeerData = {
bitfield: "00",
index: 0,
piece: 0
};
const MAX_PEERS = 55;
class TorrentHandler extends EventEmitter {
peerID: string;
_debugId: number;
finished: Boolean;
torrent: Torrent;
pieces: Array<string>;
port: number;
trackers: Object;
trackerData: Object;
connectQueue: Array<string>;
haveStack: Array<number>;
bitfieldDL: string;
bitfield: binaryBitfield;
tph: any;
peers: any;
peerCount: number;
wires: any;
incomingPeers: any;
incomingWrtcPeers: any;
inRequests: Array<Request>;
constructor(torrent: any) {
super();
if (!(this instanceof TorrentHandler))
return new TorrentHandler(torrent);
const self = this;
self._debugId = ~~((Math.random() * 100000) + 1);
self.peerID = "-EM0012-ABCDEFGHIJKL";
self.finished = torrent.finished;
self.torrent = torrent;
self.port = null;
// self.port = ~~( ( Math.random() * (65535-1000) ) + 1000 ); // Random port for speeeed.
self.trackers = {};
self.trackerData = {};
self.peers = {};
self.peerCount = 0;
self.wires = {};
self.connectQueue = [];
self.haveStack = [];
self.bitfieldDL = torrent.bitfieldDL || "00";
self.bitfield = (!torrent.pieces) ? null : new binaryBitfield(torrent.pieces.length, torrent.bitfieldDL);
self.tph = (!torrent.pieces) ? null : new TPH(torrent.files, torrent.length, torrent.pieceLength, torrent.pieces.length, torrent.lastPieceLength);
// Health Insurrance:
process.on("uncaughtException", function (err) {
self._debug(err);
});
// Incoming (TCP)
self.incomingPeers = createServer((socket) => {
self.createIncomingPeer(socket);
}).listen(0, () => {
self.port = self.incomingPeers.address().port;
self._debug("Listening on port:", self.port);
});
// Eventually add WS support
self.incomingWrtcPeers = wrtcCreateServer((socket) => {
self.createIncomingPeer(socket);
});
self.incomingWrtcPeers.listen(9001);
// Trackers (WSS/UDP)
self.torrent["announce"].forEach((tracker: string) => {
let pt = parse(tracker);
if (pt.protocol === "udp:") {
self.trackers[tracker] = Client.udp("scrape", pt.hostname, pt.port, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "wss:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 443, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
} else if (pt.protocol === "ws:") {
self.trackers[tracker] = Client.ws("scrape", pt.hostname, 80, self.port, self.torrent.infoHash, self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
}
self.trackers[tracker].on("announce", (interval, leechers, seeders, peers) => {
peers = peers.map((peer) => { return peer + ":" + ( (self.trackers[tracker].TYPE === "udp") ? "tcp" : "ws" ); });
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.trackers[tracker].on("error", () => {
self.trackerData[tracker + ":failure"] = true;
});
self.trackers[tracker].on("scrape", (seeders, completed, leechers, timeTillNextScrape) => {
self.trackerData[tracker + ":seeders"] = seeders;
self.trackerData[tracker + ":completed"] = completed;
self.trackerData[tracker + ":leechers"] = leechers;
self.trackerData[tracker + ":nextReq"] = timeTillNextScrape;
});
});
}
newConnectionRequests() {
const self = this;
// Determine how much room we have to add peers and connect.
while (self.peerCount < MAX_PEERS && (self.connectQueue.length)) {
let peer = self.connectQueue.shift().split(":");
self.createPeer(Number(peer[1]), peer[0], peer[2]);
}
}
createIncomingPeer(socket) {
const self = this;
let host = (socket.remoteAddress) ? socket.remoteAddress : socket.host,
port = (socket.remotePort) ? socket.remotePort : socket.port,
family = (socket.remoteFamily) ? socket.remoteFamily : socket.family,
wire = self.wires[host] = new Wire(self.torrent.infoHash, self.peerID);
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family, wire, socket, bitfield: "00", position: 0, piece: (-1), mode: 2, activeCount: 0 };
socket.pipe(wire).pipe(socket);
// TODO: SET BITFIELDDL DURING DOWNLOAD
wire.on("handshake", (infoHash: Buffer, peerID: string) => {
if (self.torrent.infoHash !== infoHash.toString("hex"))
return;
// Send handshake, metadata handshake, and bitfield.
wire.sendHandshake();
wire.sendBitfield(self.bitfieldDL);
});
wire.on("request", () => {
if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) {
let request = wire.inRequests.shift();
self.tph.prepareUpload(request.index, request.begin, request.length, (piece: Buffer) => {
process.nextTick(() => {
wire.sendPiece(piece);
});
});
}
wire.reqBusy = false;
}
});
wire.on("have", (pieceIndex: number) => {
// TODO: If new piece and not a seeder, switch to download phase and grab
});
self.peers[host + port].socket.on("close", () => {
self._debug("the socket decided to leave");
// Destroy the wire and delete the Object
self.peers[host + port] = null;
delete self.peers[host + port];
});
}
createPeer(port: number, host: string, type: string) {
const self = this;
self._debug("Create new peer");
self.peerCount++;
// Create the peer (MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata)
self.peers[host + port] = { port, family: "ipv4", wire: new Wire(self.torrent.infoHash, self.peerID), socket: null, bitfield: "00", position: 0, piece: (-1), mode: 0, activeCount: 0 };
if (type === "tcp")
self.peers[host + port].socket = connect(port, host);
else if (type === "ws")
self.peers[host + port].socket = wrtcConnect(port, host);
self.peers[host + port].socket.once("connect", () => {
self.peers[host + port]["socket"].pipe(self.peers[host + port].wire).pipe(self.peers[host + port]["socket"]);
self.peers[host + port].wire.sendHandshake();
});
self.peers[host + port].socket.on("error", (err) => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
self.peers[host + port].wire.closeConnection();
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.newConnectionRequests();
});
self.peers[host + port].socket.on("close", () => {
// TODO: if the peer was uploading but didn't finish, let's unset that bit
// Destroy the wire and delete the Object
if (self.peers[host + port].socket)
self.peers[host + port].socket.destroy();
delete self.peers[host + port];
self.peerCount--;
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("metadata", (torrent) => {
self._debug("Incoming metadata");
// Add the data to our torrent
extend(self.torrent, torrent);
// Prepare bitfield, files, and block handler
self.bitfield = new binaryBitfield(self.torrent.pieces.length, self.torrent.bitfieldDL);
self.manageFiles();
self.tph = new TPH(self.torrent.files, self.torrent.length, self.torrent.pieceLength, self.torrent.pieces.length, self.torrent.lastPieceLength);
// Convert all peers who are currently in meta_data mode to download mode
self._debug("Download phase");
self.downloadPhase(); // (from mode: 3, to: 1)
});
self.peers[host + port]["wire"].on("pex_added", (peers) => {
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
self.newConnectionRequests();
});
self.peers[host + port]["wire"].on("bitfield", (payload) => {
self._debug("peer's bitfield");
// Add the bitfield to the host+port
self.peers[host + port].bitfield = payload;
// Check that we have a connection:
if (self.peers[host + port]["wire"].isChoked)
self.peers[host + port]["wire"].sendInterested();
// Fetch some data if torrent. Otherwise ut_metadata (magnet)
if (self.torrent.pieces) {
self.peers[host + port].mode = 1;
self.fetchNewPiece(self.peers[host + port]); // Get some blocks!
} else {
self.peers[host + port].mode = 3;
self.peers[host + port]["wire"].metaDataRequest(); // Get metadata
}
});
self.peers[host + port]["wire"].on("have", (payload) => {
if (!self.bitfield)
return;
// UPDATE bitfield here
self.peers[host + port].bitfield = self.bitfield.onHave(payload, self.peers[host + port].bitfield);
// IF we are already sending a request and recieving a piece... hold your horses
let busy = self.peers[host + port]["wire"].isBusy();
// Additionally, if we don't get have torrent data or we have already finished the projet, ignore.
if (!busy && !self.finished && self.torrent.pieces.length) {
self.peers[host + port]["wire"].setBusy();
self.fetchNewPiece(self.peers[host + port]);
}
});
self.peers[host + port]["wire"].on("finished_piece", (index: number, block: Buffer, hash: Hash) => {
self._debug("finished piece");
self._debug("peerCount: ", self.peerCount);
let speed = 0;
for (let p in self.peers) {
speed += self.peers[p]["wire"].downloadSpeed();
}
// Check the hash
let blockHash = hash.digest("hex");
let percent = 0;
if (blockHash === self.torrent.pieces[index]) {
// Update downloaded:
self.torrent.downloaded += block.length;
self.torrent.left -= block.length;
// Place the buffer in its proper home
self.tph.saveBlock(self.peers[host + port].position, block);
// Check the percent of downloaded
percent = self.bitfield.setDownloaded(self.peers[host + port].piece);
// Emit up.
// self.emit('finished_piece', percent, );
} else |
self._debug("index downloaded: ", index);
self._debug("percent: ", percent);
if (percent === 1) {
self.finished = true;
self.finish();
self.cleanupSeeders();
} else {
// Start a new request sequence
process.nextTick(() => {
self.fetchNewPiece(self.peers[host + port]);
});
}
});
}
fetchNewPiece(peer) {
const self = this;
self.bitfield.findNewPieces(peer.bitfield, (result, downloading, which) => {
if (which !== (-1)) {
// Set the peers piece number and index of piece
peer.piece = which;
peer.position = self.tph.pieceIndex(which);
// Prepare a request for the pieces
self.tph.prepareRequest(which, (buf, count) => {
// Send to wire.
this._debug(`send ${count} piece request(s)`);
peer["wire"].sendRequest(buf, count);
});
} else {
// A have might be sent instead...
peer["wire"].unsetBusy();
}
});
}
// MODES: 0 - handshake; 1 - downloading; 2 - uploading; 3 - metadata
downloadPhase() {
const self = this;
for (let host in self.peers) {
// Convert metadata peers to downloaders:
if (self.peers[host].mode === 3) {
// Kill the metadata instance
self.peers[host]["wire"].removeMeta();
}
// Change the mode
self.peers[host].mode = 1;
// Fetch new pieces
self.fetchNewPiece(self.peers[host]);
}
}
finish() {
const self = this;
self._debug("DONE");
// for (let tracker in self.trackers) {
// if (!self.trackers[tracker + ":failure"])
// self.trackers[tracker].completed(self.torrent.left, self.torrent.uploaded, self.torrent.downloaded);
// }
}
cleanupSeeders() {
const self = this;
for (let host in self.peers) {
if ( self.bitfield.isSeeder(self.peers[host].bitfield) ) {
self.peers[host].wire.closeConnection();
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
}
cleanupAll() {
const self = this;
for (let host in self.peers) {
self.peers[host].socket.destroy();
delete self.peers[host];
}
}
manageFiles() {
this.torrent["files"] = this.torrent["files"].map((file) => {
// TODO: Setup the proper location to download
let downloadDirectory = "Downloads";
let folders = __dirname + "/" + downloadDirectory + "/" + file.path;
let f = folders.split("/");
let fileName = f.splice(-1);
folders = f.join("/");
mkdirp(folders, function (err) {
if (err) console.error(err);
else fs.writeFileSync(folders + "/" + fileName, new Buffer(file.length));
});
file.path = folders + "/" + fileName;
return file;
});
}
_debug = (...args: any[]) => {
args[0] = "[" + this._debugId + "] " + args[0];
debug.apply(null, args);
}
}
export default TorrentHandler;
| {
self._debug("failed hash");
// Remove piece and try again
self.bitfield.set(self.peers[host + port].piece, false);
} | conditional_block |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods tested here might raise
# NotImplementedError. This is perfectly acceptable behavior for the backend
# in question, but the tests need to handle this without failing. Ideally we'd
# skip these tests, but until #4788 is done we'll just ignore them.
#
# The easiest way to accomplish this is to decorate every test case with a
# wrapper that ignores the exception.
#
# The metaclass is just for fun.
#
def | (func):
def _inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotImplementedError:
return None
update_wrapper(_inner, func)
return _inner
class IgnoreNotimplementedError(type):
def __new__(cls, name, bases, attrs):
for k,v in attrs.items():
if k.startswith('test'):
attrs[k] = ignore_not_implemented(v)
return type.__new__(cls, name, bases, attrs)
class IntrospectionTests(six.with_metaclass(IgnoreNotimplementedError, TestCase)):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertTrue(Reporter._meta.db_table in tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assertTrue(Article._meta.db_table in tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertTrue('django_ixn_testcase_table' not in tl,
"django_table_names() returned a non-Django table")
def test_django_table_names_retval_type(self):
# Ticket #15216
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter]))
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual([r[0] for r in desc],
[f.column for f in Reporter._meta.fields])
def test_get_table_description_types(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[datatype(r[1], r) for r in desc],
['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
)
# Oracle forces null=True under the hood in some cases (see
# https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)
# so its idea about null_ok in cursor.description is different from ours.
@skipIfDBFeature('interprets_empty_strings_as_nulls')
def test_get_table_description_nullable(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[r[6] for r in desc],
[False, False, False, False, True]
)
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature('has_real_datatype')
def test_postgresql_real_type(self):
cursor = connection.cursor()
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
cursor.execute('DROP TABLE django_ixn_real_test_table;')
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
def test_get_relations(self):
cursor = connection.cursor()
relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
# Older versions of MySQL don't have the chops to report on this stuff,
# so just skip it if no relations come back. If they do, though, we
# should test that the response is correct.
if relations:
# That's {field_index: (field_index_other_table, other_table)}
self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = connection.cursor()
primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
self.assertEqual(primary_key_column, 'id')
def test_get_indexes(self):
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
def test_get_indexes_multicol(self):
"""
Test that multicolumn indexes are not included in the introspection
results.
"""
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
self.assertNotIn('first_name', indexes)
self.assertIn('id', indexes)
def datatype(dbtype, description):
"""Helper to convert a data type into a string."""
dt = connection.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt
| ignore_not_implemented | identifier_name |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods tested here might raise
# NotImplementedError. This is perfectly acceptable behavior for the backend
# in question, but the tests need to handle this without failing. Ideally we'd
# skip these tests, but until #4788 is done we'll just ignore them.
#
# The easiest way to accomplish this is to decorate every test case with a
# wrapper that ignores the exception.
#
# The metaclass is just for fun.
#
def ignore_not_implemented(func):
def _inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotImplementedError:
return None
update_wrapper(_inner, func)
return _inner
class IgnoreNotimplementedError(type):
def __new__(cls, name, bases, attrs):
for k,v in attrs.items():
if k.startswith('test'):
attrs[k] = ignore_not_implemented(v)
return type.__new__(cls, name, bases, attrs)
class IntrospectionTests(six.with_metaclass(IgnoreNotimplementedError, TestCase)):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertTrue(Reporter._meta.db_table in tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assertTrue(Article._meta.db_table in tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertTrue('django_ixn_testcase_table' not in tl,
"django_table_names() returned a non-Django table")
def test_django_table_names_retval_type(self):
# Ticket #15216
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter]))
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual([r[0] for r in desc],
[f.column for f in Reporter._meta.fields])
def test_get_table_description_types(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[datatype(r[1], r) for r in desc],
['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
)
# Oracle forces null=True under the hood in some cases (see
# https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)
# so its idea about null_ok in cursor.description is different from ours.
@skipIfDBFeature('interprets_empty_strings_as_nulls')
def test_get_table_description_nullable(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[r[6] for r in desc],
[False, False, False, False, True]
)
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature('has_real_datatype')
def test_postgresql_real_type(self):
cursor = connection.cursor()
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
cursor.execute('DROP TABLE django_ixn_real_test_table;')
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
def test_get_relations(self):
cursor = connection.cursor()
relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
# Older versions of MySQL don't have the chops to report on this stuff,
# so just skip it if no relations come back. If they do, though, we
# should test that the response is correct.
if relations:
# That's {field_index: (field_index_other_table, other_table)}
|
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = connection.cursor()
primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
self.assertEqual(primary_key_column, 'id')
def test_get_indexes(self):
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
def test_get_indexes_multicol(self):
"""
Test that multicolumn indexes are not included in the introspection
results.
"""
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
self.assertNotIn('first_name', indexes)
self.assertIn('id', indexes)
def datatype(dbtype, description):
"""Helper to convert a data type into a string."""
dt = connection.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt
| self.assertEqual(relations, {3: (0, Reporter._meta.db_table)}) | conditional_block |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods tested here might raise
# NotImplementedError. This is perfectly acceptable behavior for the backend
# in question, but the tests need to handle this without failing. Ideally we'd
# skip these tests, but until #4788 is done we'll just ignore them.
#
# The easiest way to accomplish this is to decorate every test case with a
# wrapper that ignores the exception.
#
# The metaclass is just for fun.
#
def ignore_not_implemented(func):
def _inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotImplementedError:
return None
update_wrapper(_inner, func)
return _inner
class IgnoreNotimplementedError(type):
def __new__(cls, name, bases, attrs):
for k,v in attrs.items():
if k.startswith('test'):
attrs[k] = ignore_not_implemented(v)
return type.__new__(cls, name, bases, attrs)
class IntrospectionTests(six.with_metaclass(IgnoreNotimplementedError, TestCase)):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertTrue(Reporter._meta.db_table in tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assertTrue(Article._meta.db_table in tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertTrue('django_ixn_testcase_table' not in tl,
"django_table_names() returned a non-Django table")
def test_django_table_names_retval_type(self):
# Ticket #15216
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_installed_models(self):
|
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual([r[0] for r in desc],
[f.column for f in Reporter._meta.fields])
def test_get_table_description_types(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[datatype(r[1], r) for r in desc],
['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
)
# Oracle forces null=True under the hood in some cases (see
# https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)
# so its idea about null_ok in cursor.description is different from ours.
@skipIfDBFeature('interprets_empty_strings_as_nulls')
def test_get_table_description_nullable(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[r[6] for r in desc],
[False, False, False, False, True]
)
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature('has_real_datatype')
def test_postgresql_real_type(self):
cursor = connection.cursor()
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
cursor.execute('DROP TABLE django_ixn_real_test_table;')
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
def test_get_relations(self):
cursor = connection.cursor()
relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
# Older versions of MySQL don't have the chops to report on this stuff,
# so just skip it if no relations come back. If they do, though, we
# should test that the response is correct.
if relations:
# That's {field_index: (field_index_other_table, other_table)}
self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = connection.cursor()
primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
self.assertEqual(primary_key_column, 'id')
def test_get_indexes(self):
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
def test_get_indexes_multicol(self):
"""
Test that multicolumn indexes are not included in the introspection
results.
"""
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
self.assertNotIn('first_name', indexes)
self.assertIn('id', indexes)
def datatype(dbtype, description):
"""Helper to convert a data type into a string."""
dt = connection.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt
| tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter])) | identifier_body |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods tested here might raise
# NotImplementedError. This is perfectly acceptable behavior for the backend
# in question, but the tests need to handle this without failing. Ideally we'd
# skip these tests, but until #4788 is done we'll just ignore them.
#
# The easiest way to accomplish this is to decorate every test case with a
# wrapper that ignores the exception.
#
# The metaclass is just for fun.
#
def ignore_not_implemented(func):
def _inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotImplementedError:
return None
update_wrapper(_inner, func)
return _inner
class IgnoreNotimplementedError(type):
def __new__(cls, name, bases, attrs):
for k,v in attrs.items():
if k.startswith('test'):
attrs[k] = ignore_not_implemented(v)
return type.__new__(cls, name, bases, attrs)
class IntrospectionTests(six.with_metaclass(IgnoreNotimplementedError, TestCase)):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertTrue(Reporter._meta.db_table in tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assertTrue(Article._meta.db_table in tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertTrue('django_ixn_testcase_table' not in tl,
"django_table_names() returned a non-Django table")
def test_django_table_names_retval_type(self):
# Ticket #15216
cursor = connection.cursor()
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter]))
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual([r[0] for r in desc],
[f.column for f in Reporter._meta.fields])
def test_get_table_description_types(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[datatype(r[1], r) for r in desc],
['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
)
# Oracle forces null=True under the hood in some cases (see
# https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)
# so its idea about null_ok in cursor.description is different from ours.
@skipIfDBFeature('interprets_empty_strings_as_nulls')
def test_get_table_description_nullable(self):
cursor = connection.cursor()
desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
self.assertEqual(
[r[6] for r in desc],
[False, False, False, False, True]
) | cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
cursor.execute('DROP TABLE django_ixn_real_test_table;')
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
def test_get_relations(self):
cursor = connection.cursor()
relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
# Older versions of MySQL don't have the chops to report on this stuff,
# so just skip it if no relations come back. If they do, though, we
# should test that the response is correct.
if relations:
# That's {field_index: (field_index_other_table, other_table)}
self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = connection.cursor()
primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
self.assertEqual(primary_key_column, 'id')
def test_get_indexes(self):
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
def test_get_indexes_multicol(self):
"""
Test that multicolumn indexes are not included in the introspection
results.
"""
cursor = connection.cursor()
indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
self.assertNotIn('first_name', indexes)
self.assertIn('id', indexes)
def datatype(dbtype, description):
"""Helper to convert a data type into a string."""
dt = connection.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt |
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature('has_real_datatype')
def test_postgresql_real_type(self):
cursor = connection.cursor() | random_line_split |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import traceback
bloom = BloomFilter(capacity=10000000, error_rate=0.001)
def get_pages(url):
try:
headers["User-Agent"] = random.choice(USER_AGENT_LIST)
r = requests.get(url,headers=headers)
if r.ok:
return r.content
else:
return None
except Exception as e:
log.error("PID:%d error:%s url:%s" % (os.getpid(),traceback.format_exc(),url))
return None
def parse_page(url, page, pattern):
page = etree.HTML(page.lower())
#page = etree.HTML(page.lower().decode('utf-8'))
ips = page.xpath(pattern["ip"])
ports = page.xpath(pattern["port"])
ty = page.xpath(pattern["type"])
if ips == None or ports == None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))
for i in range(len(ips)):
ret = {}
str = "%s:%s"
ret["ip_port"] = str%(ips[i].text,ports[i].text)
#print(url, ret["ip_port"], ty[i].text)
if ty[i].text.find("http") >= 0:
ret["type"] = 0
elif ty[i].text.find("https") >= 0:
ret["type"] = 1
else:
log.error("PID:%d page:%s can not get proxy type" % (os.getpid(), url))
yield ret
def get_and_check(url,pattern,q):
try:
page = get_pages(url)
if page == None:
return
lists = parse_page(url, page, pattern)
for ele in lists:
is_existed = ele["ip_port"] in bloom
#log.debug("PID:%d proxy worker ip %s is_existed %d" % (os.getpid(),ele["ip_port"],is_existed))
if is_existed == False:
try: | except Exception as e:
log.error("PID:%d bloom filter error:%s ip:%s" % (os.getpid(),e,ele["ip_port"]))
#url, ip, is_http, store_cookies, use_default_cookies, check_anonymity,
ele["name"] = "global"
ele["db"] = 0
ele["url"] = TEST_URL
ele["store_cookies"] = STORE_COOKIE
ele["use_default_cookies"] = USE_DEFAULT_COOKIE
ele["check_anonymity"] = True
q.put(ele)
except Exception as e:
log.error("PID:%d parse page error %s " % (os.getpid(), traceback.format_exc()))
def worker(pattern,q):
try:
num = pattern["page_range"]
for i in range(len(pattern["url"])):
index = pattern["url"][i].find("%d")
log.debug("PID:%d url:%s" % (os.getpid(), str(pattern)))
if index == -1:
get_and_check(pattern["url"][i],pattern,q)
time.sleep(10)
continue
for j in range(1,num+1):
url = pattern["url"][i] % j
get_and_check(url,pattern,q)
time.sleep(10)
except Exception as e:
log.error("PID:%d proxy url error:%s %s " % (os.getpid(),traceback.format_exc(), str(pattern)))
def db_zcount():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times = 0
while True:
try:
num = db_zcount()
log.debug("PID:%d db current ips %d------" % (os.getpid(),num))
while num > MIN_NUM:
time.sleep(REFRESH_WEB_SITE_TIMEER)
times += 1
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
t1 = time.time()
threads = []
for key,value in list(URL_PATTERN.items()):
thread = threading.Thread(target=worker,args=(value,q))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
t2 = time.time()
t = REFRESH_WEB_SITE_TIMEER - (t2 - t1)
times += 1
if t > 0:
time.sleep(t)
log.debug("PID:%d proxy sleep end------" % os.getpid())
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
except Exception as e:
log.error("PID:%d proxy error:%s" % (os.getpid(), traceback.format_exc()))
if __name__ == "__main__":
q = Queue()
get_proxy(q)
#worker(URL_PATTERN[URL_LIST[0]],q) | bloom.add(ele["ip_port"]) | random_line_split |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import traceback
bloom = BloomFilter(capacity=10000000, error_rate=0.001)
def get_pages(url):
try:
headers["User-Agent"] = random.choice(USER_AGENT_LIST)
r = requests.get(url,headers=headers)
if r.ok:
return r.content
else:
return None
except Exception as e:
log.error("PID:%d error:%s url:%s" % (os.getpid(),traceback.format_exc(),url))
return None
def parse_page(url, page, pattern):
page = etree.HTML(page.lower())
#page = etree.HTML(page.lower().decode('utf-8'))
ips = page.xpath(pattern["ip"])
ports = page.xpath(pattern["port"])
ty = page.xpath(pattern["type"])
if ips == None or ports == None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))
for i in range(len(ips)):
ret = {}
str = "%s:%s"
ret["ip_port"] = str%(ips[i].text,ports[i].text)
#print(url, ret["ip_port"], ty[i].text)
if ty[i].text.find("http") >= 0:
ret["type"] = 0
elif ty[i].text.find("https") >= 0:
ret["type"] = 1
else:
log.error("PID:%d page:%s can not get proxy type" % (os.getpid(), url))
yield ret
def get_and_check(url,pattern,q):
try:
page = get_pages(url)
if page == None:
return
lists = parse_page(url, page, pattern)
for ele in lists:
is_existed = ele["ip_port"] in bloom
#log.debug("PID:%d proxy worker ip %s is_existed %d" % (os.getpid(),ele["ip_port"],is_existed))
if is_existed == False:
try:
bloom.add(ele["ip_port"])
except Exception as e:
log.error("PID:%d bloom filter error:%s ip:%s" % (os.getpid(),e,ele["ip_port"]))
#url, ip, is_http, store_cookies, use_default_cookies, check_anonymity,
ele["name"] = "global"
ele["db"] = 0
ele["url"] = TEST_URL
ele["store_cookies"] = STORE_COOKIE
ele["use_default_cookies"] = USE_DEFAULT_COOKIE
ele["check_anonymity"] = True
q.put(ele)
except Exception as e:
log.error("PID:%d parse page error %s " % (os.getpid(), traceback.format_exc()))
def worker(pattern,q):
try:
num = pattern["page_range"]
for i in range(len(pattern["url"])):
index = pattern["url"][i].find("%d")
log.debug("PID:%d url:%s" % (os.getpid(), str(pattern)))
if index == -1:
get_and_check(pattern["url"][i],pattern,q)
time.sleep(10)
continue
for j in range(1,num+1):
url = pattern["url"][i] % j
get_and_check(url,pattern,q)
time.sleep(10)
except Exception as e:
log.error("PID:%d proxy url error:%s %s " % (os.getpid(),traceback.format_exc(), str(pattern)))
def | ():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times = 0
while True:
try:
num = db_zcount()
log.debug("PID:%d db current ips %d------" % (os.getpid(),num))
while num > MIN_NUM:
time.sleep(REFRESH_WEB_SITE_TIMEER)
times += 1
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
t1 = time.time()
threads = []
for key,value in list(URL_PATTERN.items()):
thread = threading.Thread(target=worker,args=(value,q))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
t2 = time.time()
t = REFRESH_WEB_SITE_TIMEER - (t2 - t1)
times += 1
if t > 0:
time.sleep(t)
log.debug("PID:%d proxy sleep end------" % os.getpid())
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
except Exception as e:
log.error("PID:%d proxy error:%s" % (os.getpid(), traceback.format_exc()))
if __name__ == "__main__":
q = Queue()
get_proxy(q)
#worker(URL_PATTERN[URL_LIST[0]],q)
| db_zcount | identifier_name |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import traceback
bloom = BloomFilter(capacity=10000000, error_rate=0.001)
def get_pages(url):
try:
headers["User-Agent"] = random.choice(USER_AGENT_LIST)
r = requests.get(url,headers=headers)
if r.ok:
return r.content
else:
return None
except Exception as e:
log.error("PID:%d error:%s url:%s" % (os.getpid(),traceback.format_exc(),url))
return None
def parse_page(url, page, pattern):
page = etree.HTML(page.lower())
#page = etree.HTML(page.lower().decode('utf-8'))
ips = page.xpath(pattern["ip"])
ports = page.xpath(pattern["port"])
ty = page.xpath(pattern["type"])
if ips == None or ports == None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))
for i in range(len(ips)):
ret = {}
str = "%s:%s"
ret["ip_port"] = str%(ips[i].text,ports[i].text)
#print(url, ret["ip_port"], ty[i].text)
if ty[i].text.find("http") >= 0:
ret["type"] = 0
elif ty[i].text.find("https") >= 0:
ret["type"] = 1
else:
log.error("PID:%d page:%s can not get proxy type" % (os.getpid(), url))
yield ret
def get_and_check(url,pattern,q):
try:
page = get_pages(url)
if page == None:
return
lists = parse_page(url, page, pattern)
for ele in lists:
is_existed = ele["ip_port"] in bloom
#log.debug("PID:%d proxy worker ip %s is_existed %d" % (os.getpid(),ele["ip_port"],is_existed))
if is_existed == False:
try:
bloom.add(ele["ip_port"])
except Exception as e:
log.error("PID:%d bloom filter error:%s ip:%s" % (os.getpid(),e,ele["ip_port"]))
#url, ip, is_http, store_cookies, use_default_cookies, check_anonymity,
ele["name"] = "global"
ele["db"] = 0
ele["url"] = TEST_URL
ele["store_cookies"] = STORE_COOKIE
ele["use_default_cookies"] = USE_DEFAULT_COOKIE
ele["check_anonymity"] = True
q.put(ele)
except Exception as e:
log.error("PID:%d parse page error %s " % (os.getpid(), traceback.format_exc()))
def worker(pattern,q):
try:
num = pattern["page_range"]
for i in range(len(pattern["url"])):
|
except Exception as e:
log.error("PID:%d proxy url error:%s %s " % (os.getpid(),traceback.format_exc(), str(pattern)))
def db_zcount():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times = 0
while True:
try:
num = db_zcount()
log.debug("PID:%d db current ips %d------" % (os.getpid(),num))
while num > MIN_NUM:
time.sleep(REFRESH_WEB_SITE_TIMEER)
times += 1
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
t1 = time.time()
threads = []
for key,value in list(URL_PATTERN.items()):
thread = threading.Thread(target=worker,args=(value,q))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
t2 = time.time()
t = REFRESH_WEB_SITE_TIMEER - (t2 - t1)
times += 1
if t > 0:
time.sleep(t)
log.debug("PID:%d proxy sleep end------" % os.getpid())
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
except Exception as e:
log.error("PID:%d proxy error:%s" % (os.getpid(), traceback.format_exc()))
if __name__ == "__main__":
q = Queue()
get_proxy(q)
#worker(URL_PATTERN[URL_LIST[0]],q)
| index = pattern["url"][i].find("%d")
log.debug("PID:%d url:%s" % (os.getpid(), str(pattern)))
if index == -1:
get_and_check(pattern["url"][i],pattern,q)
time.sleep(10)
continue
for j in range(1,num+1):
url = pattern["url"][i] % j
get_and_check(url,pattern,q)
time.sleep(10) | conditional_block |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import traceback
bloom = BloomFilter(capacity=10000000, error_rate=0.001)
def get_pages(url):
try:
headers["User-Agent"] = random.choice(USER_AGENT_LIST)
r = requests.get(url,headers=headers)
if r.ok:
return r.content
else:
return None
except Exception as e:
log.error("PID:%d error:%s url:%s" % (os.getpid(),traceback.format_exc(),url))
return None
def parse_page(url, page, pattern):
|
def get_and_check(url,pattern,q):
try:
page = get_pages(url)
if page == None:
return
lists = parse_page(url, page, pattern)
for ele in lists:
is_existed = ele["ip_port"] in bloom
#log.debug("PID:%d proxy worker ip %s is_existed %d" % (os.getpid(),ele["ip_port"],is_existed))
if is_existed == False:
try:
bloom.add(ele["ip_port"])
except Exception as e:
log.error("PID:%d bloom filter error:%s ip:%s" % (os.getpid(),e,ele["ip_port"]))
#url, ip, is_http, store_cookies, use_default_cookies, check_anonymity,
ele["name"] = "global"
ele["db"] = 0
ele["url"] = TEST_URL
ele["store_cookies"] = STORE_COOKIE
ele["use_default_cookies"] = USE_DEFAULT_COOKIE
ele["check_anonymity"] = True
q.put(ele)
except Exception as e:
log.error("PID:%d parse page error %s " % (os.getpid(), traceback.format_exc()))
def worker(pattern,q):
try:
num = pattern["page_range"]
for i in range(len(pattern["url"])):
index = pattern["url"][i].find("%d")
log.debug("PID:%d url:%s" % (os.getpid(), str(pattern)))
if index == -1:
get_and_check(pattern["url"][i],pattern,q)
time.sleep(10)
continue
for j in range(1,num+1):
url = pattern["url"][i] % j
get_and_check(url,pattern,q)
time.sleep(10)
except Exception as e:
log.error("PID:%d proxy url error:%s %s " % (os.getpid(),traceback.format_exc(), str(pattern)))
def db_zcount():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times = 0
while True:
try:
num = db_zcount()
log.debug("PID:%d db current ips %d------" % (os.getpid(),num))
while num > MIN_NUM:
time.sleep(REFRESH_WEB_SITE_TIMEER)
times += 1
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
t1 = time.time()
threads = []
for key,value in list(URL_PATTERN.items()):
thread = threading.Thread(target=worker,args=(value,q))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
t2 = time.time()
t = REFRESH_WEB_SITE_TIMEER - (t2 - t1)
times += 1
if t > 0:
time.sleep(t)
log.debug("PID:%d proxy sleep end------" % os.getpid())
if times == REFRESH_BF:
#bloom.clear()
bloom = BloomFilter(capacity=100000, error_rate=0.001)
times = 0
log.debug("PID:%d refresh bloom filter" % os.getpid())
except Exception as e:
log.error("PID:%d proxy error:%s" % (os.getpid(), traceback.format_exc()))
if __name__ == "__main__":
q = Queue()
get_proxy(q)
#worker(URL_PATTERN[URL_LIST[0]],q)
| page = etree.HTML(page.lower())
#page = etree.HTML(page.lower().decode('utf-8'))
ips = page.xpath(pattern["ip"])
ports = page.xpath(pattern["port"])
ty = page.xpath(pattern["type"])
if ips == None or ports == None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))
for i in range(len(ips)):
ret = {}
str = "%s:%s"
ret["ip_port"] = str%(ips[i].text,ports[i].text)
#print(url, ret["ip_port"], ty[i].text)
if ty[i].text.find("http") >= 0:
ret["type"] = 0
elif ty[i].text.find("https") >= 0:
ret["type"] = 1
else:
log.error("PID:%d page:%s can not get proxy type" % (os.getpid(), url))
yield ret | identifier_body |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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.
"""Facilities for automatically determining files' correct metadata.
"""
import os
import logging
import re
from beets import library, mediafile, config
from beets.util import sorted_walk, ancestry, displayable_path
# Parts of external interface.
from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa
from .match import tag_item, tag_album # noqa
from .match import Recommendation # noqa
# Global logger.
log = logging.getLogger('beets')
# Constants for directory walker.
MULTIDISC_MARKERS = (r'dis[ck]', r'cd') |
# Additional utilities for the main interface.
def albums_in_dir(path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files is an album.
"""
collapse_pat = collapse_paths = collapse_items = None
for root, dirs, files in sorted_walk(path,
ignore=config['ignore'].as_str_seq(),
logger=log):
# Get a list of items in the directory.
items = []
for filename in files:
try:
i = library.Item.from_path(os.path.join(root, filename))
except mediafile.FileTypeError:
pass
except mediafile.UnreadableFileError:
log.warn(u'unreadable file: {0}'.format(
displayable_path(filename))
)
except library.ReadError as exc:
log.error(u'error reading {0}: {1}'.format(
displayable_path(filename), exc
))
else:
items.append(i)
# If we're currently collapsing the constituent directories in a
# multi-disc album, check whether we should continue collapsing
# and add the current directory. If so, just add the directory
# and move on to the next directory. If not, stop collapsing.
if collapse_paths:
if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \
(collapse_pat and
collapse_pat.match(os.path.basename(root))):
# Still collapsing.
collapse_paths.append(root)
collapse_items += items
continue
else:
# Collapse finished. Yield the collapsed directory and
# proceed to process the current one.
if collapse_items:
yield collapse_paths, collapse_items
collapse_pat = collapse_paths = collapse_items = None
# Check whether this directory looks like the *first* directory
# in a multi-disc sequence. There are two indicators: the file
# is named like part of a multi-disc sequence (e.g., "Title Disc
# 1") or it contains no items but only directories that are
# named in this way.
start_collapsing = False
for marker in MULTIDISC_MARKERS:
marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I)
match = marker_pat.match(os.path.basename(root))
# Is this directory the root of a nested multi-disc album?
if dirs and not items:
# Check whether all subdirectories have the same prefix.
start_collapsing = True
subdir_pat = None
for subdir in dirs:
# The first directory dictates the pattern for
# the remaining directories.
if not subdir_pat:
match = marker_pat.match(subdir)
if match:
subdir_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
else:
start_collapsing = False
break
# Subsequent directories must match the pattern.
elif not subdir_pat.match(subdir):
start_collapsing = False
break
# If all subdirectories match, don't check other
# markers.
if start_collapsing:
break
# Is this directory the first in a flattened multi-disc album?
elif match:
start_collapsing = True
# Set the current pattern to match directories with the same
# prefix as this one, followed by a digit.
collapse_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
break
# If either of the above heuristics indicated that this is the
# beginning of a multi-disc album, initialize the collapsed
# directory and item lists and check the next directory.
if start_collapsing:
# Start collapsing; continue to the next iteration.
collapse_paths = [root]
collapse_items = items
continue
# If it's nonempty, yield it.
if items:
yield [root], items
# Clear out any unfinished collapse.
if collapse_paths and collapse_items:
yield collapse_paths, collapse_items
def apply_item_metadata(item, track_info):
"""Set an item's metadata from its matched TrackInfo object.
"""
item.artist = track_info.artist
item.artist_sort = track_info.artist_sort
item.artist_credit = track_info.artist_credit
item.title = track_info.title
item.mb_trackid = track_info.track_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
# At the moment, the other metadata is left intact (including album
# and track number). Perhaps these should be emptied?
def apply_metadata(album_info, mapping):
"""Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in mapping.iteritems():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist
else:
item.artist = album_info.artist
item.albumartist = album_info.artist
item.album = album_info.album
# Artist sort and credit names.
item.artist_sort = track_info.artist_sort or album_info.artist_sort
item.artist_credit = (track_info.artist_credit or
album_info.artist_credit)
item.albumartist_sort = album_info.artist_sort
item.albumartist_credit = album_info.artist_credit
# Release date.
for prefix in '', 'original_':
if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
# If we don't even have a year, apply nothing.
if suffix == 'year' and not value:
break
# Otherwise, set the fetched value (or 0 for the month
# and day if not available).
item[key] = value
# If we're using original release date for both fields,
# also set item.year = info.original_year, etc.
if config['original_date']:
item[suffix] = value
# Title.
item.title = track_info.title
if config['per_disc_numbering']:
item.track = track_info.medium_index or track_info.index
item.tracktotal = track_info.medium_total or len(album_info.tracks)
else:
item.track = track_info.index
item.tracktotal = len(album_info.tracks)
# Disc and disc count.
item.disc = track_info.medium
item.disctotal = album_info.mediums
# MusicBrainz IDs.
item.mb_trackid = track_info.track_id
item.mb_albumid = album_info.album_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
else:
item.mb_artistid = album_info.artist_id
item.mb_albumartistid = album_info.artist_id
item.mb_releasegroupid = album_info.releasegroup_id
# Compilation flag.
item.comp = album_info.va
# Miscellaneous metadata.
for field in ('albumtype',
'label',
'asin',
'catalognum',
'script',
'language',
'country',
'albumstatus',
'media',
'albumdisambig'):
value = getattr(album_info, field)
if value is not None:
item[field] = value
if track_info.disctitle is not None:
item.disctitle = track_info.disctitle | MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d'
| random_line_split |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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.
"""Facilities for automatically determining files' correct metadata.
"""
import os
import logging
import re
from beets import library, mediafile, config
from beets.util import sorted_walk, ancestry, displayable_path
# Parts of external interface.
from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa
from .match import tag_item, tag_album # noqa
from .match import Recommendation # noqa
# Global logger.
log = logging.getLogger('beets')
# Constants for directory walker.
MULTIDISC_MARKERS = (r'dis[ck]', r'cd')
MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d'
# Additional utilities for the main interface.
def albums_in_dir(path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files is an album.
"""
collapse_pat = collapse_paths = collapse_items = None
for root, dirs, files in sorted_walk(path,
ignore=config['ignore'].as_str_seq(),
logger=log):
# Get a list of items in the directory.
items = []
for filename in files:
try:
i = library.Item.from_path(os.path.join(root, filename))
except mediafile.FileTypeError:
pass
except mediafile.UnreadableFileError:
log.warn(u'unreadable file: {0}'.format(
displayable_path(filename))
)
except library.ReadError as exc:
log.error(u'error reading {0}: {1}'.format(
displayable_path(filename), exc
))
else:
items.append(i)
# If we're currently collapsing the constituent directories in a
# multi-disc album, check whether we should continue collapsing
# and add the current directory. If so, just add the directory
# and move on to the next directory. If not, stop collapsing.
if collapse_paths:
if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \
(collapse_pat and
collapse_pat.match(os.path.basename(root))):
# Still collapsing.
collapse_paths.append(root)
collapse_items += items
continue
else:
# Collapse finished. Yield the collapsed directory and
# proceed to process the current one.
if collapse_items:
yield collapse_paths, collapse_items
collapse_pat = collapse_paths = collapse_items = None
# Check whether this directory looks like the *first* directory
# in a multi-disc sequence. There are two indicators: the file
# is named like part of a multi-disc sequence (e.g., "Title Disc
# 1") or it contains no items but only directories that are
# named in this way.
start_collapsing = False
for marker in MULTIDISC_MARKERS:
marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I)
match = marker_pat.match(os.path.basename(root))
# Is this directory the root of a nested multi-disc album?
if dirs and not items:
# Check whether all subdirectories have the same prefix.
start_collapsing = True
subdir_pat = None
for subdir in dirs:
# The first directory dictates the pattern for
# the remaining directories.
if not subdir_pat:
match = marker_pat.match(subdir)
if match:
subdir_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
else:
start_collapsing = False
break
# Subsequent directories must match the pattern.
elif not subdir_pat.match(subdir):
start_collapsing = False
break
# If all subdirectories match, don't check other
# markers.
if start_collapsing:
break
# Is this directory the first in a flattened multi-disc album?
elif match:
start_collapsing = True
# Set the current pattern to match directories with the same
# prefix as this one, followed by a digit.
collapse_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
break
# If either of the above heuristics indicated that this is the
# beginning of a multi-disc album, initialize the collapsed
# directory and item lists and check the next directory.
if start_collapsing:
# Start collapsing; continue to the next iteration.
collapse_paths = [root]
collapse_items = items
continue
# If it's nonempty, yield it.
if items:
yield [root], items
# Clear out any unfinished collapse.
if collapse_paths and collapse_items:
yield collapse_paths, collapse_items
def apply_item_metadata(item, track_info):
"""Set an item's metadata from its matched TrackInfo object.
"""
item.artist = track_info.artist
item.artist_sort = track_info.artist_sort
item.artist_credit = track_info.artist_credit
item.title = track_info.title
item.mb_trackid = track_info.track_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
# At the moment, the other metadata is left intact (including album
# and track number). Perhaps these should be emptied?
def apply_metadata(album_info, mapping):
"""Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in mapping.iteritems():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist
else:
item.artist = album_info.artist
item.albumartist = album_info.artist
item.album = album_info.album
# Artist sort and credit names.
item.artist_sort = track_info.artist_sort or album_info.artist_sort
item.artist_credit = (track_info.artist_credit or
album_info.artist_credit)
item.albumartist_sort = album_info.artist_sort
item.albumartist_credit = album_info.artist_credit
# Release date.
for prefix in '', 'original_':
|
# Title.
item.title = track_info.title
if config['per_disc_numbering']:
item.track = track_info.medium_index or track_info.index
item.tracktotal = track_info.medium_total or len(album_info.tracks)
else:
item.track = track_info.index
item.tracktotal = len(album_info.tracks)
# Disc and disc count.
item.disc = track_info.medium
item.disctotal = album_info.mediums
# MusicBrainz IDs.
item.mb_trackid = track_info.track_id
item.mb_albumid = album_info.album_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
else:
item.mb_artistid = album_info.artist_id
item.mb_albumartistid = album_info.artist_id
item.mb_releasegroupid = album_info.releasegroup_id
# Compilation flag.
item.comp = album_info.va
# Miscellaneous metadata.
for field in ('albumtype',
'label',
'asin',
'catalognum',
'script',
'language',
'country',
'albumstatus',
'media',
'albumdisambig'):
value = getattr(album_info, field)
if value is not None:
item[field] = value
if track_info.disctitle is not None:
item.disctitle = track_info.disctitle
| if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
# If we don't even have a year, apply nothing.
if suffix == 'year' and not value:
break
# Otherwise, set the fetched value (or 0 for the month
# and day if not available).
item[key] = value
# If we're using original release date for both fields,
# also set item.year = info.original_year, etc.
if config['original_date']:
item[suffix] = value | conditional_block |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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.
"""Facilities for automatically determining files' correct metadata.
"""
import os
import logging
import re
from beets import library, mediafile, config
from beets.util import sorted_walk, ancestry, displayable_path
# Parts of external interface.
from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa
from .match import tag_item, tag_album # noqa
from .match import Recommendation # noqa
# Global logger.
log = logging.getLogger('beets')
# Constants for directory walker.
MULTIDISC_MARKERS = (r'dis[ck]', r'cd')
MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d'
# Additional utilities for the main interface.
def albums_in_dir(path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files is an album.
"""
collapse_pat = collapse_paths = collapse_items = None
for root, dirs, files in sorted_walk(path,
ignore=config['ignore'].as_str_seq(),
logger=log):
# Get a list of items in the directory.
items = []
for filename in files:
try:
i = library.Item.from_path(os.path.join(root, filename))
except mediafile.FileTypeError:
pass
except mediafile.UnreadableFileError:
log.warn(u'unreadable file: {0}'.format(
displayable_path(filename))
)
except library.ReadError as exc:
log.error(u'error reading {0}: {1}'.format(
displayable_path(filename), exc
))
else:
items.append(i)
# If we're currently collapsing the constituent directories in a
# multi-disc album, check whether we should continue collapsing
# and add the current directory. If so, just add the directory
# and move on to the next directory. If not, stop collapsing.
if collapse_paths:
if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \
(collapse_pat and
collapse_pat.match(os.path.basename(root))):
# Still collapsing.
collapse_paths.append(root)
collapse_items += items
continue
else:
# Collapse finished. Yield the collapsed directory and
# proceed to process the current one.
if collapse_items:
yield collapse_paths, collapse_items
collapse_pat = collapse_paths = collapse_items = None
# Check whether this directory looks like the *first* directory
# in a multi-disc sequence. There are two indicators: the file
# is named like part of a multi-disc sequence (e.g., "Title Disc
# 1") or it contains no items but only directories that are
# named in this way.
start_collapsing = False
for marker in MULTIDISC_MARKERS:
marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I)
match = marker_pat.match(os.path.basename(root))
# Is this directory the root of a nested multi-disc album?
if dirs and not items:
# Check whether all subdirectories have the same prefix.
start_collapsing = True
subdir_pat = None
for subdir in dirs:
# The first directory dictates the pattern for
# the remaining directories.
if not subdir_pat:
match = marker_pat.match(subdir)
if match:
subdir_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
else:
start_collapsing = False
break
# Subsequent directories must match the pattern.
elif not subdir_pat.match(subdir):
start_collapsing = False
break
# If all subdirectories match, don't check other
# markers.
if start_collapsing:
break
# Is this directory the first in a flattened multi-disc album?
elif match:
start_collapsing = True
# Set the current pattern to match directories with the same
# prefix as this one, followed by a digit.
collapse_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
break
# If either of the above heuristics indicated that this is the
# beginning of a multi-disc album, initialize the collapsed
# directory and item lists and check the next directory.
if start_collapsing:
# Start collapsing; continue to the next iteration.
collapse_paths = [root]
collapse_items = items
continue
# If it's nonempty, yield it.
if items:
yield [root], items
# Clear out any unfinished collapse.
if collapse_paths and collapse_items:
yield collapse_paths, collapse_items
def apply_item_metadata(item, track_info):
"""Set an item's metadata from its matched TrackInfo object.
"""
item.artist = track_info.artist
item.artist_sort = track_info.artist_sort
item.artist_credit = track_info.artist_credit
item.title = track_info.title
item.mb_trackid = track_info.track_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
# At the moment, the other metadata is left intact (including album
# and track number). Perhaps these should be emptied?
def apply_metadata(album_info, mapping):
| """Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in mapping.iteritems():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist
else:
item.artist = album_info.artist
item.albumartist = album_info.artist
item.album = album_info.album
# Artist sort and credit names.
item.artist_sort = track_info.artist_sort or album_info.artist_sort
item.artist_credit = (track_info.artist_credit or
album_info.artist_credit)
item.albumartist_sort = album_info.artist_sort
item.albumartist_credit = album_info.artist_credit
# Release date.
for prefix in '', 'original_':
if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
# If we don't even have a year, apply nothing.
if suffix == 'year' and not value:
break
# Otherwise, set the fetched value (or 0 for the month
# and day if not available).
item[key] = value
# If we're using original release date for both fields,
# also set item.year = info.original_year, etc.
if config['original_date']:
item[suffix] = value
# Title.
item.title = track_info.title
if config['per_disc_numbering']:
item.track = track_info.medium_index or track_info.index
item.tracktotal = track_info.medium_total or len(album_info.tracks)
else:
item.track = track_info.index
item.tracktotal = len(album_info.tracks)
# Disc and disc count.
item.disc = track_info.medium
item.disctotal = album_info.mediums
# MusicBrainz IDs.
item.mb_trackid = track_info.track_id
item.mb_albumid = album_info.album_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
else:
item.mb_artistid = album_info.artist_id
item.mb_albumartistid = album_info.artist_id
item.mb_releasegroupid = album_info.releasegroup_id
# Compilation flag.
item.comp = album_info.va
# Miscellaneous metadata.
for field in ('albumtype',
'label',
'asin',
'catalognum',
'script',
'language',
'country',
'albumstatus',
'media',
'albumdisambig'):
value = getattr(album_info, field)
if value is not None:
item[field] = value
if track_info.disctitle is not None:
item.disctitle = track_info.disctitle | identifier_body | |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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.
"""Facilities for automatically determining files' correct metadata.
"""
import os
import logging
import re
from beets import library, mediafile, config
from beets.util import sorted_walk, ancestry, displayable_path
# Parts of external interface.
from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa
from .match import tag_item, tag_album # noqa
from .match import Recommendation # noqa
# Global logger.
log = logging.getLogger('beets')
# Constants for directory walker.
MULTIDISC_MARKERS = (r'dis[ck]', r'cd')
MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d'
# Additional utilities for the main interface.
def | (path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files is an album.
"""
collapse_pat = collapse_paths = collapse_items = None
for root, dirs, files in sorted_walk(path,
ignore=config['ignore'].as_str_seq(),
logger=log):
# Get a list of items in the directory.
items = []
for filename in files:
try:
i = library.Item.from_path(os.path.join(root, filename))
except mediafile.FileTypeError:
pass
except mediafile.UnreadableFileError:
log.warn(u'unreadable file: {0}'.format(
displayable_path(filename))
)
except library.ReadError as exc:
log.error(u'error reading {0}: {1}'.format(
displayable_path(filename), exc
))
else:
items.append(i)
# If we're currently collapsing the constituent directories in a
# multi-disc album, check whether we should continue collapsing
# and add the current directory. If so, just add the directory
# and move on to the next directory. If not, stop collapsing.
if collapse_paths:
if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \
(collapse_pat and
collapse_pat.match(os.path.basename(root))):
# Still collapsing.
collapse_paths.append(root)
collapse_items += items
continue
else:
# Collapse finished. Yield the collapsed directory and
# proceed to process the current one.
if collapse_items:
yield collapse_paths, collapse_items
collapse_pat = collapse_paths = collapse_items = None
# Check whether this directory looks like the *first* directory
# in a multi-disc sequence. There are two indicators: the file
# is named like part of a multi-disc sequence (e.g., "Title Disc
# 1") or it contains no items but only directories that are
# named in this way.
start_collapsing = False
for marker in MULTIDISC_MARKERS:
marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I)
match = marker_pat.match(os.path.basename(root))
# Is this directory the root of a nested multi-disc album?
if dirs and not items:
# Check whether all subdirectories have the same prefix.
start_collapsing = True
subdir_pat = None
for subdir in dirs:
# The first directory dictates the pattern for
# the remaining directories.
if not subdir_pat:
match = marker_pat.match(subdir)
if match:
subdir_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
else:
start_collapsing = False
break
# Subsequent directories must match the pattern.
elif not subdir_pat.match(subdir):
start_collapsing = False
break
# If all subdirectories match, don't check other
# markers.
if start_collapsing:
break
# Is this directory the first in a flattened multi-disc album?
elif match:
start_collapsing = True
# Set the current pattern to match directories with the same
# prefix as this one, followed by a digit.
collapse_pat = re.compile(
r'^%s\d' % re.escape(match.group(1)), re.I
)
break
# If either of the above heuristics indicated that this is the
# beginning of a multi-disc album, initialize the collapsed
# directory and item lists and check the next directory.
if start_collapsing:
# Start collapsing; continue to the next iteration.
collapse_paths = [root]
collapse_items = items
continue
# If it's nonempty, yield it.
if items:
yield [root], items
# Clear out any unfinished collapse.
if collapse_paths and collapse_items:
yield collapse_paths, collapse_items
def apply_item_metadata(item, track_info):
"""Set an item's metadata from its matched TrackInfo object.
"""
item.artist = track_info.artist
item.artist_sort = track_info.artist_sort
item.artist_credit = track_info.artist_credit
item.title = track_info.title
item.mb_trackid = track_info.track_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
# At the moment, the other metadata is left intact (including album
# and track number). Perhaps these should be emptied?
def apply_metadata(album_info, mapping):
"""Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in mapping.iteritems():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist
else:
item.artist = album_info.artist
item.albumartist = album_info.artist
item.album = album_info.album
# Artist sort and credit names.
item.artist_sort = track_info.artist_sort or album_info.artist_sort
item.artist_credit = (track_info.artist_credit or
album_info.artist_credit)
item.albumartist_sort = album_info.artist_sort
item.albumartist_credit = album_info.artist_credit
# Release date.
for prefix in '', 'original_':
if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
# If we don't even have a year, apply nothing.
if suffix == 'year' and not value:
break
# Otherwise, set the fetched value (or 0 for the month
# and day if not available).
item[key] = value
# If we're using original release date for both fields,
# also set item.year = info.original_year, etc.
if config['original_date']:
item[suffix] = value
# Title.
item.title = track_info.title
if config['per_disc_numbering']:
item.track = track_info.medium_index or track_info.index
item.tracktotal = track_info.medium_total or len(album_info.tracks)
else:
item.track = track_info.index
item.tracktotal = len(album_info.tracks)
# Disc and disc count.
item.disc = track_info.medium
item.disctotal = album_info.mediums
# MusicBrainz IDs.
item.mb_trackid = track_info.track_id
item.mb_albumid = album_info.album_id
if track_info.artist_id:
item.mb_artistid = track_info.artist_id
else:
item.mb_artistid = album_info.artist_id
item.mb_albumartistid = album_info.artist_id
item.mb_releasegroupid = album_info.releasegroup_id
# Compilation flag.
item.comp = album_info.va
# Miscellaneous metadata.
for field in ('albumtype',
'label',
'asin',
'catalognum',
'script',
'language',
'country',
'albumstatus',
'media',
'albumdisambig'):
value = getattr(album_info, field)
if value is not None:
item[field] = value
if track_info.disctitle is not None:
item.disctitle = track_info.disctitle
| albums_in_dir | identifier_name |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger = Messenger(self.config)
self.sms_service = SMSService()
def send_initial_greeting(self):
"""
Sends the initial SMS to new* patients at a pre-defined client time.
*New patients are those that have recently been added
to the clients database, which the service does not know.
Note: this is REQUIRED otherwise 'respond' & other services do not
function as database errors are thrown (understandably).
"""
from datetime import datetime
current_time = str(datetime.now().time())[0:5]
# Send the message to new patients at the defined time.
if current_time == self.config['initialQuestion']['time']:
for number in self.__new_patients():
message = self.messenger.initial_message()
self.sms_service.send(number, message)
self.__create_new_patient(number)
self.__save_message(number, message, 'sent')
def respond(self, patient_response):
"""
Respond to new SMS when it is received via a POST request.
Args:
patient_message (dict): Contains the number, and message sent to
the service by a patient.
Returns:
response (XML): twilio formatted response.
"""
number = patient_response['number']
patient_message = patient_response['message']
# Generate a reflective summary based on the patient's response.
summary = self.messenger.summary(patient_message)
# TODO: Fix this with the system set time (i.e. UTC)
midnight = int(datetime.today().strftime("%s")) - 24*60*60
# The number of questions sent since last night.
_questions = db.session.query(models.Message).filter(
models.Message.mobile == number,
models.Message.status == 'sent',
models.Message.timestamp >= midnight).all()
all_sent = [item.message for item in _questions]
# The number of OEQ sent since last night.
num_oeq = len([i for i in self.config['questions'] if i in all_sent])
print 'Number OEQ sent since last night was: %s' % str(num_oeq)
response = None
# Do not send a response if initial daily conversation not started.
if num_oeq >= 1:
print 'The last sms sent was: %s' % all_sent[-1]
if all_sent[-1] in self.config['questions']:
print 'Last message sent was an OEQ. Sending a RS to patient.'
response = summary
else:
print 'Inside the else..'
if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT
print 'Inside the else... in the if...'
if self.config['endQuestion'] not in all_sent:
print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion']
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
return self.sms_service.reply(response)
else:
print 'No response was created.'
return '' # Prevents a 500 error code returned to POST.
def send_initial_question_to_all(self):
"""
Sends a question to all patients at a pre-defined day and time.
"""
known_patients = [item.mobile for item in
db.session.query(models.Patient.mobile).all()]
from datetime import datetime
print "Checking to see if open-ended question should be sent."
isDay = datetime.now().strftime("%A") in self.config["daysToSend"]
isTime = str(datetime.now().time())[0:5] == self.config["sendTime"]
if isDay and isTime:
for number in known_patients:
message = self.__select_question(number)
print "OEQ (%s) to patient (%s)." % (message, number)
self.__save_message(number, message, 'sent')
self.sms_service.send(number, message)
def __select_question(self, number):
"""
Select a client-defined open-ended question that has not been previously
selected at random. If all have been sent then select one at random.
Args:
number (str): The mobile number of the patient.
Returns:
str: An open-ended question to ask the patient.
"""
questions = self.config['questions']
sent_questions = [item.message for item in db.session.query(
models.Message).filter(models.Message.mobile == number).all()]
unsent_questions = list(set(questions).difference(sent_questions))
# TODO: Select most important question based on client's situation
import random
if unsent_questions:
print "Sending a message that HAS NOT been previously sent."
message = random.choice(unsent_questions) | def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of the user-defined config file.
"""
import json
from flask import current_app
config_file = current_app.config['PROJECT_ROOT'] + '/sris/config/' + \
current_app.config['CLIENT_NAME'] + '.json'
with open(config_file) as json_settings:
return json.load(json_settings)
def __new_patients(self):
"""
Checks to see if any new patients have been added to the client DB.
Returns:
list: Mobile numbers the client knows & the service does not.
"""
# ALL numbers obtained from the client.
client_numbers = db.session.query(models.Patient.mobile).all()
# The numbers the service has to date.
service_numbers = db.session.query(models.User.mobile).all()
# The numbers the client has, but the service does not.
numbers = set(client_numbers).difference(service_numbers)
print 'There was %s new patients' % str(len(numbers))
# Convert SQLAlchemy KeyedTuple to ordinary list.
return [item.mobile for item in numbers]
def __create_new_patient(self, number):
"""
Adds the patient to the service database.
Args:
number (str): The mobile number of the patient.
"""
db.session.add(models.User(mobile=number))
db.session.commit()
def __save_message(self, number, message, status):
"""
Save the SMS message (sent or received) to the service database.
Args:
number (str): The mobile number of the patient.
message (str): The SMS message content.
status (str): The status of the message, e.g. 'sent' or 'received'.
"""
db.session.add(models.Message(mobile=number, message=message,
status=status))
db.session.commit() | else:
print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message
| random_line_split |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger = Messenger(self.config)
self.sms_service = SMSService()
def send_initial_greeting(self):
"""
Sends the initial SMS to new* patients at a pre-defined client time.
*New patients are those that have recently been added
to the clients database, which the service does not know.
Note: this is REQUIRED otherwise 'respond' & other services do not
function as database errors are thrown (understandably).
"""
from datetime import datetime
current_time = str(datetime.now().time())[0:5]
# Send the message to new patients at the defined time.
if current_time == self.config['initialQuestion']['time']:
for number in self.__new_patients():
message = self.messenger.initial_message()
self.sms_service.send(number, message)
self.__create_new_patient(number)
self.__save_message(number, message, 'sent')
def respond(self, patient_response):
"""
Respond to new SMS when it is received via a POST request.
Args:
patient_message (dict): Contains the number, and message sent to
the service by a patient.
Returns:
response (XML): twilio formatted response.
"""
number = patient_response['number']
patient_message = patient_response['message']
# Generate a reflective summary based on the patient's response.
summary = self.messenger.summary(patient_message)
# TODO: Fix this with the system set time (i.e. UTC)
midnight = int(datetime.today().strftime("%s")) - 24*60*60
# The number of questions sent since last night.
_questions = db.session.query(models.Message).filter(
models.Message.mobile == number,
models.Message.status == 'sent',
models.Message.timestamp >= midnight).all()
all_sent = [item.message for item in _questions]
# The number of OEQ sent since last night.
num_oeq = len([i for i in self.config['questions'] if i in all_sent])
print 'Number OEQ sent since last night was: %s' % str(num_oeq)
response = None
# Do not send a response if initial daily conversation not started.
if num_oeq >= 1:
print 'The last sms sent was: %s' % all_sent[-1]
if all_sent[-1] in self.config['questions']:
print 'Last message sent was an OEQ. Sending a RS to patient.'
response = summary
else:
print 'Inside the else..'
if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT
print 'Inside the else... in the if...'
if self.config['endQuestion'] not in all_sent:
print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion']
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
return self.sms_service.reply(response)
else:
print 'No response was created.'
return '' # Prevents a 500 error code returned to POST.
def send_initial_question_to_all(self):
"""
Sends a question to all patients at a pre-defined day and time.
"""
known_patients = [item.mobile for item in
db.session.query(models.Patient.mobile).all()]
from datetime import datetime
print "Checking to see if open-ended question should be sent."
isDay = datetime.now().strftime("%A") in self.config["daysToSend"]
isTime = str(datetime.now().time())[0:5] == self.config["sendTime"]
if isDay and isTime:
for number in known_patients:
message = self.__select_question(number)
print "OEQ (%s) to patient (%s)." % (message, number)
self.__save_message(number, message, 'sent')
self.sms_service.send(number, message)
def __select_question(self, number):
|
def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of the user-defined config file.
"""
import json
from flask import current_app
config_file = current_app.config['PROJECT_ROOT'] + '/sris/config/' + \
current_app.config['CLIENT_NAME'] + '.json'
with open(config_file) as json_settings:
return json.load(json_settings)
def __new_patients(self):
"""
Checks to see if any new patients have been added to the client DB.
Returns:
list: Mobile numbers the client knows & the service does not.
"""
# ALL numbers obtained from the client.
client_numbers = db.session.query(models.Patient.mobile).all()
# The numbers the service has to date.
service_numbers = db.session.query(models.User.mobile).all()
# The numbers the client has, but the service does not.
numbers = set(client_numbers).difference(service_numbers)
print 'There was %s new patients' % str(len(numbers))
# Convert SQLAlchemy KeyedTuple to ordinary list.
return [item.mobile for item in numbers]
def __create_new_patient(self, number):
"""
Adds the patient to the service database.
Args:
number (str): The mobile number of the patient.
"""
db.session.add(models.User(mobile=number))
db.session.commit()
def __save_message(self, number, message, status):
"""
Save the SMS message (sent or received) to the service database.
Args:
number (str): The mobile number of the patient.
message (str): The SMS message content.
status (str): The status of the message, e.g. 'sent' or 'received'.
"""
db.session.add(models.Message(mobile=number, message=message,
status=status))
db.session.commit()
| """
Select a client-defined open-ended question that has not been previously
selected at random. If all have been sent then select one at random.
Args:
number (str): The mobile number of the patient.
Returns:
str: An open-ended question to ask the patient.
"""
questions = self.config['questions']
sent_questions = [item.message for item in db.session.query(
models.Message).filter(models.Message.mobile == number).all()]
unsent_questions = list(set(questions).difference(sent_questions))
# TODO: Select most important question based on client's situation
import random
if unsent_questions:
print "Sending a message that HAS NOT been previously sent."
message = random.choice(unsent_questions)
else:
print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message | identifier_body |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger = Messenger(self.config)
self.sms_service = SMSService()
def send_initial_greeting(self):
"""
Sends the initial SMS to new* patients at a pre-defined client time.
*New patients are those that have recently been added
to the clients database, which the service does not know.
Note: this is REQUIRED otherwise 'respond' & other services do not
function as database errors are thrown (understandably).
"""
from datetime import datetime
current_time = str(datetime.now().time())[0:5]
# Send the message to new patients at the defined time.
if current_time == self.config['initialQuestion']['time']:
for number in self.__new_patients():
message = self.messenger.initial_message()
self.sms_service.send(number, message)
self.__create_new_patient(number)
self.__save_message(number, message, 'sent')
def respond(self, patient_response):
"""
Respond to new SMS when it is received via a POST request.
Args:
patient_message (dict): Contains the number, and message sent to
the service by a patient.
Returns:
response (XML): twilio formatted response.
"""
number = patient_response['number']
patient_message = patient_response['message']
# Generate a reflective summary based on the patient's response.
summary = self.messenger.summary(patient_message)
# TODO: Fix this with the system set time (i.e. UTC)
midnight = int(datetime.today().strftime("%s")) - 24*60*60
# The number of questions sent since last night.
_questions = db.session.query(models.Message).filter(
models.Message.mobile == number,
models.Message.status == 'sent',
models.Message.timestamp >= midnight).all()
all_sent = [item.message for item in _questions]
# The number of OEQ sent since last night.
num_oeq = len([i for i in self.config['questions'] if i in all_sent])
print 'Number OEQ sent since last night was: %s' % str(num_oeq)
response = None
# Do not send a response if initial daily conversation not started.
if num_oeq >= 1:
print 'The last sms sent was: %s' % all_sent[-1]
if all_sent[-1] in self.config['questions']:
print 'Last message sent was an OEQ. Sending a RS to patient.'
response = summary
else:
print 'Inside the else..'
if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT
print 'Inside the else... in the if...'
if self.config['endQuestion'] not in all_sent:
print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion']
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
return self.sms_service.reply(response)
else:
print 'No response was created.'
return '' # Prevents a 500 error code returned to POST.
def send_initial_question_to_all(self):
"""
Sends a question to all patients at a pre-defined day and time.
"""
known_patients = [item.mobile for item in
db.session.query(models.Patient.mobile).all()]
from datetime import datetime
print "Checking to see if open-ended question should be sent."
isDay = datetime.now().strftime("%A") in self.config["daysToSend"]
isTime = str(datetime.now().time())[0:5] == self.config["sendTime"]
if isDay and isTime:
for number in known_patients:
message = self.__select_question(number)
print "OEQ (%s) to patient (%s)." % (message, number)
self.__save_message(number, message, 'sent')
self.sms_service.send(number, message)
def __select_question(self, number):
"""
Select a client-defined open-ended question that has not been previously
selected at random. If all have been sent then select one at random.
Args:
number (str): The mobile number of the patient.
Returns:
str: An open-ended question to ask the patient.
"""
questions = self.config['questions']
sent_questions = [item.message for item in db.session.query(
models.Message).filter(models.Message.mobile == number).all()]
unsent_questions = list(set(questions).difference(sent_questions))
# TODO: Select most important question based on client's situation
import random
if unsent_questions:
print "Sending a message that HAS NOT been previously sent."
message = random.choice(unsent_questions)
else:
print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message
def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of the user-defined config file.
"""
import json
from flask import current_app
config_file = current_app.config['PROJECT_ROOT'] + '/sris/config/' + \
current_app.config['CLIENT_NAME'] + '.json'
with open(config_file) as json_settings:
return json.load(json_settings)
def __new_patients(self):
"""
Checks to see if any new patients have been added to the client DB.
Returns:
list: Mobile numbers the client knows & the service does not.
"""
# ALL numbers obtained from the client.
client_numbers = db.session.query(models.Patient.mobile).all()
# The numbers the service has to date.
service_numbers = db.session.query(models.User.mobile).all()
# The numbers the client has, but the service does not.
numbers = set(client_numbers).difference(service_numbers)
print 'There was %s new patients' % str(len(numbers))
# Convert SQLAlchemy KeyedTuple to ordinary list.
return [item.mobile for item in numbers]
def | (self, number):
"""
Adds the patient to the service database.
Args:
number (str): The mobile number of the patient.
"""
db.session.add(models.User(mobile=number))
db.session.commit()
def __save_message(self, number, message, status):
"""
Save the SMS message (sent or received) to the service database.
Args:
number (str): The mobile number of the patient.
message (str): The SMS message content.
status (str): The status of the message, e.g. 'sent' or 'received'.
"""
db.session.add(models.Message(mobile=number, message=message,
status=status))
db.session.commit()
| __create_new_patient | identifier_name |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenger = Messenger(self.config)
self.sms_service = SMSService()
def send_initial_greeting(self):
"""
Sends the initial SMS to new* patients at a pre-defined client time.
*New patients are those that have recently been added
to the clients database, which the service does not know.
Note: this is REQUIRED otherwise 'respond' & other services do not
function as database errors are thrown (understandably).
"""
from datetime import datetime
current_time = str(datetime.now().time())[0:5]
# Send the message to new patients at the defined time.
if current_time == self.config['initialQuestion']['time']:
for number in self.__new_patients():
message = self.messenger.initial_message()
self.sms_service.send(number, message)
self.__create_new_patient(number)
self.__save_message(number, message, 'sent')
def respond(self, patient_response):
"""
Respond to new SMS when it is received via a POST request.
Args:
patient_message (dict): Contains the number, and message sent to
the service by a patient.
Returns:
response (XML): twilio formatted response.
"""
number = patient_response['number']
patient_message = patient_response['message']
# Generate a reflective summary based on the patient's response.
summary = self.messenger.summary(patient_message)
# TODO: Fix this with the system set time (i.e. UTC)
midnight = int(datetime.today().strftime("%s")) - 24*60*60
# The number of questions sent since last night.
_questions = db.session.query(models.Message).filter(
models.Message.mobile == number,
models.Message.status == 'sent',
models.Message.timestamp >= midnight).all()
all_sent = [item.message for item in _questions]
# The number of OEQ sent since last night.
num_oeq = len([i for i in self.config['questions'] if i in all_sent])
print 'Number OEQ sent since last night was: %s' % str(num_oeq)
response = None
# Do not send a response if initial daily conversation not started.
if num_oeq >= 1:
print 'The last sms sent was: %s' % all_sent[-1]
if all_sent[-1] in self.config['questions']:
print 'Last message sent was an OEQ. Sending a RS to patient.'
response = summary
else:
print 'Inside the else..'
if (num_oeq >= int(self.config['limit'])): # True: OEQ >= LIMIT
print 'Inside the else... in the if...'
if self.config['endQuestion'] not in all_sent:
|
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
print 'The response (%s) has been saved to the database.' % response
return self.sms_service.reply(response)
else:
print 'No response was created.'
return '' # Prevents a 500 error code returned to POST.
def send_initial_question_to_all(self):
"""
Sends a question to all patients at a pre-defined day and time.
"""
known_patients = [item.mobile for item in
db.session.query(models.Patient.mobile).all()]
from datetime import datetime
print "Checking to see if open-ended question should be sent."
isDay = datetime.now().strftime("%A") in self.config["daysToSend"]
isTime = str(datetime.now().time())[0:5] == self.config["sendTime"]
if isDay and isTime:
for number in known_patients:
message = self.__select_question(number)
print "OEQ (%s) to patient (%s)." % (message, number)
self.__save_message(number, message, 'sent')
self.sms_service.send(number, message)
def __select_question(self, number):
"""
Select a client-defined open-ended question that has not been previously
selected at random. If all have been sent then select one at random.
Args:
number (str): The mobile number of the patient.
Returns:
str: An open-ended question to ask the patient.
"""
questions = self.config['questions']
sent_questions = [item.message for item in db.session.query(
models.Message).filter(models.Message.mobile == number).all()]
unsent_questions = list(set(questions).difference(sent_questions))
# TODO: Select most important question based on client's situation
import random
if unsent_questions:
print "Sending a message that HAS NOT been previously sent."
message = random.choice(unsent_questions)
else:
print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message
def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of the user-defined config file.
"""
import json
from flask import current_app
config_file = current_app.config['PROJECT_ROOT'] + '/sris/config/' + \
current_app.config['CLIENT_NAME'] + '.json'
with open(config_file) as json_settings:
return json.load(json_settings)
def __new_patients(self):
"""
Checks to see if any new patients have been added to the client DB.
Returns:
list: Mobile numbers the client knows & the service does not.
"""
# ALL numbers obtained from the client.
client_numbers = db.session.query(models.Patient.mobile).all()
# The numbers the service has to date.
service_numbers = db.session.query(models.User.mobile).all()
# The numbers the client has, but the service does not.
numbers = set(client_numbers).difference(service_numbers)
print 'There was %s new patients' % str(len(numbers))
# Convert SQLAlchemy KeyedTuple to ordinary list.
return [item.mobile for item in numbers]
def __create_new_patient(self, number):
"""
Adds the patient to the service database.
Args:
number (str): The mobile number of the patient.
"""
db.session.add(models.User(mobile=number))
db.session.commit()
def __save_message(self, number, message, status):
"""
Save the SMS message (sent or received) to the service database.
Args:
number (str): The mobile number of the patient.
message (str): The SMS message content.
status (str): The status of the message, e.g. 'sent' or 'received'.
"""
db.session.add(models.Message(mobile=number, message=message,
status=status))
db.session.commit()
| print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion'] | conditional_block |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` and `post` into our namespace
from DbC import pre, post
def check_pre(*args):
'Pre-condition checker.'
# must have an even number of args
assert ( len(args) & 1 ) == 0, 'Expected an even number of arguments'
# all numbers must be non-negative ints
assert all(i>=0 and isinstance(i,int) for i in args), \
'Numbers must be positive integers'
# all second numbers must be < 10
assert all(i<10 for i in args[1::2]), 'Numbers must be < 10'
def check_post(*args):
'Post-condition checker.'
# return value from decorated function is always the last positional
# parameter
rval = args[-1]
# simple check of the number of items in the return
assert 2 * len(rval) == len(args) - 1
# check units
units_out = [i%10 for i in rval]
units_in = [i for i in args[1:-1:2]]
assert units_out == units_in
# check tens
tens_out = [i//10 for i in rval]
tens_in = [i for i in args[0:-1:2]]
assert tens_out == tens_in
# It doesn't matter which order you include the decorators
@pre(check_pre)
@post(check_post)
def pairoff(*args):
'Make tens+units from pairs of numbers.'
it = iter(args)
return [10*a+b for a,b in zip(it,it)]
# Test data
print( pairoff(*range(8)) )
print( pairoff(4,2, 10,1) )
try: # odd number of args
pairoff(1,2,3,4,5)
except AssertionError as e:
print(e)
try: # unit >= 10
pairoff(4,2, 9,10)
except AssertionError as e:
print(e)
try: # negative | pairoff(4,2, -1,2)
except AssertionError as e:
print(e)
try: # non-integer
pairoff(1.25,0.6)
except AssertionError as e:
print(e) | random_line_split | |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` and `post` into our namespace
from DbC import pre, post
def check_pre(*args):
|
def check_post(*args):
'Post-condition checker.'
# return value from decorated function is always the last positional
# parameter
rval = args[-1]
# simple check of the number of items in the return
assert 2 * len(rval) == len(args) - 1
# check units
units_out = [i%10 for i in rval]
units_in = [i for i in args[1:-1:2]]
assert units_out == units_in
# check tens
tens_out = [i//10 for i in rval]
tens_in = [i for i in args[0:-1:2]]
assert tens_out == tens_in
# It doesn't matter which order you include the decorators
@pre(check_pre)
@post(check_post)
def pairoff(*args):
'Make tens+units from pairs of numbers.'
it = iter(args)
return [10*a+b for a,b in zip(it,it)]
# Test data
print( pairoff(*range(8)) )
print( pairoff(4,2, 10,1) )
try: # odd number of args
pairoff(1,2,3,4,5)
except AssertionError as e:
print(e)
try: # unit >= 10
pairoff(4,2, 9,10)
except AssertionError as e:
print(e)
try: # negative
pairoff(4,2, -1,2)
except AssertionError as e:
print(e)
try: # non-integer
pairoff(1.25,0.6)
except AssertionError as e:
print(e)
| 'Pre-condition checker.'
# must have an even number of args
assert ( len(args) & 1 ) == 0, 'Expected an even number of arguments'
# all numbers must be non-negative ints
assert all(i>=0 and isinstance(i,int) for i in args), \
'Numbers must be positive integers'
# all second numbers must be < 10
assert all(i<10 for i in args[1::2]), 'Numbers must be < 10' | identifier_body |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` and `post` into our namespace
from DbC import pre, post
def | (*args):
'Pre-condition checker.'
# must have an even number of args
assert ( len(args) & 1 ) == 0, 'Expected an even number of arguments'
# all numbers must be non-negative ints
assert all(i>=0 and isinstance(i,int) for i in args), \
'Numbers must be positive integers'
# all second numbers must be < 10
assert all(i<10 for i in args[1::2]), 'Numbers must be < 10'
def check_post(*args):
'Post-condition checker.'
# return value from decorated function is always the last positional
# parameter
rval = args[-1]
# simple check of the number of items in the return
assert 2 * len(rval) == len(args) - 1
# check units
units_out = [i%10 for i in rval]
units_in = [i for i in args[1:-1:2]]
assert units_out == units_in
# check tens
tens_out = [i//10 for i in rval]
tens_in = [i for i in args[0:-1:2]]
assert tens_out == tens_in
# It doesn't matter which order you include the decorators
@pre(check_pre)
@post(check_post)
def pairoff(*args):
'Make tens+units from pairs of numbers.'
it = iter(args)
return [10*a+b for a,b in zip(it,it)]
# Test data
print( pairoff(*range(8)) )
print( pairoff(4,2, 10,1) )
try: # odd number of args
pairoff(1,2,3,4,5)
except AssertionError as e:
print(e)
try: # unit >= 10
pairoff(4,2, 9,10)
except AssertionError as e:
print(e)
try: # negative
pairoff(4,2, -1,2)
except AssertionError as e:
print(e)
try: # non-integer
pairoff(1.25,0.6)
except AssertionError as e:
print(e)
| check_pre | identifier_name |
taskcluster-spark-dogfood.py | #!/usr/bin/env python
import os.path
config = {
"default_vcs": "tc-vcs",
"default_actions": [
'checkout-sources',
'build',
'build-symbols',
'make-updates',
'prep-upload',
'submit-to-balrog'
],
"balrog_credentials_file": "balrog_credentials",
"nightly_build": True,
"env": {
"GAIA_OPTIMIZE": "1",
"B2G_UPDATER": "1",
"LIGHTSABER": "1", | "B2G_UPDATE_CHANNEL": "dogfood",
"BOWER_FLAGS": "--allow-root",
"B2G_PATH": "%(work_dir)s",
"GAIA_DISTRIBUTION_DIR": "%(work_dir)s/gaia/distros/spark",
"WGET_OPTS": "-c -q"
},
"is_automation": True,
"repo_remote_mappings": {
'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp',
'git://codeaurora.org/': 'https://git.mozilla.org/external/caf',
'https://git.mozilla.org/b2g': 'https://git.mozilla.org/b2g',
'git://github.com/mozilla-b2g/': 'https://git.mozilla.org/b2g',
'git://github.com/mozilla/': 'https://git.mozilla.org/b2g',
'https://git.mozilla.org/releases': 'https://git.mozilla.org/releases',
'http://android.git.linaro.org/git-ro/': 'https://git.mozilla.org/external/linaro',
'git://github.com/apitrace/': 'https://git.mozilla.org/external/apitrace',
},
} | "DOGFOOD": "1", | random_line_split |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. This dependency should be removed, and this file deleted, in the
# future.
def AddBuildTypeOption(option_parser):
"""Decorates OptionParser with build type option."""
default_build_type = 'Debug'
if 'BUILDTYPE' in os.environ:
|
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type', default=default_build_type,
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
'Default is env var BUILDTYPE or Debug.')
def AddTestRunnerOptions(option_parser, default_timeout=60):
"""Decorates OptionParser with options applicable to all tests."""
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int',
default=default_timeout)
option_parser.add_option('-c', dest='cleanup_test_files',
help='Cleanup test files on the device after run',
action='store_true')
option_parser.add_option('--num_retries', dest='num_retries', type='int',
default=2,
help='Number of retries for a test before '
'giving up.')
option_parser.add_option('-v',
'--verbose',
dest='verbose_count',
default=0,
action='count',
help='Verbose level (multiple times for more)')
profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
'traceview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
'Available profilers: %s' % profilers)
option_parser.add_option('--tool',
dest='tool',
help='Run the test under a tool '
'(use --tool help to list them)')
option_parser.add_option('--flakiness-dashboard-server',
dest='flakiness_dashboard_server',
help=('Address of the server that is hosting the '
'Chrome for Android flakiness dashboard.'))
option_parser.add_option('--skip-deps-push', dest='push_deps',
action='store_false', default=True,
help='Do not push dependencies to the device. '
'Use this at own risk for speeding up test '
'execution on local machine.')
AddBuildTypeOption(option_parser)
| default_build_type = os.environ['BUILDTYPE'] | conditional_block |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. This dependency should be removed, and this file deleted, in the
# future.
def AddBuildTypeOption(option_parser):
"""Decorates OptionParser with build type option."""
default_build_type = 'Debug'
if 'BUILDTYPE' in os.environ:
default_build_type = os.environ['BUILDTYPE']
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type', default=default_build_type,
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
'Default is env var BUILDTYPE or Debug.')
def AddTestRunnerOptions(option_parser, default_timeout=60):
"""Decorates OptionParser with options applicable to all tests."""
| default=default_timeout)
option_parser.add_option('-c', dest='cleanup_test_files',
help='Cleanup test files on the device after run',
action='store_true')
option_parser.add_option('--num_retries', dest='num_retries', type='int',
default=2,
help='Number of retries for a test before '
'giving up.')
option_parser.add_option('-v',
'--verbose',
dest='verbose_count',
default=0,
action='count',
help='Verbose level (multiple times for more)')
profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
'traceview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
'Available profilers: %s' % profilers)
option_parser.add_option('--tool',
dest='tool',
help='Run the test under a tool '
'(use --tool help to list them)')
option_parser.add_option('--flakiness-dashboard-server',
dest='flakiness_dashboard_server',
help=('Address of the server that is hosting the '
'Chrome for Android flakiness dashboard.'))
option_parser.add_option('--skip-deps-push', dest='push_deps',
action='store_false', default=True,
help='Do not push dependencies to the device. '
'Use this at own risk for speeding up test '
'execution on local machine.')
AddBuildTypeOption(option_parser) | option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int', | random_line_split |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. This dependency should be removed, and this file deleted, in the
# future.
def AddBuildTypeOption(option_parser):
"""Decorates OptionParser with build type option."""
default_build_type = 'Debug'
if 'BUILDTYPE' in os.environ:
default_build_type = os.environ['BUILDTYPE']
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type', default=default_build_type,
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
'Default is env var BUILDTYPE or Debug.')
def AddTestRunnerOptions(option_parser, default_timeout=60):
| """Decorates OptionParser with options applicable to all tests."""
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int',
default=default_timeout)
option_parser.add_option('-c', dest='cleanup_test_files',
help='Cleanup test files on the device after run',
action='store_true')
option_parser.add_option('--num_retries', dest='num_retries', type='int',
default=2,
help='Number of retries for a test before '
'giving up.')
option_parser.add_option('-v',
'--verbose',
dest='verbose_count',
default=0,
action='count',
help='Verbose level (multiple times for more)')
profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
'traceview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
'Available profilers: %s' % profilers)
option_parser.add_option('--tool',
dest='tool',
help='Run the test under a tool '
'(use --tool help to list them)')
option_parser.add_option('--flakiness-dashboard-server',
dest='flakiness_dashboard_server',
help=('Address of the server that is hosting the '
'Chrome for Android flakiness dashboard.'))
option_parser.add_option('--skip-deps-push', dest='push_deps',
action='store_false', default=True,
help='Do not push dependencies to the device. '
'Use this at own risk for speeding up test '
'execution on local machine.')
AddBuildTypeOption(option_parser) | identifier_body | |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. This dependency should be removed, and this file deleted, in the
# future.
def AddBuildTypeOption(option_parser):
"""Decorates OptionParser with build type option."""
default_build_type = 'Debug'
if 'BUILDTYPE' in os.environ:
default_build_type = os.environ['BUILDTYPE']
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type', default=default_build_type,
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
'Default is env var BUILDTYPE or Debug.')
def | (option_parser, default_timeout=60):
"""Decorates OptionParser with options applicable to all tests."""
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int',
default=default_timeout)
option_parser.add_option('-c', dest='cleanup_test_files',
help='Cleanup test files on the device after run',
action='store_true')
option_parser.add_option('--num_retries', dest='num_retries', type='int',
default=2,
help='Number of retries for a test before '
'giving up.')
option_parser.add_option('-v',
'--verbose',
dest='verbose_count',
default=0,
action='count',
help='Verbose level (multiple times for more)')
profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
'traceview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
'Available profilers: %s' % profilers)
option_parser.add_option('--tool',
dest='tool',
help='Run the test under a tool '
'(use --tool help to list them)')
option_parser.add_option('--flakiness-dashboard-server',
dest='flakiness_dashboard_server',
help=('Address of the server that is hosting the '
'Chrome for Android flakiness dashboard.'))
option_parser.add_option('--skip-deps-push', dest='push_deps',
action='store_false', default=True,
help='Do not push dependencies to the device. '
'Use this at own risk for speeding up test '
'execution on local machine.')
AddBuildTypeOption(option_parser)
| AddTestRunnerOptions | identifier_name |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var inspectCustom = require('./util.inspect').custom;
var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null;
module.exports = function inspect_ (obj, opts, depth, seen) {
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
return String(obj);
}
if (!opts) opts = {};
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') depth = 0;
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return '[Object]';
}
if (typeof seen === 'undefined') seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) return '[]';
return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (parts.length === 0) return '[' + String(obj) + ']';
return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
}
if (typeof obj === 'object') {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
} else if (typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var parts = [];
mapForEach.call(obj, function (value, key) {
parts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), parts);
}
if (isSet(obj)) {
var parts = [];
setForEach.call(obj, function (value ) {
parts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), parts);
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var xs = arrObjKeys(obj, inspect);
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '"');
}
function isArray (obj) { return toStr(obj) === '[object Array]' }
function isDate (obj) { return toStr(obj) === '[object Date]' }
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
function isString (obj) { return toStr(obj) === '[object String]' }
function isNumber (obj) { return toStr(obj) === '[object Number]' }
function isBoolean (obj) { return toStr(obj) === '[object Boolean]' }
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return objectToString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = String(f).match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isMap (x) {
if (!mapSize) {
return false; | } catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet (x) {
if (!setSize) {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
}
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
function markBoxed (str) {
return 'Object(' + str + ')';
}
function collectionOf (type, size, entries) {
return type + ' (' + size + ') {' + entries.join(', ') + '}';
}
function arrObjKeys (obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
for (var key in obj) {
if (!has(obj, key)) continue;
if (isArr && String(Number(key)) === key && key < obj.length) continue;
if (/[^\w$]/.test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
return xs;
} | }
try {
mapSize.call(x);
try {
setSize.call(x); | random_line_split |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var inspectCustom = require('./util.inspect').custom;
var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null;
module.exports = function inspect_ (obj, opts, depth, seen) {
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
return String(obj);
}
if (!opts) opts = {};
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') depth = 0;
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return '[Object]';
}
if (typeof seen === 'undefined') seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) return '[]';
return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (parts.length === 0) return '[' + String(obj) + ']';
return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
}
if (typeof obj === 'object') {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
} else if (typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var parts = [];
mapForEach.call(obj, function (value, key) {
parts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), parts);
}
if (isSet(obj)) {
var parts = [];
setForEach.call(obj, function (value ) {
parts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), parts);
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var xs = arrObjKeys(obj, inspect);
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '"');
}
function isArray (obj) { return toStr(obj) === '[object Array]' }
function isDate (obj) { return toStr(obj) === '[object Date]' }
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
function isString (obj) { return toStr(obj) === '[object String]' }
function isNumber (obj) { return toStr(obj) === '[object Number]' }
function isBoolean (obj) { return toStr(obj) === '[object Boolean]' }
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function | (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return objectToString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = String(f).match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isMap (x) {
if (!mapSize) {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet (x) {
if (!setSize) {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
}
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
function markBoxed (str) {
return 'Object(' + str + ')';
}
function collectionOf (type, size, entries) {
return type + ' (' + size + ') {' + entries.join(', ') + '}';
}
function arrObjKeys (obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
for (var key in obj) {
if (!has(obj, key)) continue;
if (isArr && String(Number(key)) === key && key < obj.length) continue;
if (/[^\w$]/.test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
return xs;
}
| has | identifier_name |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var inspectCustom = require('./util.inspect').custom;
var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null;
module.exports = function inspect_ (obj, opts, depth, seen) {
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
return String(obj);
}
if (!opts) opts = {};
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') depth = 0;
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return '[Object]';
}
if (typeof seen === 'undefined') seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) return '[]';
return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (parts.length === 0) return '[' + String(obj) + ']';
return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
}
if (typeof obj === 'object') {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
} else if (typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var parts = [];
mapForEach.call(obj, function (value, key) {
parts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), parts);
}
if (isSet(obj)) {
var parts = [];
setForEach.call(obj, function (value ) {
parts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), parts);
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var xs = arrObjKeys(obj, inspect);
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '"');
}
function isArray (obj) { return toStr(obj) === '[object Array]' }
function isDate (obj) |
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
function isString (obj) { return toStr(obj) === '[object String]' }
function isNumber (obj) { return toStr(obj) === '[object Number]' }
function isBoolean (obj) { return toStr(obj) === '[object Boolean]' }
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return objectToString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = String(f).match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isMap (x) {
if (!mapSize) {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet (x) {
if (!setSize) {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
}
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
function markBoxed (str) {
return 'Object(' + str + ')';
}
function collectionOf (type, size, entries) {
return type + ' (' + size + ') {' + entries.join(', ') + '}';
}
function arrObjKeys (obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
for (var key in obj) {
if (!has(obj, key)) continue;
if (isArr && String(Number(key)) === key && key < obj.length) continue;
if (/[^\w$]/.test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
return xs;
}
| { return toStr(obj) === '[object Date]' } | identifier_body |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var inspectCustom = require('./util.inspect').custom;
var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null;
module.exports = function inspect_ (obj, opts, depth, seen) {
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj);
}
if (typeof obj === 'number') {
if (obj === 0) |
return String(obj);
}
if (!opts) opts = {};
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') depth = 0;
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return '[Object]';
}
if (typeof seen === 'undefined') seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) return '[]';
return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (parts.length === 0) return '[' + String(obj) + ']';
return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
}
if (typeof obj === 'object') {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
} else if (typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var parts = [];
mapForEach.call(obj, function (value, key) {
parts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
});
return collectionOf('Map', mapSize.call(obj), parts);
}
if (isSet(obj)) {
var parts = [];
setForEach.call(obj, function (value ) {
parts.push(inspect(value, obj));
});
return collectionOf('Set', setSize.call(obj), parts);
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var xs = arrObjKeys(obj, inspect);
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '"');
}
function isArray (obj) { return toStr(obj) === '[object Array]' }
function isDate (obj) { return toStr(obj) === '[object Date]' }
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
function isString (obj) { return toStr(obj) === '[object String]' }
function isNumber (obj) { return toStr(obj) === '[object Number]' }
function isBoolean (obj) { return toStr(obj) === '[object Boolean]' }
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return objectToString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = String(f).match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isMap (x) {
if (!mapSize) {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet (x) {
if (!setSize) {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
}
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
function markBoxed (str) {
return 'Object(' + str + ')';
}
function collectionOf (type, size, entries) {
return type + ' (' + size + ') {' + entries.join(', ') + '}';
}
function arrObjKeys (obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
for (var key in obj) {
if (!has(obj, key)) continue;
if (isArr && String(Number(key)) === key && key < obj.length) continue;
if (/[^\w$]/.test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
return xs;
}
| {
return Infinity / obj > 0 ? '0' : '-0';
} | conditional_block |
typeid-intrinsic2.rs | // Copyright 2013 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.
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn | () -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId { TypeId::of::<C>() }
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T: 'static>() -> TypeId { TypeId::of::<T>() }
| id_B | identifier_name |
typeid-intrinsic2.rs | // Copyright 2013 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 |
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn id_B() -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId { TypeId::of::<C>() }
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T: 'static>() -> TypeId { TypeId::of::<T>() } | // option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
typeid-intrinsic2.rs | // Copyright 2013 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.
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn id_B() -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId |
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T: 'static>() -> TypeId { TypeId::of::<T>() }
| { TypeId::of::<C>() } | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
}
| {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
} | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn | () {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
}
| line_through | identifier_name |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect() | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
} | }
}
| random_line_split |
copy.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function (grunt) {
grunt.config('copy', {
build: {
files: [{
cwd: '<%= yeoman.tmp %>/scripts',
dest: '<%= yeoman.dist %>/scripts',
expand: true,
src: ['**/*.js']
}]
},
dist: {
files: [
{
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
dot: true,
// static resources.
expand: true,
src: [
'*.{ico,png,txt}',
'.htaccess',
'images/{,*/}*.{webp,gif,svg,jpg,jpeg,png}',
'styles/fonts/{,*/}*.*',
'fonts/**/*.{woff,eot,ttf,svg,ofl}',
'i18n/{,*/}{,*/}*.*'
]
},
{
cwd: '<%= yeoman.app %>/bower_components/jquery-ui',
dest: '<%= yeoman.dist %>/bower_components/jquery-ui',
// jquery ui
expand: true,
src: ['**/*.js']
},
{
cwd: '<%= yeoman.app %>/bower_components/fxa-password-strength-checker/build/',
dest: '<%= yeoman.dist %>/bower_components/fxa-password-strength-checker/build/',
// password strength checker
expand: true,
src: ['*.js']
},
{
cwd: '<%= yeoman.app %>/bower_components/fxa-checkbox/',
dest: '<%= yeoman.dist %>/bower_components/fxa-checkbox/',
// fxa-checkbox
expand: true,
src: ['*.js']
},
{
cwd: '<%= yeoman.tmp %>/concat/scripts',
dest: '<%= yeoman.dist %>/scripts',
// head scripts
expand: true,
src: ['**/*.js']
}
]
},
error_pages: { //eslint-disable-line camelcase
files: [{
cwd: '<%= yeoman.page_template_dist %>',
dest: '<%= yeoman.app %>',
dot: true,
expand: true,
flatten: true,
src: 'en/{500,502,503}.html'
}]
},
// copy normalize.css to .tmp during build, this library is required by grunt-usemin to be in .tmp
normalize: {
dest: '<%= yeoman.tmp %>/bower_components/normalize-css/normalize.css',
src: 'app/bower_components/normalize-css/normalize.css'
},
strings: { | files: [
{
cwd: '<%= yeoman.strings_src %>',
dest: '<%= yeoman.strings_dist %>',
expand: true,
src: ['**/*.po']
},
{
cwd: '<%= yeoman.strings_src %>/sv_SE',
dest: '<%= yeoman.strings_dist %>/sv',
// Copy strings from sv_SE to sv
expand: true,
src: ['**/*.po']
},
{
cwd: '<%= yeoman.strings_src %>/hi_IN',
dest: '<%= yeoman.strings_dist %>/hi',
// Copy strings from hi_IN to hi
expand: true,
src: ['**/*.po']
}
]
},
styles: {
cwd: '<%= yeoman.app %>/styles',
dest: '<%= yeoman.tmp %>/styles/',
dot: true,
expand: true,
src: '{,*/}*.css'
},
tos_pp: { //eslint-disable-line camelcase
// The legal repo use es-ES but we (in accordance with Verbatim) use es,
// so copy es-ES templates to es
files: [
{
expand: true,
cwd: '<%= yeoman.tos_html_dest %>',
dest: '<%= yeoman.tos_html_dest %>',
src: 'es_ES.html',
rename: function (dest) {
return dest + '/es.html';
}
},
{
expand: true,
cwd: '<%= yeoman.pp_html_dest %>',
dest: '<%= yeoman.pp_html_dest %>',
src: 'es_ES.html',
rename: function (dest) {
return dest + '/es.html';
}
}
]
}
});
}; | random_line_split | |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() | {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | identifier_body | |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // <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.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn | () {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
}
| main | identifier_name |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy from 'fuzzy';
import { SweeperClient } from '../../util/lib/SweeperClient';
import { prompt, PromptResult } from '../../util/lib/Util';
const idRegex: RegExp = /^(?:<@!?)?(\d+)>?$/;
export default class | extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
}
public async action(message: Message): Promise<any> {
let msgAuthor: GuildMember = message.member;
if (msgAuthor) {
// If calling user is the server owner or D0cR3d
if (msgAuthor.user.id === message.guild.ownerID || msgAuthor.user.id === '82942340309716992') {
let embed: RichEmbed = new RichEmbed();
embed.setDescription('If this is a large server, this will take a while and should **NOT** be done often.');
// If message sent from a non-mod channel then show minimal info
if (message.channel.id !== Constants.modChannelId) {
// Delete calling message immediately
message.delete();
}
const [result, ask, confirmation]: [PromptResult, Message, Message] = <[PromptResult, Message, Message]> await prompt(message,
'Are you sure you want to initiate a member sync? (__y__es | __n__o)',
/^(?:yes|y)$/i, /^(?:no|n)$/i, { embed });
// If message sent from a non-mod channel then delete the mod messages
if (ask.channel.id !== Constants.modChannelId) {
// Delete the prompt messages
ask.delete();
confirmation.delete();
}
if (result === PromptResult.TIMEOUT) return message.channel.send('Command timed out, aborting action.');
if (result === PromptResult.FAILURE) return message.channel.send('Okay, aborting action.');
// If guild owner confirmed action
try {
let actionMsg: Message;
actionMsg = <Message> await message.channel.send(`Attempting action...`);
// Fetches all members including offline
await message.guild.fetchMembers();
// Adds to the database
for (const member of message.guild.members.values()) {
await this.client.mod.actions.userJoin(member, message.guild);
this.logger.log('CMD membersSync', `Added ${member.user.tag} to server join logs.`);
await new Promise((r: any) => setTimeout(r, 250));
}
return actionMsg.edit(`That action has completed.`);
} catch (err) {
const modChannel: TextChannel = <TextChannel> message.guild.channels.get(Constants.modChannelId);
modChannel.send(`There was an error syncing the server members. Please try again.\n\n**Error:**\n${err}`);
return this.logger.log('CMD membersSync', `Unable to sync members: Possible error logging to DB.`);
}
} else {
message.channel.send('You may not use this command.');
return message.delete();
}
}
}
}
| Mute | identifier_name |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy from 'fuzzy';
import { SweeperClient } from '../../util/lib/SweeperClient';
import { prompt, PromptResult } from '../../util/lib/Util';
const idRegex: RegExp = /^(?:<@!?)?(\d+)>?$/;
export default class Mute extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
}
public async action(message: Message): Promise<any> {
let msgAuthor: GuildMember = message.member;
if (msgAuthor) {
// If calling user is the server owner or D0cR3d
if (msgAuthor.user.id === message.guild.ownerID || msgAuthor.user.id === '82942340309716992') {
let embed: RichEmbed = new RichEmbed();
embed.setDescription('If this is a large server, this will take a while and should **NOT** be done often.');
// If message sent from a non-mod channel then show minimal info
if (message.channel.id !== Constants.modChannelId) |
const [result, ask, confirmation]: [PromptResult, Message, Message] = <[PromptResult, Message, Message]> await prompt(message,
'Are you sure you want to initiate a member sync? (__y__es | __n__o)',
/^(?:yes|y)$/i, /^(?:no|n)$/i, { embed });
// If message sent from a non-mod channel then delete the mod messages
if (ask.channel.id !== Constants.modChannelId) {
// Delete the prompt messages
ask.delete();
confirmation.delete();
}
if (result === PromptResult.TIMEOUT) return message.channel.send('Command timed out, aborting action.');
if (result === PromptResult.FAILURE) return message.channel.send('Okay, aborting action.');
// If guild owner confirmed action
try {
let actionMsg: Message;
actionMsg = <Message> await message.channel.send(`Attempting action...`);
// Fetches all members including offline
await message.guild.fetchMembers();
// Adds to the database
for (const member of message.guild.members.values()) {
await this.client.mod.actions.userJoin(member, message.guild);
this.logger.log('CMD membersSync', `Added ${member.user.tag} to server join logs.`);
await new Promise((r: any) => setTimeout(r, 250));
}
return actionMsg.edit(`That action has completed.`);
} catch (err) {
const modChannel: TextChannel = <TextChannel> message.guild.channels.get(Constants.modChannelId);
modChannel.send(`There was an error syncing the server members. Please try again.\n\n**Error:**\n${err}`);
return this.logger.log('CMD membersSync', `Unable to sync members: Possible error logging to DB.`);
}
} else {
message.channel.send('You may not use this command.');
return message.delete();
}
}
}
}
| {
// Delete calling message immediately
message.delete();
} | conditional_block |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy from 'fuzzy';
import { SweeperClient } from '../../util/lib/SweeperClient';
import { prompt, PromptResult } from '../../util/lib/Util';
const idRegex: RegExp = /^(?:<@!?)?(\d+)>?$/;
export default class Mute extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() |
public async action(message: Message): Promise<any> {
let msgAuthor: GuildMember = message.member;
if (msgAuthor) {
// If calling user is the server owner or D0cR3d
if (msgAuthor.user.id === message.guild.ownerID || msgAuthor.user.id === '82942340309716992') {
let embed: RichEmbed = new RichEmbed();
embed.setDescription('If this is a large server, this will take a while and should **NOT** be done often.');
// If message sent from a non-mod channel then show minimal info
if (message.channel.id !== Constants.modChannelId) {
// Delete calling message immediately
message.delete();
}
const [result, ask, confirmation]: [PromptResult, Message, Message] = <[PromptResult, Message, Message]> await prompt(message,
'Are you sure you want to initiate a member sync? (__y__es | __n__o)',
/^(?:yes|y)$/i, /^(?:no|n)$/i, { embed });
// If message sent from a non-mod channel then delete the mod messages
if (ask.channel.id !== Constants.modChannelId) {
// Delete the prompt messages
ask.delete();
confirmation.delete();
}
if (result === PromptResult.TIMEOUT) return message.channel.send('Command timed out, aborting action.');
if (result === PromptResult.FAILURE) return message.channel.send('Okay, aborting action.');
// If guild owner confirmed action
try {
let actionMsg: Message;
actionMsg = <Message> await message.channel.send(`Attempting action...`);
// Fetches all members including offline
await message.guild.fetchMembers();
// Adds to the database
for (const member of message.guild.members.values()) {
await this.client.mod.actions.userJoin(member, message.guild);
this.logger.log('CMD membersSync', `Added ${member.user.tag} to server join logs.`);
await new Promise((r: any) => setTimeout(r, 250));
}
return actionMsg.edit(`That action has completed.`);
} catch (err) {
const modChannel: TextChannel = <TextChannel> message.guild.channels.get(Constants.modChannelId);
modChannel.send(`There was an error syncing the server members. Please try again.\n\n**Error:**\n${err}`);
return this.logger.log('CMD membersSync', `Unable to sync members: Possible error logging to DB.`);
}
} else {
message.channel.send('You may not use this command.');
return message.delete();
}
}
}
}
| {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
} | identifier_body |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot | import { SweeperClient } from '../../util/lib/SweeperClient';
import { prompt, PromptResult } from '../../util/lib/Util';
const idRegex: RegExp = /^(?:<@!?)?(\d+)>?$/;
export default class Mute extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
}
public async action(message: Message): Promise<any> {
let msgAuthor: GuildMember = message.member;
if (msgAuthor) {
// If calling user is the server owner or D0cR3d
if (msgAuthor.user.id === message.guild.ownerID || msgAuthor.user.id === '82942340309716992') {
let embed: RichEmbed = new RichEmbed();
embed.setDescription('If this is a large server, this will take a while and should **NOT** be done often.');
// If message sent from a non-mod channel then show minimal info
if (message.channel.id !== Constants.modChannelId) {
// Delete calling message immediately
message.delete();
}
const [result, ask, confirmation]: [PromptResult, Message, Message] = <[PromptResult, Message, Message]> await prompt(message,
'Are you sure you want to initiate a member sync? (__y__es | __n__o)',
/^(?:yes|y)$/i, /^(?:no|n)$/i, { embed });
// If message sent from a non-mod channel then delete the mod messages
if (ask.channel.id !== Constants.modChannelId) {
// Delete the prompt messages
ask.delete();
confirmation.delete();
}
if (result === PromptResult.TIMEOUT) return message.channel.send('Command timed out, aborting action.');
if (result === PromptResult.FAILURE) return message.channel.send('Okay, aborting action.');
// If guild owner confirmed action
try {
let actionMsg: Message;
actionMsg = <Message> await message.channel.send(`Attempting action...`);
// Fetches all members including offline
await message.guild.fetchMembers();
// Adds to the database
for (const member of message.guild.members.values()) {
await this.client.mod.actions.userJoin(member, message.guild);
this.logger.log('CMD membersSync', `Added ${member.user.tag} to server join logs.`);
await new Promise((r: any) => setTimeout(r, 250));
}
return actionMsg.edit(`That action has completed.`);
} catch (err) {
const modChannel: TextChannel = <TextChannel> message.guild.channels.get(Constants.modChannelId);
modChannel.send(`There was an error syncing the server members. Please try again.\n\n**Error:**\n${err}`);
return this.logger.log('CMD membersSync', `Unable to sync members: Possible error logging to DB.`);
}
} else {
message.channel.send('You may not use this command.');
return message.delete();
}
}
}
} |
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy from 'fuzzy'; | random_line_split |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.seed(1)
def exam1():
y_hat = tf.constant(36, name='Y-hat')
y = tf.constant(39, name='y')
loss = tf.Variable((y - y_hat) ** 2, name='loss')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(loss))
def exam2():
a = tf.constant(2)
b = tf.constant(3)
c = tf.multiply(a, b)
return c
def exam3(x_input):
with tf.Session() as sess:
x = tf.placeholder(tf.int64, name='x')
y = 2 * x
print(sess.run(y, feed_dict={x: x_input}))
# GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- runs the session for Y = WX + b
"""
np.random.seed(1)
X = tf.constant(np.random.randn(3, 1), tf.float32, name='X')
W = tf.constant(np.random.randn(4, 3), tf.float32, name='W')
b = tf.constant(np.random.randn(4, 1), tf.float32, name='b')
Y = tf.matmul(W, X) + b
with tf.Session() as sess:
result = sess.run(Y)
return result
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
x = tf.placeholder(tf.float32, name='x')
sigmoid = tf.nn.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, feed_dict={x: z})
return result
def cost(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels"
in the TensorFlow documentation. So logits will feed into z, and labels into y.
Returns:
cost -- runs the session of the cost (formula (2))
"""
z = tf.placeholder(tf.float32, name='z-input')
y = tf.placeholder(tf.float32, name='y-input')
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y)
|
# GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
Arguments:
labels -- vector containing the labels
C -- number of classes, the depth of the one hot dimension
Returns:
one_hot -- one hot matrix
"""
C = tf.constant(C, name='C')
one_hot_matrix = tf.one_hot(labels, C, axis=0)
tf.nn.sigmoid_cross_entropy_with_logits()
with tf.Session() as sess:
one_hot = sess.run(one_hot_matrix)
return one_hot
if __name__ == '__main__':
# exam1()
logits = np.array([0.2, 0.4, 0.7, 0.9])
cost = cost(logits, np.array([0, 0, 1, 1]))
print("cost = " + str(cost))
tf.one_hot(labels,C,axis=0) | with tf.Session() as sess:
cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
| random_line_split |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.seed(1)
def exam1():
y_hat = tf.constant(36, name='Y-hat')
y = tf.constant(39, name='y')
loss = tf.Variable((y - y_hat) ** 2, name='loss')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(loss))
def exam2():
a = tf.constant(2)
b = tf.constant(3)
c = tf.multiply(a, b)
return c
def exam3(x_input):
with tf.Session() as sess:
x = tf.placeholder(tf.int64, name='x')
y = 2 * x
print(sess.run(y, feed_dict={x: x_input}))
# GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- runs the session for Y = WX + b
"""
np.random.seed(1)
X = tf.constant(np.random.randn(3, 1), tf.float32, name='X')
W = tf.constant(np.random.randn(4, 3), tf.float32, name='W')
b = tf.constant(np.random.randn(4, 1), tf.float32, name='b')
Y = tf.matmul(W, X) + b
with tf.Session() as sess:
result = sess.run(Y)
return result
# GRADED FUNCTION: sigmoid
def | (z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
x = tf.placeholder(tf.float32, name='x')
sigmoid = tf.nn.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, feed_dict={x: z})
return result
def cost(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels"
in the TensorFlow documentation. So logits will feed into z, and labels into y.
Returns:
cost -- runs the session of the cost (formula (2))
"""
z = tf.placeholder(tf.float32, name='z-input')
y = tf.placeholder(tf.float32, name='y-input')
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y)
with tf.Session() as sess:
cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
# GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
Arguments:
labels -- vector containing the labels
C -- number of classes, the depth of the one hot dimension
Returns:
one_hot -- one hot matrix
"""
C = tf.constant(C, name='C')
one_hot_matrix = tf.one_hot(labels, C, axis=0)
tf.nn.sigmoid_cross_entropy_with_logits()
with tf.Session() as sess:
one_hot = sess.run(one_hot_matrix)
return one_hot
if __name__ == '__main__':
# exam1()
logits = np.array([0.2, 0.4, 0.7, 0.9])
cost = cost(logits, np.array([0, 0, 1, 1]))
print("cost = " + str(cost))
tf.one_hot(labels,C,axis=0) | sigmoid | identifier_name |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.seed(1)
def exam1():
y_hat = tf.constant(36, name='Y-hat')
y = tf.constant(39, name='y')
loss = tf.Variable((y - y_hat) ** 2, name='loss')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(loss))
def exam2():
a = tf.constant(2)
b = tf.constant(3)
c = tf.multiply(a, b)
return c
def exam3(x_input):
with tf.Session() as sess:
x = tf.placeholder(tf.int64, name='x')
y = 2 * x
print(sess.run(y, feed_dict={x: x_input}))
# GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- runs the session for Y = WX + b
"""
np.random.seed(1)
X = tf.constant(np.random.randn(3, 1), tf.float32, name='X')
W = tf.constant(np.random.randn(4, 3), tf.float32, name='W')
b = tf.constant(np.random.randn(4, 1), tf.float32, name='b')
Y = tf.matmul(W, X) + b
with tf.Session() as sess:
result = sess.run(Y)
return result
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
x = tf.placeholder(tf.float32, name='x')
sigmoid = tf.nn.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, feed_dict={x: z})
return result
def cost(logits, labels):
| trix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
Arguments:
labels -- vector containing the labels
C -- number of classes, the depth of the one hot dimension
Returns:
one_hot -- one hot matrix
"""
C = tf.constant(C, name='C')
one_hot_matrix = tf.one_hot(labels, C, axis=0)
tf.nn.sigmoid_cross_entropy_with_logits()
with tf.Session() as sess:
one_hot = sess.run(one_hot_matrix)
return one_hot
if __name__ == '__main__':
# exam1()
logits = np.array([0.2, 0.4, 0.7, 0.9])
cost = cost(logits, np.array([0, 0, 1, 1]))
print("cost = " + str(cost))
tf.one_hot(labels,C,axis=0) | """
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels"
in the TensorFlow documentation. So logits will feed into z, and labels into y.
Returns:
cost -- runs the session of the cost (formula (2))
"""
z = tf.placeholder(tf.float32, name='z-input')
y = tf.placeholder(tf.float32, name='y-input')
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y)
with tf.Session() as sess:
cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
# GRADED FUNCTION: one_hot_ma | identifier_body |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.seed(1)
def exam1():
y_hat = tf.constant(36, name='Y-hat')
y = tf.constant(39, name='y')
loss = tf.Variable((y - y_hat) ** 2, name='loss')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(loss))
def exam2():
a = tf.constant(2)
b = tf.constant(3)
c = tf.multiply(a, b)
return c
def exam3(x_input):
with tf.Session() as sess:
x = tf.placeholder(tf.int64, name='x')
y = 2 * x
print(sess.run(y, feed_dict={x: x_input}))
# GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- runs the session for Y = WX + b
"""
np.random.seed(1)
X = tf.constant(np.random.randn(3, 1), tf.float32, name='X')
W = tf.constant(np.random.randn(4, 3), tf.float32, name='W')
b = tf.constant(np.random.randn(4, 1), tf.float32, name='b')
Y = tf.matmul(W, X) + b
with tf.Session() as sess:
result = sess.run(Y)
return result
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
x = tf.placeholder(tf.float32, name='x')
sigmoid = tf.nn.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, feed_dict={x: z})
return result
def cost(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels"
in the TensorFlow documentation. So logits will feed into z, and labels into y.
Returns:
cost -- runs the session of the cost (formula (2))
"""
z = tf.placeholder(tf.float32, name='z-input')
y = tf.placeholder(tf.float32, name='y-input')
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y)
with tf.Session() as sess:
cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
# GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
Arguments:
labels -- vector containing the labels
C -- number of classes, the depth of the one hot dimension
Returns:
one_hot -- one hot matrix
"""
C = tf.constant(C, name='C')
one_hot_matrix = tf.one_hot(labels, C, axis=0)
tf.nn.sigmoid_cross_entropy_with_logits()
with tf.Session() as sess:
one_hot = sess.run(one_hot_matrix)
return one_hot
if __name__ == '__main__':
# exam1()
logits = np.array([0.2, 0.4, 0.7 | , 0.9])
cost = cost(logits, np.array([0, 0, 1, 1]))
print("cost = " + str(cost))
tf.one_hot(labels,C,axis=0) | conditional_block | |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn | (stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
}
}
Ok(results)
}
}
| read_and_decode | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result; | // Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn read_and_decode(stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
}
}
Ok(results)
}
} | random_line_split | |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn read_and_decode(stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> |
}
| {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
}
}
Ok(results)
} | identifier_body |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
# Importing the libraries
from domainIndependent import *
from operator import itemgetter
import itertools
# General Graphic Search (with goal state verification only after choosing a leaf node!)
def g | problem, strategy):
node = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there are no more nodes to explore and we didn't found a solution yet, return Failure
if not frontier:
iteration = next(iterCounter)
return None, iteration, len(frontier), generatedNodes
# chooses the node with the lowest cost
# first we sort by max and then we take the last element of the list
# this allow us to choose the vertice with the last lowest cost that was
# appended to list (in case of ties)
sortedFrontier = sorted(frontier, key = itemgetter('f'), reverse = True)
node = sortedFrontier[-1]
# and remove it from the frontier
frontier.remove(node)
# checks if the chosen node its a goal state before expand it
if problem.goalState(node) is True:
iteration = next(iterCounter)
return execute(node), iteration, len(frontier), generatedNodes
iteration = next(iterCounter)
# Debugging process
#gsDebug(iteration, node, frontier)
# adds the node being explored to the explored set
exploredSet.append(node)
# expand the node and get the child nodes
childNodes = childNodesGetter(problem, node, strategy)
for child in childNodes:
generatedNodes = next(nodesCounter)
# checks if the child node has already been explored or if it is already in the frontier
if not inExploredList(problem, child, exploredSet) and not inFrontier(problem, child, frontier):
frontier.append(child)
| s( | identifier_name |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
# Importing the libraries
from domainIndependent import *
from operator import itemgetter
import itertools
# General Graphic Search (with goal state verification only after choosing a leaf node!)
def gs(problem, strategy):
n | ode = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there are no more nodes to explore and we didn't found a solution yet, return Failure
if not frontier:
iteration = next(iterCounter)
return None, iteration, len(frontier), generatedNodes
# chooses the node with the lowest cost
# first we sort by max and then we take the last element of the list
# this allow us to choose the vertice with the last lowest cost that was
# appended to list (in case of ties)
sortedFrontier = sorted(frontier, key = itemgetter('f'), reverse = True)
node = sortedFrontier[-1]
# and remove it from the frontier
frontier.remove(node)
# checks if the chosen node its a goal state before expand it
if problem.goalState(node) is True:
iteration = next(iterCounter)
return execute(node), iteration, len(frontier), generatedNodes
iteration = next(iterCounter)
# Debugging process
#gsDebug(iteration, node, frontier)
# adds the node being explored to the explored set
exploredSet.append(node)
# expand the node and get the child nodes
childNodes = childNodesGetter(problem, node, strategy)
for child in childNodes:
generatedNodes = next(nodesCounter)
# checks if the child node has already been explored or if it is already in the frontier
if not inExploredList(problem, child, exploredSet) and not inFrontier(problem, child, frontier):
frontier.append(child)
| identifier_body | |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
# Importing the libraries
from domainIndependent import *
from operator import itemgetter
import itertools
# General Graphic Search (with goal state verification only after choosing a leaf node!)
def gs(problem, strategy):
node = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there are no more nodes to explore and we didn't found a solution yet, return Failure
if not frontier:
i | # chooses the node with the lowest cost
# first we sort by max and then we take the last element of the list
# this allow us to choose the vertice with the last lowest cost that was
# appended to list (in case of ties)
sortedFrontier = sorted(frontier, key = itemgetter('f'), reverse = True)
node = sortedFrontier[-1]
# and remove it from the frontier
frontier.remove(node)
# checks if the chosen node its a goal state before expand it
if problem.goalState(node) is True:
iteration = next(iterCounter)
return execute(node), iteration, len(frontier), generatedNodes
iteration = next(iterCounter)
# Debugging process
#gsDebug(iteration, node, frontier)
# adds the node being explored to the explored set
exploredSet.append(node)
# expand the node and get the child nodes
childNodes = childNodesGetter(problem, node, strategy)
for child in childNodes:
generatedNodes = next(nodesCounter)
# checks if the child node has already been explored or if it is already in the frontier
if not inExploredList(problem, child, exploredSet) and not inFrontier(problem, child, frontier):
frontier.append(child)
| teration = next(iterCounter)
return None, iteration, len(frontier), generatedNodes
| conditional_block |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
# Importing the libraries
from domainIndependent import *
from operator import itemgetter
import itertools
# General Graphic Search (with goal state verification only after choosing a leaf node!)
def gs(problem, strategy):
node = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there are no more nodes to explore and we didn't found a solution yet, return Failure
if not frontier:
iteration = next(iterCounter)
return None, iteration, len(frontier), generatedNodes
# chooses the node with the lowest cost
# first we sort by max and then we take the last element of the list
# this allow us to choose the vertice with the last lowest cost that was
# appended to list (in case of ties)
sortedFrontier = sorted(frontier, key = itemgetter('f'), reverse = True)
node = sortedFrontier[-1]
# and remove it from the frontier
frontier.remove(node)
# checks if the chosen node its a goal state before expand it
if problem.goalState(node) is True:
iteration = next(iterCounter)
return execute(node), iteration, len(frontier), generatedNodes
iteration = next(iterCounter)
# Debugging process
#gsDebug(iteration, node, frontier) | generatedNodes = next(nodesCounter)
# checks if the child node has already been explored or if it is already in the frontier
if not inExploredList(problem, child, exploredSet) and not inFrontier(problem, child, frontier):
frontier.append(child) | # adds the node being explored to the explored set
exploredSet.append(node)
# expand the node and get the child nodes
childNodes = childNodesGetter(problem, node, strategy)
for child in childNodes: | random_line_split |
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
| context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click() | identifier_body | |
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def | (context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
| step_impl | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.