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
view_environment.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ Script to visualize the model coordination environments """ __author__ = "David Waroquiers" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "2.0" __maintainer__ = "David Waroquiers" __email__ = "[email protected]" __date__ = "Feb 20, 2016" from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import AllCoordinationGeometries from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import SEPARATION_PLANE from pymatgen.analysis.chemenv.utils.scripts_utils import visualize from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane import numpy as np if __name__ == '__main__': print('+-------------------------------------------------------+\n' '| Development script of the ChemEnv utility of pymatgen |\n' '| Visualization of the model coordination environments |\n' '+-------------------------------------------------------+\n') allcg = AllCoordinationGeometries() vis = None while True: cg_symbol = raw_input('Enter symbol of the geometry you want to see, "l" to see the list ' 'of existing geometries or "q" to quit : ') if cg_symbol == 'q': break if cg_symbol == 'l': print(allcg.pretty_print(maxcn=13, additional_info={'nb_hints': True})) continue try: cg = allcg[cg_symbol] except LookupError: print('Wrong geometry, try again ...') continue print(cg.name) for ipoint, point in enumerate(cg.points): print('Point #{:d} : {} {} {}'.format(ipoint, repr(point[0]), repr(point[1]), repr(point[2]))) print('Algorithms used :') for ialgo, algo in enumerate(cg.algorithms): print('Algorithm #{:d} :'.format(ialgo)) print(algo) print('') # Visualize the separation plane of a given algorithm sepplane = False if any([algo.algorithm_type == SEPARATION_PLANE for algo in cg.algorithms]): test = raw_input('Enter index of the algorithm for which you want to visualize the plane : ') if test != '':
myfactor = 3.0 if vis is None: vis = visualize(cg=cg, zoom=1.0, myfactor=myfactor) else: vis = visualize(cg=cg, vis=vis, myfactor=myfactor) cg_points = [myfactor*np.array(pp) for pp in cg.points] cg_central_site = myfactor*np.array(cg.central_site) if sepplane: pts = [cg_points[ii] for ii in algo.plane_points] if algo.minimum_number_of_points == 2: pts.append(cg_central_site) centre = cg_central_site else: centre = np.sum(pts, axis=0) / len(pts) factor = 1.5 target_dist = max([np.dot(pp-centre, pp-centre) for pp in cg_points]) current_dist = np.dot(pts[0] - centre, pts[0] - centre) factor = factor * target_dist / current_dist plane = Plane.from_npoints(points=pts) p1 = centre + factor * (pts[0] - centre) perp = factor * np.cross(pts[0] - centre, plane.normal_vector) p2 = centre + perp p3 = centre - factor * (pts[0] - centre) p4 = centre - perp vis.add_faces([[p1, p2, p3, p4]], [1.0, 0.0, 0.0], opacity=0.5) target_radius = 0.25 radius = 1.5 * target_radius if algo.minimum_number_of_points == 2: vis.add_partial_sphere(coords=cg_central_site, radius=radius, color=[1.0, 0.0, 0.0], start=0, end=360, opacity=0.5) for pp in pts: vis.add_partial_sphere(coords=pp, radius=radius, color=[1.0, 0.0, 0.0], start=0, end=360, opacity=0.5) ps1 = [cg_points[ii] for ii in algo.point_groups[0]] ps2 = [cg_points[ii] for ii in algo.point_groups[1]] for pp in ps1: vis.add_partial_sphere(coords=pp, radius=radius, color=[0.0, 1.0, 0.0], start=0, end=360, opacity=0.5) for pp in ps2: vis.add_partial_sphere(coords=pp, radius=radius, color=[0.0, 0.0, 1.0], start=0, end=360, opacity=0.5) vis.show()
try: ialgo = int(test) algo = cg.algorithms[ialgo] sepplane = True except: print('Unable to determine the algorithm/separation_plane you want ' 'to visualize for this geometry. Continues without ...')
conditional_block
const-fields-and-indexing.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. const x : [isize; 4] = [1,2,3,4]; static p : isize = x[2]; const y : &'static [isize] = &[1,2,3,4]; static q : isize = y[2]; struct S {a: isize, b: isize} const s : S = S {a: 10, b: 20};
struct K {a: isize, b: isize, c: D} struct D { d: isize, e: isize } const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}}; static m : isize = k.c.e; pub fn main() { println!("{}", p); println!("{}", q); println!("{}", t); assert_eq!(p, 3); assert_eq!(q, 3); assert_eq!(t, 20); }
static t : isize = s.b;
random_line_split
const-fields-and-indexing.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. const x : [isize; 4] = [1,2,3,4]; static p : isize = x[2]; const y : &'static [isize] = &[1,2,3,4]; static q : isize = y[2]; struct S {a: isize, b: isize} const s : S = S {a: 10, b: 20}; static t : isize = s.b; struct K {a: isize, b: isize, c: D} struct
{ d: isize, e: isize } const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}}; static m : isize = k.c.e; pub fn main() { println!("{}", p); println!("{}", q); println!("{}", t); assert_eq!(p, 3); assert_eq!(q, 3); assert_eq!(t, 20); }
D
identifier_name
9. if elif else.py
''' What is going on everyone welcome to my if elif else tutorial video. The idea of this is to add yet another layer of logic to the pre-existing if else statement. See with our typical if else statment, the if will be checked for sure, and the else will only run if the if fails... but then what if you want to check multiple ifs?
Instead, you can use what is called the "elif" here in python... which is short for "else if" ''' x = 5 y = 10 z = 22 # first run the default like this, then # change the x > y to x < y... # then change both of these to an == if x > y: print('x is greater than y') elif x < z: print('x is less than z') else: print('if and elif never ran...')
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine. There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
random_line_split
9. if elif else.py
''' What is going on everyone welcome to my if elif else tutorial video. The idea of this is to add yet another layer of logic to the pre-existing if else statement. See with our typical if else statment, the if will be checked for sure, and the else will only run if the if fails... but then what if you want to check multiple ifs? You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine. There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this. Instead, you can use what is called the "elif" here in python... which is short for "else if" ''' x = 5 y = 10 z = 22 # first run the default like this, then # change the x > y to x < y... # then change both of these to an == if x > y: print('x is greater than y') elif x < z:
else: print('if and elif never ran...')
print('x is less than z')
conditional_block
forum.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key))
} } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdForum = function MdForum(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2t-1.3 0.4h-16.6l-6.6 6.8v-23.4q0-0.7 0.4-1.2t1.2-0.4h21.6q0.7 0 1.3 0.4t0.5 1.2v15z m6.6-10q0.7 0 1.2 0.5t0.4 1.1v25l-6.6-6.6h-18.4q-0.7 0-1.1-0.5t-0.5-1.1v-3.4h21.6v-15h3.4z' }) ) ); }; exports.default = MdForum; module.exports = exports['default'];
{ target[key] = source[key]; }
conditional_block
forum.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj)
var MdForum = function MdForum(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2t-1.3 0.4h-16.6l-6.6 6.8v-23.4q0-0.7 0.4-1.2t1.2-0.4h21.6q0.7 0 1.3 0.4t0.5 1.2v15z m6.6-10q0.7 0 1.2 0.5t0.4 1.1v25l-6.6-6.6h-18.4q-0.7 0-1.1-0.5t-0.5-1.1v-3.4h21.6v-15h3.4z' }) ) ); }; exports.default = MdForum; module.exports = exports['default'];
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
forum.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdForum = function MdForum(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2t-1.3 0.4h-16.6l-6.6 6.8v-23.4q0-0.7 0.4-1.2t1.2-0.4h21.6q0.7 0 1.3 0.4t0.5 1.2v15z m6.6-10q0.7 0 1.2 0.5t0.4 1.1v25l-6.6-6.6h-18.4q-0.7 0-1.1-0.5t-0.5-1.1v-3.4h21.6v-15h3.4z' }) ) ); }; exports.default = MdForum; module.exports = exports['default'];
_interopRequireDefault
identifier_name
forum.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react');
var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdForum = function MdForum(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2t-1.3 0.4h-16.6l-6.6 6.8v-23.4q0-0.7 0.4-1.2t1.2-0.4h21.6q0.7 0 1.3 0.4t0.5 1.2v15z m6.6-10q0.7 0 1.2 0.5t0.4 1.1v25l-6.6-6.6h-18.4q-0.7 0-1.1-0.5t-0.5-1.1v-3.4h21.6v-15h3.4z' }) ) ); }; exports.default = MdForum; module.exports = exports['default'];
random_line_split
routing.tsx
import * as myra from 'myra' import * as router from 'myra-router' import RouteComponent from './route-component' /** * State */ type State = { routeCtx: router.RouteContext } const init = {} as State /** * Component */ export default myra.define(init, (evolve, events) => { const onRoute = (ctx: router.RouteContext) => console.log(ctx) > evolve({ routeCtx: ctx }) events.didMount = () => router.addListener(onRoute) const routeTo = (path: string) => (ev: Event) => { ev.preventDefault() return router.routeTo(path) } // The render function is called after an update. return state => <section>
'test1/:param': (params: any) => <RouteComponent {...params} /> }, <nothing />)} {state.routeCtx && state.routeCtx.match('test1/:param').isMatch ? <p>Location '/test2/:param' matched.</p> : <nothing />} <ul class="list-group"> <li class="list-group-item"> <a href="" onclick={routeTo('/test1')}> Update location to '/test1' </a> </li> <li class="list-group-item"> <a href="" onclick={routeTo('/test1/test2')}> Update location to '/test1/test2' </a> </li> <li class="list-group-item"> <a href="" onclick={ev => ev.preventDefault() > router.goBack()}> Go back </a> </li> <li class="list-group-item"> <a href="" onclick={ev => ev.preventDefault() > router.goForward()}> Go forward </a> </li> </ul> </section> })
<h1>Router examples</h1> {state.routeCtx && state.routeCtx.matchAny({ 'test1': <p>Route to '/test1'.</p>,
random_line_split
flip.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj)
var ImageFlip = _react2.default.createClass({ displayName: 'ImageFlip', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z'})); } }); exports.default = ImageFlip; module.exports = exports['default'];
{ return obj && obj.__esModule ? obj : {default: obj}; }
identifier_body
flip.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var ImageFlip = _react2.default.createClass({ displayName: 'ImageFlip', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() {
}); exports.default = ImageFlip; module.exports = exports['default'];
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z'})); }
random_line_split
flip.js
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function
(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var ImageFlip = _react2.default.createClass({ displayName: 'ImageFlip', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z'})); } }); exports.default = ImageFlip; module.exports = exports['default'];
_interopRequireDefault
identifier_name
HUnitDaughter2Woman_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True
super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True
random_line_split
HUnitDaughter2Woman_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this):
# define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True
return True
identifier_body
HUnitDaughter2Woman_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self["mm__"] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self["MT_constraint__"] = """return True""" self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self["equations"] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Family""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1]["MT_pre__attr1"] = """return True""" self.vs[1]["MT_label__"] = """2""" self.vs[1]["mm__"] = """MT_pre__Child""" self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2]["MT_pre__attr1"] = """return attr_value == "daughters" """ self.vs[2]["MT_label__"] = """3""" self.vs[2]["mm__"] = """MT_pre__directLink_S""" self.vs[2]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def
(self, attr_value, this): return attr_value == "daughters" def constraint(self, PreNode, graph): return True
eval_attr13
identifier_name
uniq-cc.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. #![feature(managed_boxes)] use std::cell::RefCell; enum maybe_pointy { none, p(@RefCell<Pointy>), } struct Pointy { a : maybe_pointy, c : Box<int>, d : proc():Send->(), } fn empty_pointy() -> @RefCell<Pointy> { return @RefCell::new(Pointy { a : none, c : box 22, d : proc() {}, }) } pub fn main()
{ let v = empty_pointy(); { let mut vb = v.borrow_mut(); vb.a = p(v); } }
identifier_body
uniq-cc.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.
use std::cell::RefCell; enum maybe_pointy { none, p(@RefCell<Pointy>), } struct Pointy { a : maybe_pointy, c : Box<int>, d : proc():Send->(), } fn empty_pointy() -> @RefCell<Pointy> { return @RefCell::new(Pointy { a : none, c : box 22, d : proc() {}, }) } pub fn main() { let v = empty_pointy(); { let mut vb = v.borrow_mut(); vb.a = p(v); } }
#![feature(managed_boxes)]
random_line_split
uniq-cc.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. #![feature(managed_boxes)] use std::cell::RefCell; enum maybe_pointy { none, p(@RefCell<Pointy>), } struct Pointy { a : maybe_pointy, c : Box<int>, d : proc():Send->(), } fn
() -> @RefCell<Pointy> { return @RefCell::new(Pointy { a : none, c : box 22, d : proc() {}, }) } pub fn main() { let v = empty_pointy(); { let mut vb = v.borrow_mut(); vb.a = p(v); } }
empty_pointy
identifier_name
torrents.js
App.getTorrentsCollection = function (options) { var start = +new Date(), url = 'http://subapi.com/'; var supportedLanguages = ['english', 'french', 'dutch', 'portuguese', 'romanian', 'spanish', 'turkish', 'brazilian', 'italian']; if (options.genre) { url += options.genre.toLowerCase() + '.json';
url += 'search.json?query=' + options.keywords; } else { url += 'popular.json'; } } if (options.page && options.page.match(/\d+/)) { var str = url.match(/\?/) ? '&' : '?'; url += str + 'page=' + options.page; } var MovieTorrentCollection = Backbone.Collection.extend({ url: url, model: App.Model.Movie, parse: function (data) { var movies = []; data.movies.forEach(function (movie) { var torrents = {}; torrent = ''; var subtitles = {}; for( var k in movie.torrents ) { if( typeof torrents[movie.torrents[k].quality] == 'undefined' ) { torrents[movie.torrents[k].quality] = movie.torrents[k].url; } } // Pick the worst quality by default if( typeof torrents['1080p'] != 'undefined' ){ quality = '1080p'; torrent = torrents['1080p']; } if( typeof torrents['720p'] != 'undefined' ){ quality = '720p'; torrent = torrents['720p']; } for( var k in movie.subtitles ) { if( supportedLanguages.indexOf(movie.subtitles[k].language) < 0 ){ continue; } if( typeof subtitles[movie.subtitles[k].language] == 'undefined' ) { subtitles[movie.subtitles[k].language] = movie.subtitles[k].url; } } movies.push({ imdb: movie.imdb_id, title: movie.title, year: movie.year, runtime: movie.runtime, synopsis: movie.synopsis, voteAverage:movie.vote_average, coverImage: movie.poster, backdropImage: movie.backdrop, quality: quality, torrent: torrent, torrents: torrents, subtitles: subtitles, seeders: movie.seeders, leechers: movie.leechers }); }); return movies; } }); return new MovieTorrentCollection(); };
} else { if (options.keywords) {
random_line_split
torrents.js
App.getTorrentsCollection = function (options) { var start = +new Date(), url = 'http://subapi.com/'; var supportedLanguages = ['english', 'french', 'dutch', 'portuguese', 'romanian', 'spanish', 'turkish', 'brazilian', 'italian']; if (options.genre) { url += options.genre.toLowerCase() + '.json'; } else { if (options.keywords) { url += 'search.json?query=' + options.keywords; } else
} if (options.page && options.page.match(/\d+/)) { var str = url.match(/\?/) ? '&' : '?'; url += str + 'page=' + options.page; } var MovieTorrentCollection = Backbone.Collection.extend({ url: url, model: App.Model.Movie, parse: function (data) { var movies = []; data.movies.forEach(function (movie) { var torrents = {}; torrent = ''; var subtitles = {}; for( var k in movie.torrents ) { if( typeof torrents[movie.torrents[k].quality] == 'undefined' ) { torrents[movie.torrents[k].quality] = movie.torrents[k].url; } } // Pick the worst quality by default if( typeof torrents['1080p'] != 'undefined' ){ quality = '1080p'; torrent = torrents['1080p']; } if( typeof torrents['720p'] != 'undefined' ){ quality = '720p'; torrent = torrents['720p']; } for( var k in movie.subtitles ) { if( supportedLanguages.indexOf(movie.subtitles[k].language) < 0 ){ continue; } if( typeof subtitles[movie.subtitles[k].language] == 'undefined' ) { subtitles[movie.subtitles[k].language] = movie.subtitles[k].url; } } movies.push({ imdb: movie.imdb_id, title: movie.title, year: movie.year, runtime: movie.runtime, synopsis: movie.synopsis, voteAverage:movie.vote_average, coverImage: movie.poster, backdropImage: movie.backdrop, quality: quality, torrent: torrent, torrents: torrents, subtitles: subtitles, seeders: movie.seeders, leechers: movie.leechers }); }); return movies; } }); return new MovieTorrentCollection(); };
{ url += 'popular.json'; }
conditional_block
BoxGeometry.d.ts
import { Geometry } from '../core/Geometry'; import { BufferGeometry } from '../core/BufferGeometry'; import { Float32BufferAttribute } from '../core/BufferAttribute'; import { Vector3 } from '../math/Vector3'; // Extras / Geometries ///////////////////////////////////////////////////////////////////// export class BoxBufferGeometry extends BufferGeometry { constructor( width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number ); parameters: { width: number; height: number; depth: number; widthSegments: number; heightSegments: number; depthSegments: number; }; } /** * BoxGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. */ export class BoxGeometry extends Geometry { /** * @param width β€” Width of the sides on the X axis. * @param height β€” Height of the sides on the Y axis. * @param depth β€” Depth of the sides on the Z axis. * @param widthSegments β€” Number of segmented faces along the width of the sides. * @param heightSegments β€” Number of segmented faces along the height of the sides. * @param depthSegments β€” Number of segmented faces along the depth of the sides. */ constructor( width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number ); parameters: { width: number; height: number; depth: number;
widthSegments: number; heightSegments: number; depthSegments: number; }; }
random_line_split
BoxGeometry.d.ts
import { Geometry } from '../core/Geometry'; import { BufferGeometry } from '../core/BufferGeometry'; import { Float32BufferAttribute } from '../core/BufferAttribute'; import { Vector3 } from '../math/Vector3'; // Extras / Geometries ///////////////////////////////////////////////////////////////////// export class
extends BufferGeometry { constructor( width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number ); parameters: { width: number; height: number; depth: number; widthSegments: number; heightSegments: number; depthSegments: number; }; } /** * BoxGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. */ export class BoxGeometry extends Geometry { /** * @param width β€” Width of the sides on the X axis. * @param height β€” Height of the sides on the Y axis. * @param depth β€” Depth of the sides on the Z axis. * @param widthSegments β€” Number of segmented faces along the width of the sides. * @param heightSegments β€” Number of segmented faces along the height of the sides. * @param depthSegments β€” Number of segmented faces along the depth of the sides. */ constructor( width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number ); parameters: { width: number; height: number; depth: number; widthSegments: number; heightSegments: number; depthSegments: number; }; }
BoxBufferGeometry
identifier_name
show_hostlink_hostlink.py
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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. from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.show_hostlink import CommandShowHostlink class
(CommandShowHostlink): required_parameters = ["hostlink"]
CommandShowHostlinkHostlink
identifier_name
show_hostlink_hostlink.py
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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.
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.show_hostlink import CommandShowHostlink class CommandShowHostlinkHostlink(CommandShowHostlink): required_parameters = ["hostlink"]
random_line_split
show_hostlink_hostlink.py
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # 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. from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.show_hostlink import CommandShowHostlink class CommandShowHostlinkHostlink(CommandShowHostlink):
required_parameters = ["hostlink"]
identifier_body
ticket.js
'use strict'; var mongoose = require('mongoose'); /** * Schema defining the 'ticket' model. */ var TicketSchema = module.exports = new mongoose.Schema({ /** * Describes on which board does this ticket belong. * * TODO Should we actually group the ticket's under the 'board' model as * references, or keep this style? */ board: { ref: 'board', type: mongoose.Schema.Types.ObjectId, required: true }, /** * Who created the ticket. */ createdBy: { ref: 'user', type: mongoose.Schema.Types.ObjectId }, /** * Who last edited the ticket. */ lastEditedBy: { ref: 'user', type: mongoose.Schema.Types.ObjectId }, /** * The ticket header. */ heading: { type: String, default: '' }, /** * The ticket contents. * * TODO Should we allow HTML content? */ content: { type: String, default: '' }, /** * The ticket color. * * TODO Enumerate the color, eg. #FFF, #BABABA... */ color: { type: String, default: '#FFFFFF' }, /** * Comments of the ticket */ comments: { type: Number, default: 0 }, /** * The ticket's position. The ticket moves in a 2D-plane (x, y) with z * indicating the 'z-index' of the ticket. * * TODO Clamp these to the board's size? We would need to know the ticket's * pixel size in order to clamp the x, y -coordinates to the board's * maximum size. */ position: { x: { type: Number, default: 0 }, y: { type: Number, default: 0 } } });
TicketSchema.options.toJSON.transform = function(doc, ret) { ret.id = doc.id; delete ret._id; delete ret.__v; } /** * BUG See 'config/schemas/board.js' for details. */ TicketSchema.options.toObject.transform = TicketSchema.options.toJSON.transform;
if(!TicketSchema.options.toJSON) TicketSchema.options.toJSON = { } if(!TicketSchema.options.toObject) TicketSchema.options.toObject = { }
random_line_split
catalog.js
function
(NumSection,GrosEntry){ var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry})) // var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"}) $("#tabs").append(TabLink) // $("#my-tab-content").append(SectionBody) } var Vitr= []; function Vitrine (jsonKid,SectionNum){ Vitr.push(jsonKid) IDEnt=Vitr.length-1 var IT = {"Name":jsonKid[0],'Price':jsonKid[1],"Link":jsonKid[2],"About":jsonKid[3],"Weigth":jsonKid[4] } Image = $('<img>',{src:IT.Link, class:"img-thumbnail"}) lot =$("<div/>",{id:IDEnt, class:"product col-6 col-sm-6 col-lg-4"}).prepend(Image).append("<h4>"+IT.Name+" <small>"+IT.Price+"Ρ€ΡƒΠ±</small></h4><p>"+IT.About+" <i>"+IT.Weigth+"Π³Ρ€</i></p>") $("#"+SectionNum).append(lot) } var ShopName = "DH" if ($.cookie('ShopName')){ShopName=$.cookie('ShopName')} $.cookie('ShopName',ShopName) $('#PartnerShopHiden').val(ShopName) function GetCatalog() { var Section = "Sect" var NumSection=0 $.getJSON("./catalog"+ShopName+".json", function(json){ Object.keys(json).forEach(function(GrosEntry) { NumSection+=1 AddSection(NumSection,GrosEntry) var SectionNum = Section+NumSection $("#vitrina").append($("<div/>",{id:SectionNum,class:Section})) json[GrosEntry].forEach(function(entry) { var jsonKid=entry Vitrine(jsonKid,SectionNum) }); }); // $(".Sect:even div").css("font-family","serif"); // $('.product').height(222) // MarketReady() }); MarketReady() } $(document).ready(function () { GetCatalog() })
AddSection
identifier_name
catalog.js
function AddSection(NumSection,GrosEntry){ var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry})) // var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"}) $("#tabs").append(TabLink) // $("#my-tab-content").append(SectionBody) } var Vitr= []; function Vitrine (jsonKid,SectionNum){ Vitr.push(jsonKid) IDEnt=Vitr.length-1 var IT = {"Name":jsonKid[0],'Price':jsonKid[1],"Link":jsonKid[2],"About":jsonKid[3],"Weigth":jsonKid[4] } Image = $('<img>',{src:IT.Link, class:"img-thumbnail"}) lot =$("<div/>",{id:IDEnt, class:"product col-6 col-sm-6 col-lg-4"}).prepend(Image).append("<h4>"+IT.Name+" <small>"+IT.Price+"Ρ€ΡƒΠ±</small></h4><p>"+IT.About+" <i>"+IT.Weigth+"Π³Ρ€</i></p>") $("#"+SectionNum).append(lot) } var ShopName = "DH" if ($.cookie('ShopName')){ShopName=$.cookie('ShopName')} $.cookie('ShopName',ShopName) $('#PartnerShopHiden').val(ShopName) function GetCatalog() { var Section = "Sect" var NumSection=0 $.getJSON("./catalog"+ShopName+".json", function(json){ Object.keys(json).forEach(function(GrosEntry) { NumSection+=1 AddSection(NumSection,GrosEntry) var SectionNum = Section+NumSection $("#vitrina").append($("<div/>",{id:SectionNum,class:Section})) json[GrosEntry].forEach(function(entry) { var jsonKid=entry Vitrine(jsonKid,SectionNum) }); }); // $(".Sect:even div").css("font-family","serif"); // $('.product').height(222) // MarketReady() }); MarketReady()
} $(document).ready(function () { GetCatalog() })
random_line_split
catalog.js
function AddSection(NumSection,GrosEntry){ var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry})) // var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"}) $("#tabs").append(TabLink) // $("#my-tab-content").append(SectionBody) } var Vitr= []; function Vitrine (jsonKid,SectionNum){ Vitr.push(jsonKid) IDEnt=Vitr.length-1 var IT = {"Name":jsonKid[0],'Price':jsonKid[1],"Link":jsonKid[2],"About":jsonKid[3],"Weigth":jsonKid[4] } Image = $('<img>',{src:IT.Link, class:"img-thumbnail"}) lot =$("<div/>",{id:IDEnt, class:"product col-6 col-sm-6 col-lg-4"}).prepend(Image).append("<h4>"+IT.Name+" <small>"+IT.Price+"Ρ€ΡƒΠ±</small></h4><p>"+IT.About+" <i>"+IT.Weigth+"Π³Ρ€</i></p>") $("#"+SectionNum).append(lot) } var ShopName = "DH" if ($.cookie('ShopName')){Shop
okie('ShopName',ShopName) $('#PartnerShopHiden').val(ShopName) function GetCatalog() { var Section = "Sect" var NumSection=0 $.getJSON("./catalog"+ShopName+".json", function(json){ Object.keys(json).forEach(function(GrosEntry) { NumSection+=1 AddSection(NumSection,GrosEntry) var SectionNum = Section+NumSection $("#vitrina").append($("<div/>",{id:SectionNum,class:Section})) json[GrosEntry].forEach(function(entry) { var jsonKid=entry Vitrine(jsonKid,SectionNum) }); }); // $(".Sect:even div").css("font-family","serif"); // $('.product').height(222) // MarketReady() }); MarketReady() } $(document).ready(function () { GetCatalog() })
Name=$.cookie('ShopName')} $.co
conditional_block
catalog.js
function AddSection(NumSection,GrosEntry){ var TabLink = ($('<li/>',{class: "subSection","data-toggle":"tab"})).append($('<a/>',{class:"LinktoAnchor", "href":"#Sect"+NumSection,"data-toggle":"tab",text:GrosEntry})) // var SectionBody = $('<div/>',{id: 'One',class:'tab-pane',html:"<h2>@</h2>"}) $("#tabs").append(TabLink) // $("#my-tab-content").append(SectionBody) } var Vitr= []; function Vitrine (jsonKid,SectionNum){ Vitr.push(jsonKid) IDEnt=Vitr.length-1 var IT = {"Name":jsonKid[0],'Price':jsonKid[1],"Link":jsonKid[2],"About":jsonKid[3],"Weigth":jsonKid[4] } Image = $('<img>',{src:IT.Link, class:"img-thumbnail"}) lot =$("<div/>",{id:IDEnt, class:"product col-6 col-sm-6 col-lg-4"}).prepend(Image).append("<h4>"+IT.Name+" <small>"+IT.Price+"Ρ€ΡƒΠ±</small></h4><p>"+IT.About+" <i>"+IT.Weigth+"Π³Ρ€</i></p>") $("#"+SectionNum).append(lot) } var ShopName = "DH" if ($.cookie('ShopName')){ShopName=$.cookie('ShopName')} $.cookie('ShopName',ShopName) $('#PartnerShopHiden').val(ShopName) function GetCatalog() {
cument).ready(function () { GetCatalog() })
var Section = "Sect" var NumSection=0 $.getJSON("./catalog"+ShopName+".json", function(json){ Object.keys(json).forEach(function(GrosEntry) { NumSection+=1 AddSection(NumSection,GrosEntry) var SectionNum = Section+NumSection $("#vitrina").append($("<div/>",{id:SectionNum,class:Section})) json[GrosEntry].forEach(function(entry) { var jsonKid=entry Vitrine(jsonKid,SectionNum) }); }); // $(".Sect:even div").css("font-family","serif"); // $('.product').height(222) // MarketReady() }); MarketReady() } $(do
identifier_body
lub.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. use super::combine::*; use super::equate::Equate; use super::glb::Glb; use super::higher_ranked::HigherRankedRelations; use super::lattice::*; use super::sub::Sub; use super::{cres, InferCtxt}; use super::{TypeTrace, Subtype}; use middle::ty::{BuiltinBounds}; use middle::ty::{self, Ty}; use syntax::ast::{Many, Once}; use syntax::ast::{Onceness, Unsafety}; use syntax::ast::{MutMutable, MutImmutable}; use util::ppaux::mt_to_string; use util::ppaux::Repr; /// "Least upper bound" (common supertype) pub struct Lub<'f, 'tcx: 'f> { fields: CombineFields<'f, 'tcx> } #[allow(non_snake_case)] pub fn Lub<'f, 'tcx>(cf: CombineFields<'f, 'tcx>) -> Lub<'f, 'tcx> { Lub { fields: cf } } impl<'f, 'tcx> Combine<'tcx> for Lub<'f, 'tcx> { fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx> { self.fields.infcx } fn tag(&self) -> String { "lub".to_string() } fn a_is_expected(&self) -> bool { self.fields.a_is_expected } fn trace(&self) -> TypeTrace<'tcx> { self.fields.trace.clone() } fn
<'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) } fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) } fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) } fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) } fn mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> { let tcx = self.tcx(); debug!("{}.mts({}, {})", self.tag(), mt_to_string(tcx, a), mt_to_string(tcx, b)); if a.mutbl != b.mutbl { return Err(ty::terr_mutability) } let m = a.mutbl; match m { MutImmutable => { let t = try!(self.tys(a.ty, b.ty)); Ok(ty::mt {ty: t, mutbl: m}) } MutMutable => { let t = try!(self.equate().tys(a.ty, b.ty)); Ok(ty::mt {ty: t, mutbl: m}) } } } fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> { self.glb().tys(a, b) } fn unsafeties(&self, a: Unsafety, b: Unsafety) -> cres<'tcx, Unsafety> { match (a, b) { (Unsafety::Unsafe, _) | (_, Unsafety::Unsafe) => Ok(Unsafety::Unsafe), (Unsafety::Normal, Unsafety::Normal) => Ok(Unsafety::Normal), } } fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness> { match (a, b) { (Once, _) | (_, Once) => Ok(Once), (Many, Many) => Ok(Many) } } fn builtin_bounds(&self, a: ty::BuiltinBounds, b: ty::BuiltinBounds) -> cres<'tcx, ty::BuiltinBounds> { // More bounds is a subtype of fewer bounds, so // the LUB (mutual supertype) is the intersection. Ok(a.intersection(b)) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> { self.glb().regions(a, b) } fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(self.infcx().region_vars.lub_regions(Subtype(self.trace()), a, b)) } fn tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> { super_lattice_tys(self, a, b) } fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>> where T : Combineable<'tcx> { self.higher_ranked_lub(a, b) } }
equate
identifier_name
lub.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. use super::combine::*; use super::equate::Equate; use super::glb::Glb; use super::higher_ranked::HigherRankedRelations; use super::lattice::*; use super::sub::Sub; use super::{cres, InferCtxt}; use super::{TypeTrace, Subtype}; use middle::ty::{BuiltinBounds}; use middle::ty::{self, Ty}; use syntax::ast::{Many, Once}; use syntax::ast::{Onceness, Unsafety}; use syntax::ast::{MutMutable, MutImmutable}; use util::ppaux::mt_to_string; use util::ppaux::Repr; /// "Least upper bound" (common supertype) pub struct Lub<'f, 'tcx: 'f> { fields: CombineFields<'f, 'tcx> } #[allow(non_snake_case)] pub fn Lub<'f, 'tcx>(cf: CombineFields<'f, 'tcx>) -> Lub<'f, 'tcx> { Lub { fields: cf } } impl<'f, 'tcx> Combine<'tcx> for Lub<'f, 'tcx> { fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx> { self.fields.infcx } fn tag(&self) -> String { "lub".to_string() } fn a_is_expected(&self) -> bool { self.fields.a_is_expected } fn trace(&self) -> TypeTrace<'tcx> { self.fields.trace.clone() } fn equate<'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) } fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) } fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) } fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) } fn mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> { let tcx = self.tcx(); debug!("{}.mts({}, {})", self.tag(), mt_to_string(tcx, a), mt_to_string(tcx, b)); if a.mutbl != b.mutbl {
return Err(ty::terr_mutability) } let m = a.mutbl; match m { MutImmutable => { let t = try!(self.tys(a.ty, b.ty)); Ok(ty::mt {ty: t, mutbl: m}) } MutMutable => { let t = try!(self.equate().tys(a.ty, b.ty)); Ok(ty::mt {ty: t, mutbl: m}) } } } fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> { self.glb().tys(a, b) } fn unsafeties(&self, a: Unsafety, b: Unsafety) -> cres<'tcx, Unsafety> { match (a, b) { (Unsafety::Unsafe, _) | (_, Unsafety::Unsafe) => Ok(Unsafety::Unsafe), (Unsafety::Normal, Unsafety::Normal) => Ok(Unsafety::Normal), } } fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness> { match (a, b) { (Once, _) | (_, Once) => Ok(Once), (Many, Many) => Ok(Many) } } fn builtin_bounds(&self, a: ty::BuiltinBounds, b: ty::BuiltinBounds) -> cres<'tcx, ty::BuiltinBounds> { // More bounds is a subtype of fewer bounds, so // the LUB (mutual supertype) is the intersection. Ok(a.intersection(b)) } fn contraregions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> { self.glb().regions(a, b) } fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(self.infcx().region_vars.lub_regions(Subtype(self.trace()), a, b)) } fn tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> { super_lattice_tys(self, a, b) } fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>> where T : Combineable<'tcx> { self.higher_ranked_lub(a, b) } }
random_line_split
CoarseFundamentalTop3Algorithm.py
ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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. from clr import AddReference AddReference("System.Core") AddReference("QuantConnect.Common") AddReference("QuantConnect.Algorithm") from System import * from QuantConnect import * from QuantConnect.Algorithm import QCAlgorithm from QuantConnect.Data.UniverseSelection import * ### <summary> ### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks. ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="universes" /> ### <meta name="tag" content="coarse universes" /> ### <meta name="tag" content="fine universes" /> class CoarseFundamentalTop3Algorithm(QCAlgorithm): def Initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.SetStartDate(2014,3,24) #Set Start Date self.SetEndDate(2014,4,7) #Set End Date self.SetCash(50000) #Set Strategy Cash # what resolution should the data *added* to the universe be? self.UniverseSettings.Resolution = Resolution.Daily # this add universe method accepts a single parameter that is a function that # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol> self.AddUniverse(self.CoarseSelectionFunction) self.__numberOfSymbols = 3 self._changes = None # sort the data by daily dollar volume and take the top 'NumberOfSymbols' def CoarseSelectionFunction(self, coarse): # sort descending by daily dollar volume sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True) # return the symbol objects of the top entries from our sorted collection return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ] def OnData(self, data): self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}") # if we have no changes, do nothing if self._changes is None: return # liquidate removed securities for security in self._changes.RemovedSecurities: if
# we want 1/N allocation in each security in our universe for security in self._changes.AddedSecurities: self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols) self._changes = None # this event fires whenever we have changes to our universe def OnSecuritiesChanged(self, changes): self._changes = changes self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}") def OnOrderEvent(self, fill): self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}")
security.Invested: self.Liquidate(security.Symbol)
conditional_block
CoarseFundamentalTop3Algorithm.py
ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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. from clr import AddReference AddReference("System.Core") AddReference("QuantConnect.Common") AddReference("QuantConnect.Algorithm") from System import * from QuantConnect import * from QuantConnect.Algorithm import QCAlgorithm from QuantConnect.Data.UniverseSelection import * ### <summary> ### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks. ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="universes" /> ### <meta name="tag" content="coarse universes" /> ### <meta name="tag" content="fine universes" /> class CoarseFundamentalTop3Algorithm(QCAlgorithm): def Initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.SetStartDate(2014,3,24) #Set Start Date self.SetEndDate(2014,4,7) #Set End Date self.SetCash(50000) #Set Strategy Cash # what resolution should the data *added* to the universe be? self.UniverseSettings.Resolution = Resolution.Daily # this add universe method accepts a single parameter that is a function that # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol> self.AddUniverse(self.CoarseSelectionFunction) self.__numberOfSymbols = 3 self._changes = None # sort the data by daily dollar volume and take the top 'NumberOfSymbols' def CoarseSelectionFunction(self, coarse): # sort descending by daily dollar volume sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True) # return the symbol objects of the top entries from our sorted collection return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ] def OnData(self, data): self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}") # if we have no changes, do nothing if self._changes is None: return # liquidate removed securities for security in self._changes.RemovedSecurities: if security.Invested: self.Liquidate(security.Symbol) # we want 1/N allocation in each security in our universe for security in self._changes.AddedSecurities: self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols) self._changes = None # this event fires whenever we have changes to our universe def OnSecuritiesChanged(self, changes): self._changes = changes self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}")
self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}")
def OnOrderEvent(self, fill):
random_line_split
CoarseFundamentalTop3Algorithm.py
ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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. from clr import AddReference AddReference("System.Core") AddReference("QuantConnect.Common") AddReference("QuantConnect.Algorithm") from System import * from QuantConnect import * from QuantConnect.Algorithm import QCAlgorithm from QuantConnect.Data.UniverseSelection import * ### <summary> ### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks. ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="universes" /> ### <meta name="tag" content="coarse universes" /> ### <meta name="tag" content="fine universes" /> class CoarseFundamentalTop3Algorithm(QCAlgorithm): def Initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.SetStartDate(2014,3,24) #Set Start Date self.SetEndDate(2014,4,7) #Set End Date self.SetCash(50000) #Set Strategy Cash # what resolution should the data *added* to the universe be? self.UniverseSettings.Resolution = Resolution.Daily # this add universe method accepts a single parameter that is a function that # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol> self.AddUniverse(self.CoarseSelectionFunction) self.__numberOfSymbols = 3 self._changes = None # sort the data by daily dollar volume and take the top 'NumberOfSymbols' def CoarseSelectionFunction(self, coarse): # sort descending by daily dollar volume so
def OnData(self, data): self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}") # if we have no changes, do nothing if self._changes is None: return # liquidate removed securities for security in self._changes.RemovedSecurities: if security.Invested: self.Liquidate(security.Symbol) # we want 1/N allocation in each security in our universe for security in self._changes.AddedSecurities: self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols) self._changes = None # this event fires whenever we have changes to our universe def OnSecuritiesChanged(self, changes): self._changes = changes self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}") def OnOrderEvent(self, fill): self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}")
rtedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True) # return the symbol objects of the top entries from our sorted collection return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]
identifier_body
CoarseFundamentalTop3Algorithm.py
ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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. from clr import AddReference AddReference("System.Core") AddReference("QuantConnect.Common") AddReference("QuantConnect.Algorithm") from System import * from QuantConnect import * from QuantConnect.Algorithm import QCAlgorithm from QuantConnect.Data.UniverseSelection import * ### <summary> ### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks. ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="universes" /> ### <meta name="tag" content="coarse universes" /> ### <meta name="tag" content="fine universes" /> class Co
CAlgorithm): def Initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.SetStartDate(2014,3,24) #Set Start Date self.SetEndDate(2014,4,7) #Set End Date self.SetCash(50000) #Set Strategy Cash # what resolution should the data *added* to the universe be? self.UniverseSettings.Resolution = Resolution.Daily # this add universe method accepts a single parameter that is a function that # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol> self.AddUniverse(self.CoarseSelectionFunction) self.__numberOfSymbols = 3 self._changes = None # sort the data by daily dollar volume and take the top 'NumberOfSymbols' def CoarseSelectionFunction(self, coarse): # sort descending by daily dollar volume sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True) # return the symbol objects of the top entries from our sorted collection return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ] def OnData(self, data): self.Log(f"OnData({self.UtcTime}): Keys: {', '.join([key.Value for key in data.Keys])}") # if we have no changes, do nothing if self._changes is None: return # liquidate removed securities for security in self._changes.RemovedSecurities: if security.Invested: self.Liquidate(security.Symbol) # we want 1/N allocation in each security in our universe for security in self._changes.AddedSecurities: self.SetHoldings(security.Symbol, 1 / self.__numberOfSymbols) self._changes = None # this event fires whenever we have changes to our universe def OnSecuritiesChanged(self, changes): self._changes = changes self.Log(f"OnSecuritiesChanged({self.UtcTime}):: {changes}") def OnOrderEvent(self, fill): self.Log(f"OnOrderEvent({self.UtcTime}):: {fill}")
arseFundamentalTop3Algorithm(Q
identifier_name
import_ie_naptan_xml.py
"""Import an Irish NaPTAN XML file, obtainable from https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345 """ import warnings import zipfile import xml.etree.cElementTree as ET from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from ...models import Locality, AdminArea, StopPoint class Command(BaseCommand): ns = {'naptan': 'http://www.naptan.org.uk/'} @staticmethod def add_arguments(parser): parser.add_argument('filenames', nargs='+', type=str) def handle_stop(self, element): stop = StopPoint( atco_code=element.find('naptan:AtcoCode', self.ns).text, locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true', active=element.get('Status') == 'active', ) for subelement in element.find('naptan:Descriptor', self.ns): tag = subelement.tag[27:] if tag == 'CommonName': stop.common_name = subelement.text elif tag == 'Street': stop.street = subelement.text elif tag == 'Indicator': stop.indicator = subelement.text.lower() else:
stop_classification_element = element.find('naptan:StopClassification', self.ns) stop_type = stop_classification_element.find('naptan:StopType', self.ns).text if stop_type != 'class_undefined': stop.stop_type = stop_type bus_element = stop_classification_element.find('naptan:OnStreet/naptan:Bus', self.ns) if bus_element is not None: stop.bus_stop_type = bus_element.find('naptan:BusStopType', self.ns).text stop.timing_status = bus_element.find('naptan:TimingStatus', self.ns).text compass_point_element = bus_element.find( 'naptan:MarkedPoint/naptan:Bearing/naptan:CompassPoint', self.ns ) if compass_point_element is not None: stop.bearing = compass_point_element.text if stop.bus_stop_type == 'type_undefined': stop.bus_stop_type = '' place_element = element.find('naptan:Place', self.ns) location_element = place_element.find('naptan:Location', self.ns) longitude_element = location_element.find('naptan:Longitude', self.ns) latitude_element = location_element.find('naptan:Latitude', self.ns) if longitude_element is None: warnings.warn('Stop {} has no location'.format(stop.atco_code)) else: stop.latlong = Point(float(longitude_element.text), float(latitude_element.text)) admin_area_id = element.find('naptan:AdministrativeAreaRef', self.ns).text if not AdminArea.objects.filter(atco_code=admin_area_id).exists(): AdminArea.objects.create(id=admin_area_id, atco_code=admin_area_id, region_id='NI') stop.admin_area_id = admin_area_id locality_element = place_element.find('naptan:NptgLocalityRef', self.ns) if locality_element is not None: if not Locality.objects.filter(id=locality_element.text).exists(): Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id) stop.locality_id = locality_element.text stop.save() def handle_file(self, archive, filename): with archive.open(filename) as open_file: iterator = ET.iterparse(open_file) for _, element in iterator: tag = element.tag[27:] if tag == 'StopPoint': self.handle_stop(element) element.clear() def handle(self, *args, **options): for filename in options['filenames']: with zipfile.ZipFile(filename) as archive: for filename in archive.namelist(): self.handle_file(archive, filename)
warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag))
conditional_block
import_ie_naptan_xml.py
"""Import an Irish NaPTAN XML file, obtainable from https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345 """ import warnings import zipfile import xml.etree.cElementTree as ET from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from ...models import Locality, AdminArea, StopPoint class Command(BaseCommand): ns = {'naptan': 'http://www.naptan.org.uk/'} @staticmethod def add_arguments(parser): parser.add_argument('filenames', nargs='+', type=str) def handle_stop(self, element):
locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true', active=element.get('Status') == 'active', ) for subelement in element.find('naptan:Descriptor', self.ns): tag = subelement.tag[27:] if tag == 'CommonName': stop.common_name = subelement.text elif tag == 'Street': stop.street = subelement.text elif tag == 'Indicator': stop.indicator = subelement.text.lower() else: warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag)) stop_classification_element = element.find('naptan:StopClassification', self.ns) stop_type = stop_classification_element.find('naptan:StopType', self.ns).text if stop_type != 'class_undefined': stop.stop_type = stop_type bus_element = stop_classification_element.find('naptan:OnStreet/naptan:Bus', self.ns) if bus_element is not None: stop.bus_stop_type = bus_element.find('naptan:BusStopType', self.ns).text stop.timing_status = bus_element.find('naptan:TimingStatus', self.ns).text compass_point_element = bus_element.find( 'naptan:MarkedPoint/naptan:Bearing/naptan:CompassPoint', self.ns ) if compass_point_element is not None: stop.bearing = compass_point_element.text if stop.bus_stop_type == 'type_undefined': stop.bus_stop_type = '' place_element = element.find('naptan:Place', self.ns) location_element = place_element.find('naptan:Location', self.ns) longitude_element = location_element.find('naptan:Longitude', self.ns) latitude_element = location_element.find('naptan:Latitude', self.ns) if longitude_element is None: warnings.warn('Stop {} has no location'.format(stop.atco_code)) else: stop.latlong = Point(float(longitude_element.text), float(latitude_element.text)) admin_area_id = element.find('naptan:AdministrativeAreaRef', self.ns).text if not AdminArea.objects.filter(atco_code=admin_area_id).exists(): AdminArea.objects.create(id=admin_area_id, atco_code=admin_area_id, region_id='NI') stop.admin_area_id = admin_area_id locality_element = place_element.find('naptan:NptgLocalityRef', self.ns) if locality_element is not None: if not Locality.objects.filter(id=locality_element.text).exists(): Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id) stop.locality_id = locality_element.text stop.save() def handle_file(self, archive, filename): with archive.open(filename) as open_file: iterator = ET.iterparse(open_file) for _, element in iterator: tag = element.tag[27:] if tag == 'StopPoint': self.handle_stop(element) element.clear() def handle(self, *args, **options): for filename in options['filenames']: with zipfile.ZipFile(filename) as archive: for filename in archive.namelist(): self.handle_file(archive, filename)
stop = StopPoint( atco_code=element.find('naptan:AtcoCode', self.ns).text,
random_line_split
import_ie_naptan_xml.py
"""Import an Irish NaPTAN XML file, obtainable from https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345 """ import warnings import zipfile import xml.etree.cElementTree as ET from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from ...models import Locality, AdminArea, StopPoint class Command(BaseCommand): ns = {'naptan': 'http://www.naptan.org.uk/'} @staticmethod def add_arguments(parser): parser.add_argument('filenames', nargs='+', type=str) def handle_stop(self, element):
def handle_file(self, archive, filename): with archive.open(filename) as open_file: iterator = ET.iterparse(open_file) for _, element in iterator: tag = element.tag[27:] if tag == 'StopPoint': self.handle_stop(element) element.clear() def handle(self, *args, **options): for filename in options['filenames']: with zipfile.ZipFile(filename) as archive: for filename in archive.namelist(): self.handle_file(archive, filename)
stop = StopPoint( atco_code=element.find('naptan:AtcoCode', self.ns).text, locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true', active=element.get('Status') == 'active', ) for subelement in element.find('naptan:Descriptor', self.ns): tag = subelement.tag[27:] if tag == 'CommonName': stop.common_name = subelement.text elif tag == 'Street': stop.street = subelement.text elif tag == 'Indicator': stop.indicator = subelement.text.lower() else: warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag)) stop_classification_element = element.find('naptan:StopClassification', self.ns) stop_type = stop_classification_element.find('naptan:StopType', self.ns).text if stop_type != 'class_undefined': stop.stop_type = stop_type bus_element = stop_classification_element.find('naptan:OnStreet/naptan:Bus', self.ns) if bus_element is not None: stop.bus_stop_type = bus_element.find('naptan:BusStopType', self.ns).text stop.timing_status = bus_element.find('naptan:TimingStatus', self.ns).text compass_point_element = bus_element.find( 'naptan:MarkedPoint/naptan:Bearing/naptan:CompassPoint', self.ns ) if compass_point_element is not None: stop.bearing = compass_point_element.text if stop.bus_stop_type == 'type_undefined': stop.bus_stop_type = '' place_element = element.find('naptan:Place', self.ns) location_element = place_element.find('naptan:Location', self.ns) longitude_element = location_element.find('naptan:Longitude', self.ns) latitude_element = location_element.find('naptan:Latitude', self.ns) if longitude_element is None: warnings.warn('Stop {} has no location'.format(stop.atco_code)) else: stop.latlong = Point(float(longitude_element.text), float(latitude_element.text)) admin_area_id = element.find('naptan:AdministrativeAreaRef', self.ns).text if not AdminArea.objects.filter(atco_code=admin_area_id).exists(): AdminArea.objects.create(id=admin_area_id, atco_code=admin_area_id, region_id='NI') stop.admin_area_id = admin_area_id locality_element = place_element.find('naptan:NptgLocalityRef', self.ns) if locality_element is not None: if not Locality.objects.filter(id=locality_element.text).exists(): Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id) stop.locality_id = locality_element.text stop.save()
identifier_body
import_ie_naptan_xml.py
"""Import an Irish NaPTAN XML file, obtainable from https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345 """ import warnings import zipfile import xml.etree.cElementTree as ET from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from ...models import Locality, AdminArea, StopPoint class Command(BaseCommand): ns = {'naptan': 'http://www.naptan.org.uk/'} @staticmethod def
(parser): parser.add_argument('filenames', nargs='+', type=str) def handle_stop(self, element): stop = StopPoint( atco_code=element.find('naptan:AtcoCode', self.ns).text, locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true', active=element.get('Status') == 'active', ) for subelement in element.find('naptan:Descriptor', self.ns): tag = subelement.tag[27:] if tag == 'CommonName': stop.common_name = subelement.text elif tag == 'Street': stop.street = subelement.text elif tag == 'Indicator': stop.indicator = subelement.text.lower() else: warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag)) stop_classification_element = element.find('naptan:StopClassification', self.ns) stop_type = stop_classification_element.find('naptan:StopType', self.ns).text if stop_type != 'class_undefined': stop.stop_type = stop_type bus_element = stop_classification_element.find('naptan:OnStreet/naptan:Bus', self.ns) if bus_element is not None: stop.bus_stop_type = bus_element.find('naptan:BusStopType', self.ns).text stop.timing_status = bus_element.find('naptan:TimingStatus', self.ns).text compass_point_element = bus_element.find( 'naptan:MarkedPoint/naptan:Bearing/naptan:CompassPoint', self.ns ) if compass_point_element is not None: stop.bearing = compass_point_element.text if stop.bus_stop_type == 'type_undefined': stop.bus_stop_type = '' place_element = element.find('naptan:Place', self.ns) location_element = place_element.find('naptan:Location', self.ns) longitude_element = location_element.find('naptan:Longitude', self.ns) latitude_element = location_element.find('naptan:Latitude', self.ns) if longitude_element is None: warnings.warn('Stop {} has no location'.format(stop.atco_code)) else: stop.latlong = Point(float(longitude_element.text), float(latitude_element.text)) admin_area_id = element.find('naptan:AdministrativeAreaRef', self.ns).text if not AdminArea.objects.filter(atco_code=admin_area_id).exists(): AdminArea.objects.create(id=admin_area_id, atco_code=admin_area_id, region_id='NI') stop.admin_area_id = admin_area_id locality_element = place_element.find('naptan:NptgLocalityRef', self.ns) if locality_element is not None: if not Locality.objects.filter(id=locality_element.text).exists(): Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id) stop.locality_id = locality_element.text stop.save() def handle_file(self, archive, filename): with archive.open(filename) as open_file: iterator = ET.iterparse(open_file) for _, element in iterator: tag = element.tag[27:] if tag == 'StopPoint': self.handle_stop(element) element.clear() def handle(self, *args, **options): for filename in options['filenames']: with zipfile.ZipFile(filename) as archive: for filename in archive.namelist(): self.handle_file(archive, filename)
add_arguments
identifier_name
conftest.py
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' # Test instance listens on port 13095 instead of the default 13085, # to make it easier to run tests while also testing Turq manually. # Of course, ideally it should be a random free port instead. self.mock_port = 13095 self.editor_port = 13096 self.password = '' self.extra_args = [] self.wait = True self._process = None self.console_output = None def __enter__(self): args = [sys.executable, '-m', 'turq.main', '--bind', self.host, '--mock-port', str(self.mock_port), '--editor-port', str(self.editor_port)] if self.password is not None: args += ['--editor-password', self.password] args += self.extra_args self._process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if self.wait: self._wait_for_server() return self def __exit__(self, exc_type, exc_value, traceback): self._process.terminate() self._process.wait() self.console_output = self._process.stderr.read().decode() return False def _wait_for_server(self, timeout=3): # Wait until the mock server starts accepting connections, # but no more than `timeout` seconds. t0 = time.monotonic() while time.monotonic() - t0 < timeout: time.sleep(0.1)
return except OSError: pass raise RuntimeError('Turq failed to start') def connect(self): return socket.create_connection((self.host, self.mock_port), timeout=5) def connect_editor(self): return socket.create_connection((self.host, self.editor_port), timeout=5) def send(self, *events): hconn = h11.Connection(our_role=h11.CLIENT) with self.connect() as sock: for event in events: sock.sendall(hconn.send(event)) sock.shutdown(socket.SHUT_WR) while hconn.their_state is not h11.CLOSED: event = hconn.next_event() if event is h11.NEED_DATA: hconn.receive_data(sock.recv(4096)) elif not isinstance(event, h11.ConnectionClosed): yield event def request(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url) return requests.request(method, full_url, **kwargs) def request_editor(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url) return requests.request(method, full_url, **kwargs)
try: self.connect().close() self.connect_editor().close()
random_line_split
conftest.py
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' # Test instance listens on port 13095 instead of the default 13085, # to make it easier to run tests while also testing Turq manually. # Of course, ideally it should be a random free port instead. self.mock_port = 13095 self.editor_port = 13096 self.password = '' self.extra_args = [] self.wait = True self._process = None self.console_output = None def __enter__(self): args = [sys.executable, '-m', 'turq.main', '--bind', self.host, '--mock-port', str(self.mock_port), '--editor-port', str(self.editor_port)] if self.password is not None: args += ['--editor-password', self.password] args += self.extra_args self._process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if self.wait: self._wait_for_server() return self def __exit__(self, exc_type, exc_value, traceback): self._process.terminate() self._process.wait() self.console_output = self._process.stderr.read().decode() return False def _wait_for_server(self, timeout=3): # Wait until the mock server starts accepting connections, # but no more than `timeout` seconds. t0 = time.monotonic() while time.monotonic() - t0 < timeout: time.sleep(0.1) try: self.connect().close() self.connect_editor().close() return except OSError: pass raise RuntimeError('Turq failed to start') def connect(self): return socket.create_connection((self.host, self.mock_port), timeout=5) def connect_editor(self): return socket.create_connection((self.host, self.editor_port), timeout=5) def send(self, *events): hconn = h11.Connection(our_role=h11.CLIENT) with self.connect() as sock: for event in events: sock.sendall(hconn.send(event)) sock.shutdown(socket.SHUT_WR) while hconn.their_state is not h11.CLOSED: event = hconn.next_event() if event is h11.NEED_DATA: hconn.receive_data(sock.recv(4096)) elif not isinstance(event, h11.ConnectionClosed):
def request(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url) return requests.request(method, full_url, **kwargs) def request_editor(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url) return requests.request(method, full_url, **kwargs)
yield event
conditional_block
conftest.py
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' # Test instance listens on port 13095 instead of the default 13085, # to make it easier to run tests while also testing Turq manually. # Of course, ideally it should be a random free port instead. self.mock_port = 13095 self.editor_port = 13096 self.password = '' self.extra_args = [] self.wait = True self._process = None self.console_output = None def __enter__(self): args = [sys.executable, '-m', 'turq.main', '--bind', self.host, '--mock-port', str(self.mock_port), '--editor-port', str(self.editor_port)] if self.password is not None: args += ['--editor-password', self.password] args += self.extra_args self._process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if self.wait: self._wait_for_server() return self def __exit__(self, exc_type, exc_value, traceback): self._process.terminate() self._process.wait() self.console_output = self._process.stderr.read().decode() return False def _wait_for_server(self, timeout=3): # Wait until the mock server starts accepting connections, # but no more than `timeout` seconds. t0 = time.monotonic() while time.monotonic() - t0 < timeout: time.sleep(0.1) try: self.connect().close() self.connect_editor().close() return except OSError: pass raise RuntimeError('Turq failed to start') def connect(self): return socket.create_connection((self.host, self.mock_port), timeout=5) def connect_editor(self):
def send(self, *events): hconn = h11.Connection(our_role=h11.CLIENT) with self.connect() as sock: for event in events: sock.sendall(hconn.send(event)) sock.shutdown(socket.SHUT_WR) while hconn.their_state is not h11.CLOSED: event = hconn.next_event() if event is h11.NEED_DATA: hconn.receive_data(sock.recv(4096)) elif not isinstance(event, h11.ConnectionClosed): yield event def request(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url) return requests.request(method, full_url, **kwargs) def request_editor(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url) return requests.request(method, full_url, **kwargs)
return socket.create_connection((self.host, self.editor_port), timeout=5)
identifier_body
conftest.py
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' # Test instance listens on port 13095 instead of the default 13085, # to make it easier to run tests while also testing Turq manually. # Of course, ideally it should be a random free port instead. self.mock_port = 13095 self.editor_port = 13096 self.password = '' self.extra_args = [] self.wait = True self._process = None self.console_output = None def __enter__(self): args = [sys.executable, '-m', 'turq.main', '--bind', self.host, '--mock-port', str(self.mock_port), '--editor-port', str(self.editor_port)] if self.password is not None: args += ['--editor-password', self.password] args += self.extra_args self._process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if self.wait: self._wait_for_server() return self def __exit__(self, exc_type, exc_value, traceback): self._process.terminate() self._process.wait() self.console_output = self._process.stderr.read().decode() return False def _wait_for_server(self, timeout=3): # Wait until the mock server starts accepting connections, # but no more than `timeout` seconds. t0 = time.monotonic() while time.monotonic() - t0 < timeout: time.sleep(0.1) try: self.connect().close() self.connect_editor().close() return except OSError: pass raise RuntimeError('Turq failed to start') def connect(self): return socket.create_connection((self.host, self.mock_port), timeout=5) def connect_editor(self): return socket.create_connection((self.host, self.editor_port), timeout=5) def send(self, *events): hconn = h11.Connection(our_role=h11.CLIENT) with self.connect() as sock: for event in events: sock.sendall(hconn.send(event)) sock.shutdown(socket.SHUT_WR) while hconn.their_state is not h11.CLOSED: event = hconn.next_event() if event is h11.NEED_DATA: hconn.receive_data(sock.recv(4096)) elif not isinstance(event, h11.ConnectionClosed): yield event def
(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.mock_port, url) return requests.request(method, full_url, **kwargs) def request_editor(self, method, url, **kwargs): full_url = 'http://%s:%d%s' % (self.host, self.editor_port, url) return requests.request(method, full_url, **kwargs)
request
identifier_name
aixc++.py
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') return SCons.Platform.aix.get_xlc(env, xlc, packages) def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, version = get_xlc(env) if path and _cxx: _cxx = os.path.join(path, _cxx) if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version def exists(env):
# Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
path, _cxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None
identifier_body
aixc++.py
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') return SCons.Platform.aix.get_xlc(env, xlc, packages) def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, version = get_xlc(env) if path and _cxx: _cxx = os.path.join(path, _cxx) if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version def exists(env): path, _cxx, version = get_xlc(env) if path and _cxx:
xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
random_line_split
aixc++.py
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') return SCons.Platform.aix.get_xlc(env, xlc, packages) def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, version = get_xlc(env) if path and _cxx:
if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version def exists(env): path, _cxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
_cxx = os.path.join(path, _cxx)
conditional_block
aixc++.py
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') return SCons.Platform.aix.get_xlc(env, xlc, packages) def
(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, version = get_xlc(env) if path and _cxx: _cxx = os.path.join(path, _cxx) if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version def exists(env): path, _cxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
generate
identifier_name
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Enumerate; struct
<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn enumerate(self) -> Enumerate<Self> where Self: Sized { // Enumerate { iter: self, count: 0 } // } // fn count(self) -> usize where Self: Sized { // // Might overflow. // self.fold(0, |cnt, _| cnt + 1) // } } } } type T = i32; Iterator_impl!(T); // impl<I> Iterator for Enumerate<I> where I: Iterator { // type Item = (usize, <I as Iterator>::Item); // // /// # Overflow Behavior // /// // /// The method does no guarding against overflows, so enumerating more than // /// `usize::MAX` elements either produces the wrong result or panics. If // /// debug assertions are enabled, a panic is guaranteed. // /// // /// # Panics // /// // /// Might panic if the index of the element overflows a `usize`. // #[inline] // fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> { // self.iter.next().map(|a| { // let ret = (self.count, a); // // Possible undefined overflow. // self.count += 1; // ret // }) // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // self.iter.size_hint() // } // // #[inline] // fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> { // self.iter.nth(n).map(|a| { // let i = self.count + n; // self.count = i + 1; // (i, a) // }) // } // // #[inline] // fn count(self) -> usize { // self.iter.count() // } // } #[test] fn count_test1() { let a: A<T> = A { begin: 10, end: 20 }; let enumerate: Enumerate<A<T>> = a.enumerate(); assert_eq!(enumerate.count(), 10); } #[test] fn count_test2() { let a: A<T> = A { begin: 10, end: 20 }; let mut enumerate: Enumerate<A<T>> = a.enumerate(); enumerate.next(); assert_eq!(enumerate.count(), 9); } }
A
identifier_name
count.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::Enumerate; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } // fn enumerate(self) -> Enumerate<Self> where Self: Sized { // Enumerate { iter: self, count: 0 } // } // fn count(self) -> usize where Self: Sized { // // Might overflow. // self.fold(0, |cnt, _| cnt + 1) // } } } } type T = i32; Iterator_impl!(T); // impl<I> Iterator for Enumerate<I> where I: Iterator { // type Item = (usize, <I as Iterator>::Item); // // /// # Overflow Behavior // /// // /// The method does no guarding against overflows, so enumerating more than // /// `usize::MAX` elements either produces the wrong result or panics. If // /// debug assertions are enabled, a panic is guaranteed. // /// // /// # Panics // /// // /// Might panic if the index of the element overflows a `usize`. // #[inline] // fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> { // self.iter.next().map(|a| { // let ret = (self.count, a); // // Possible undefined overflow. // self.count += 1; // ret // }) // } // // #[inline] // fn size_hint(&self) -> (usize, Option<usize>) { // self.iter.size_hint() // } // // #[inline] // fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> { // self.iter.nth(n).map(|a| {
// // #[inline] // fn count(self) -> usize { // self.iter.count() // } // } #[test] fn count_test1() { let a: A<T> = A { begin: 10, end: 20 }; let enumerate: Enumerate<A<T>> = a.enumerate(); assert_eq!(enumerate.count(), 10); } #[test] fn count_test2() { let a: A<T> = A { begin: 10, end: 20 }; let mut enumerate: Enumerate<A<T>> = a.enumerate(); enumerate.next(); assert_eq!(enumerate.count(), 9); } }
// let i = self.count + n; // self.count = i + 1; // (i, a) // }) // }
random_line_split
index.js
import { RequestHook, Selector } from 'testcafe'; import { resolve } from 'path'; const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise')); export default class CustomHook extends RequestHook { constructor (config) { super(null, config); this.pendingAjaxRequestIds = new Set(); this._hasAjaxRequests = false; } onRequest (event) { if (event.isAjax) { this.pendingAjaxRequestIds.add(event._requestInfo.requestId); this._hasAjaxRequests = true; } } onResponse (event)
get hasAjaxRequests () { return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests); } } const hook1 = new CustomHook(); const hook2 = new CustomHook({}); const hook3 = new CustomHook({ includeHeaders: true }); fixture `GH-4516` .page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`; test.requestHooks(hook1)('Without config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook1.hasAjaxRequests).ok() .expect(hook1.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook2)('With empty config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook2.hasAjaxRequests).ok() .expect(hook2.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook3)('With includeHeaders', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook3.hasAjaxRequests).ok() .expect(hook3.pendingAjaxRequestIds.size).eql(0); });
{ this.pendingAjaxRequestIds.delete(event.requestId); }
identifier_body
index.js
import { RequestHook, Selector } from 'testcafe'; import { resolve } from 'path'; const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise')); export default class CustomHook extends RequestHook { constructor (config) { super(null, config); this.pendingAjaxRequestIds = new Set(); this._hasAjaxRequests = false; } onRequest (event) { if (event.isAjax)
} onResponse (event) { this.pendingAjaxRequestIds.delete(event.requestId); } get hasAjaxRequests () { return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests); } } const hook1 = new CustomHook(); const hook2 = new CustomHook({}); const hook3 = new CustomHook({ includeHeaders: true }); fixture `GH-4516` .page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`; test.requestHooks(hook1)('Without config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook1.hasAjaxRequests).ok() .expect(hook1.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook2)('With empty config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook2.hasAjaxRequests).ok() .expect(hook2.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook3)('With includeHeaders', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook3.hasAjaxRequests).ok() .expect(hook3.pendingAjaxRequestIds.size).eql(0); });
{ this.pendingAjaxRequestIds.add(event._requestInfo.requestId); this._hasAjaxRequests = true; }
conditional_block
index.js
import { RequestHook, Selector } from 'testcafe'; import { resolve } from 'path'; const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise')); export default class CustomHook extends RequestHook { constructor (config) { super(null, config); this.pendingAjaxRequestIds = new Set(); this._hasAjaxRequests = false; } onRequest (event) { if (event.isAjax) { this.pendingAjaxRequestIds.add(event._requestInfo.requestId); this._hasAjaxRequests = true; } } onResponse (event) { this.pendingAjaxRequestIds.delete(event.requestId); } get
() { return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests); } } const hook1 = new CustomHook(); const hook2 = new CustomHook({}); const hook3 = new CustomHook({ includeHeaders: true }); fixture `GH-4516` .page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`; test.requestHooks(hook1)('Without config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook1.hasAjaxRequests).ok() .expect(hook1.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook2)('With empty config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook2.hasAjaxRequests).ok() .expect(hook2.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook3)('With includeHeaders', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook3.hasAjaxRequests).ok() .expect(hook3.pendingAjaxRequestIds.size).eql(0); });
hasAjaxRequests
identifier_name
index.js
import { RequestHook, Selector } from 'testcafe'; import { resolve } from 'path'; const ReExecutablePromise = require(resolve('./lib/utils/re-executable-promise')); export default class CustomHook extends RequestHook { constructor (config) { super(null, config); this.pendingAjaxRequestIds = new Set(); this._hasAjaxRequests = false; } onRequest (event) { if (event.isAjax) { this.pendingAjaxRequestIds.add(event._requestInfo.requestId); this._hasAjaxRequests = true; } } onResponse (event) { this.pendingAjaxRequestIds.delete(event.requestId); } get hasAjaxRequests () { return ReExecutablePromise.fromFn(async () => this._hasAjaxRequests); } } const hook1 = new CustomHook(); const hook2 = new CustomHook({}); const hook3 = new CustomHook({ includeHeaders: true }); fixture `GH-4516` .page `http://localhost:3000/fixtures/regression/gh-4516/pages/index.html`; test.requestHooks(hook1)('Without config', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook1.hasAjaxRequests).ok() .expect(hook1.pendingAjaxRequestIds.size).eql(0); });
.expect(Selector('#result').visible).ok() .expect(hook2.hasAjaxRequests).ok() .expect(hook2.pendingAjaxRequestIds.size).eql(0); }); test.requestHooks(hook3)('With includeHeaders', async t => { await t .expect(Selector('#result').visible).ok() .expect(hook3.hasAjaxRequests).ok() .expect(hook3.pendingAjaxRequestIds.size).eql(0); });
test.requestHooks(hook2)('With empty config', async t => { await t
random_line_split
zenjmx.py
#! /usr/bin/env python ############################################################################## # # Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # ############################################################################## __doc__ = """Monitor Java Management eXtension (JMX) mbeans Dispatches calls to a java server process to collect JMX values for a device. """ import logging import sys import os import socket import Globals import zope from twisted.internet.defer import Deferred from twisted.web import xmlrpc from twisted.internet.protocol import ProcessProtocol from twisted.internet import defer, reactor, error from Products.ZenCollector.daemon import CollectorDaemon from Products.ZenCollector.interfaces import ICollectorPreferences,\ IDataService,\ IEventService,\ IScheduledTask from Products.ZenCollector.tasks import SimpleTaskFactory,\ SimpleTaskSplitter,\ TaskStates from Products.ZenEvents import Event from Products.ZenHub.XmlRpcService import XmlRpcService from Products.ZenUtils.NJobs import NJobs from Products.ZenUtils.Utils import unused from Products.ZenUtils.observable import ObservableMixin import ZenPacks.zenoss.ZenJMX from ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService import JMXDataSourceConfig unused(JMXDataSourceConfig) log = logging.getLogger( "zen.zenjmx" ) DEFAULT_HEARTBEAT_TIME = 5 * 60 WARNING_EVENT = dict(eventClass='/Status/JMX', component='JMX', device=socket.getfqdn(), severity=Event.Warning) class ZenJMXPreferences(object): """ Configuration values for the zenjmx daemon. """ zope.interface.implements(ICollectorPreferences) def __init__(self): """ Construct a new ZenJMXPreferences instance and provide default values for needed attributes. """ self.collectorName = "zenjmx" self.defaultRRDCreateCommand = None self.cycleInterval = 5 * 60 # seconds self.configCycleInterval = 20 # minutes self.options = None # the configurationService attribute is the fully qualified class-name # of our configuration service that runs within ZenHub self.configurationService = 'ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService' def buildOptions(self, parser): parser.add_option('-j','--zenjmxjavaport', dest='zenjmxjavaport', default=9988, type='int', help='Port for zenjmxjava process; default 9988. '+\ 'Tries 5 consecutive ports if there is a conflict', ) parser.add_option('--concurrentJMXCalls', dest='concurrentJMXCalls', action='store_true', default=False, help='Enable concurrent calls to a JMX server' ) parser.add_option('--parallel', dest='parallel', default=200, type='int', help='Number of devices to collect from at one time' ) parser.add_option('--cycleInterval', dest='cycleInterval', default=300, type='int', help='Cycle time, in seconds, to run collection' ) parser.add_option('--portRange', dest='portRange', default=5, type='int', help='Number of ports to attempt when starting' + 'Java jmx client') parser.add_option('--javaheap', dest="maxHeap",type="int", default=512, help="Max heap, in MB, to use for java process") def postStartup(self): pass def getJavaClientArgs(self): args = None if self.options.configfile: args = ('--configfile', self.options.configfile) if self.options.logseverity: args = args + ('-v', str(self.options.logseverity)) if self.options.concurrentJMXCalls: args = args + ('-concurrentJMXCalls', ) return args def getStartingPort(self): return self.options.zenjmxjavaport def getAttemptedPortRange(self): return self.options.portRange class IZenJMXJavaClient(zope.interface.Interface): listenPort = zope.interface.Attribute("listenPort") class ZenJMXJavaClientImpl(ProcessProtocol): """ Protocol to control the zenjmxjava process """ zope.interface.implements(IZenJMXJavaClient) def __init__( self, args, cycle=True, zenjmxjavaport=9988, maxHeap=512 ): """ Initializer @param args: argument list for zenjmx @type args: list of strings @param cycle: whether to run once or repeat @type cycle: boolean @param zenjmxjavaport: port on which java process will listen for queries @type zenjmxjavaport: int """ self.deferred = Deferred() self.stopCalled = False self.process = None self.outReceived = sys.stdout.write self.errReceived = sys.stderr.write self.log = logging.getLogger('zen.ZenJMXJavaClient') self.args = args self.cycle = cycle self.listenPort = zenjmxjavaport self._maxHeap = maxHeap self.restartEnabled = False self._eventService = zope.component.queryUtility(IEventService) self._preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') def processEnded(self, reason): """ Twisted reactor function called when the process ends. @param reason: message from the process @type reason: string """ self.process = None if not self.stopCalled: procEndEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava ended unexpectedly: %s'\ % reason.getErrorMessage(), 'severity': Event.Warning, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procEndEvent) self.log.warn('processEnded():zenjmxjava process ended %s' % reason) if self.deferred: msg = reason.getErrorMessage() exitCode = reason.value.exitCode if exitCode == 10: msg = 'Could not start up Java web server, '+\ 'possible port conflict' self.deferred.callback((exitCode,msg)) self.deferred = None elif self.restartEnabled: self.log.info('processEnded():restarting zenjmxjava') reactor.callLater(1, self.run) def stop(self): """ Twisted reactor function called when we are shutting down. """ import signal self.log.info('stop():stopping zenjmxjava') self.stopCalled = True if not self.process: self.log.debug('stop():no zenjmxjava process to stop') return try: self.process.signalProcess(signal.SIGKILL) except error.ProcessExitedAlready: self.log.info('stop():zenjmxjava process already exited') pass try: self.process.loseConnection() except Exception: pass self.process = None def connectionMade(self): """ Called when the Twisted reactor starts up """ self.log.debug('connectionMade():zenjmxjava started') def doCallback(): """ doCallback """ msg = \ 'doCallback(): callback on deferred zenjmxjava proc is up' self.log.debug(msg) if self.deferred: self.deferred.callback((True,'zenjmx java started')) if self.process: procStartEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava started', 'severity': Event.Clear, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procStartEvent) self.deferred = None if self.deferred: self.log.debug('connectionMade():scheduling callback') # give the java service a chance to startup reactor.callLater(3, doCallback) self.log.debug('connectionMade(): done') def run(self): """ Twisted function called when started """ if self.stopCalled: return self.log.info('run():starting zenjmxjava') zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir, 'zenjmxjava') if self.cycle: args = ('runjmxenabled', ) else: # don't want to start up with jmx server to avoid port conflicts args = ('run', ) args = args + ('-zenjmxjavaport', str(self.listenPort)) if self.args: args = args + self.args cmd = (zenjmxjavacmd, ) + args self.log.debug('run():spawn process %s' % (cmd, )) self.deferred = Deferred() env = dict(os.environ) env['JVM_MAX_HEAP'] = '-Xmx%sm'%self._maxHeap self.process = reactor.spawnProcess(self, zenjmxjavacmd, cmd, env=env) return self.deferred DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient' class ZenJMXJavaClientInitialization(object): """ Wrapper that continues to start the Java jmx client until successful. """ def __init__(self, registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME): """ @param registeredName: the name with which this client will be registered as a utility """ self._jmxClient = None self._clientName = registeredName def initialize(self): """ Begin the first attempt to start the Java jmx client. Note that this method returns a Deferred that relies on the ZenJMXPreferences being present when it is finally executed. This is meant to be the Deferred that is given to the CollectorDaemon for initialization before the first JMX task is scheduled. @return the deferred that represents the loading of preferences and the initial attempt to start the Java jmx client @rtype defer.Deferred """ def loadPrefs(): log.debug( "Retrieving java client startup args") preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') self._args = preferences.getJavaClientArgs() self._cycle = preferences.options.cycle self._maxHeap = preferences.options.maxHeap self._startingPort = preferences.getStartingPort() self._rpcPort = self._startingPort self._attemptedPortRange = preferences.getAttemptedPortRange() def printProblem(result): log.error( str(result) ) sys.exit(1) d = defer.maybeDeferred( loadPrefs ) d.addCallback( self._startJavaProc ) d.addErrback( printProblem ) return d def _tryClientOnCurrentPort( self ): """ Returns the Deferred for executing an attempt to start the java jmx client on the current port. """ log.debug( 'Attempting java client startup on port %s', self._rpcPort ) self._jmxClient = ZenJMXJavaClientImpl( self._args, self._cycle, self._rpcPort, self._maxHeap ) zope.component.provideUtility( self._jmxClient, IZenJMXJavaClient, self._clientName ) return self._jmxClient.run() def _startJavaProc( self, result=None ): """ Checks whether startup of the java jmx client was successful. If it was unsuccessful due to port conflict, increments the port and tries to start the client again. """ # If the result is not None, that means this was called as a callback # after an attempt to start the client if result is not None: # If result[0] is True, the client process started
# If there was no result passed in, then this is the first attempt # to start the client else: deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) return deferred class ZenJMXTask(ObservableMixin): """ The scheduled task for all the jmx datasources on an individual device. """ zope.interface.implements(IScheduledTask) def __init__(self, deviceId, taskName, scheduleIntervalSeconds, taskConfig, clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ): super( ZenJMXTask, self ).__init__() self.name = taskName self.configId = deviceId self.state = TaskStates.STATE_IDLE self._taskConfig = taskConfig self._manageIp = self._taskConfig.manageIp self._dataService = zope.component.queryUtility( IDataService ) self._eventService = zope.component.queryUtility( IEventService ) self._preferences = zope.component.queryUtility( ICollectorPreferences, 'zenjmx' ) self._client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) # At this time, do not use the interval passed from the device # configuration. Use the value pulled from the daemon # configuration. unused( scheduleIntervalSeconds ) self.interval = self._preferences.options.cycleInterval def createEvent(self, errorMap, component=None): """ Given an event dictionary, copy it and return the event @param errorMap: errorMap @type errorMap: s dictionarytring @param component: component name @type component: string @return: updated event @rtype: dictionary """ event = errorMap.copy() if component: event['component'] = component if event.get('datasourceId') and not event.get('eventKey'): event['eventKey'] = event.get('datasourceId') return event def sendEvent(self, event, **kw): self._eventService.sendEvent(event, **kw) def _collectJMX(self, dsConfigList): """ Call Java JMX process to collect JMX values @param dsConfigList: DataSource configuration @type dsConfigList: list of JMXDataSourceConfig @return: Twisted deferred object @rtype: Twisted deferred object """ def toDict(config): """ Marshall the fields from the datasource into a dictionary and ignore everything that is not a primitive @param config: dictionary of results @type config: string @return: results from remote device @rtype: dictionary """ vals = {} for (key, val) in config.__dict__.items(): if key != 'rrdConfig' and type(val)\ in XmlRpcService.PRIMITIVES: vals[key] = val rrdConfigs = config.rrdConfig.values() rrdConfigs.sort(lambda x, y: cmp(x.dataPointId, y.dataPointId)) vals['dps'] = [] vals['dptypes'] = [] for rrdConfig in rrdConfigs: vals['dps'].append(rrdConfig.dataPointId) vals['dptypes'].append(rrdConfig.rrdType) vals['connectionKey'] = config.getConnectionPropsKey() return vals def rpcCall(): """ Communicate with our local JMX process to collect results. This is a generator function @param driver: generator @type driver: string """ port = self._client.listenPort xmlRpcProxy = xmlrpc.Proxy('http://localhost:%s/' % port) d = xmlRpcProxy.callRemote('zenjmx.collect', configMaps) d.addCallbacks( processResults , processRpcError) return d def processRpcError(error): log.debug("Could not make XML RPC call for device %s; content of call: %s", self._taskConfig, configMaps) self.sendEvent({}, severity=Event.Error, eventClass='/Status/JMX', summary='unexpected error: %s' % error.getErrorMessage(), eventKey='unexpected_xmlrpc_error', device=self.configId) return error def processResults(jmxResults): """ Given the results from JMX, store them or send events. @param jmxResults: jmxResults @type jmxResults: string """ #Send clear for RPC error self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='unexpected error cleared', eventKey='unexpected_xmlrpc_error', device=self.configId) result = {} hasConnectionError = False hasUnexpectedError = False for result in jmxResults: log.debug("JMX result -> %s", result) evtSummary = result.get('summary') deviceId = result.get('device') evt = self.createEvent(result) if not evtSummary: rrdPath = result.get('rrdPath') dsId = result.get('datasourceId') dpId = result.get('dpId') value = result.get('value') try: self.storeRRD(deviceId, rrdPath, dsId, dpId, value) except ValueError: pass self.sendEvent(evt,summary="Clear",severity=Event.Clear) else: # send event log.debug('processResults(): ' + 'jmx error, sending event for %s' % result) if evt.get("eventClass", "") == '/Status/JMX/Connection': hasConnectionError = True if evt.get("eventKey", "") == 'unexpected_error': hasUnexpectedError = True self.sendEvent(evt, severity=Event.Error) if not hasConnectionError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX/Connection', summary='Connection is up', eventKey=connectionComponentKey, device=self.configId) if not hasUnexpectedError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='Unexpected error cleared', eventKey='unexpected_error', device=self.configId) return jmxResults connectionComponentKey = '' configMaps = [] for config in dsConfigList: connectionComponentKey = config.getConnectionPropsKey() configMaps.append(toDict(config)) log.info('collectJMX(): for %s %s' % (config.device, connectionComponentKey)) return rpcCall() def storeRRD( self, deviceId, rrdPath, dataSourceId, dataPointId, dpValue, ): """ Store a value into an RRD file @param deviceId: name of the remote device @type deviceId: string @param dataSourceId: name of the data source @type dataSourceId: string @param dataPointId: name of the data point @type dataPointId: string @param dpValue: dpValue @type dpValue: number """ deviceConfig = self._taskConfig dsConfig = deviceConfig.findDataSource(dataSourceId) if not dsConfig: log.info( 'No data source config found for device %s datasource %s' \ % (deviceId, dataSourceId)) return rrdConf = dsConfig.rrdConfig.get(dataPointId) type = rrdConf.rrdType if(type in ('COUNTER', 'DERIVE')): try: # cast to float first because long('100.0') will fail with a # ValueError dpValue = long(float(dpValue)) except (TypeError, ValueError): log.warning("value %s not valid for derive or counter data points", dpValue) else: try: dpValue = float(dpValue) except (TypeError, ValueError): log.warning("value %s not valid for data point", dpValue) if not rrdConf: log.info( 'No RRD config found for device %s datasource %s datapoint %s' \ % (deviceId, dataSourceId, dataPointId)) return dpPath = '/'.join((rrdPath, rrdConf.dpName)) min = rrdConf.min max = rrdConf.max self._dataService.writeRRD(dpPath, dpValue, rrdConf.rrdType, rrdConf.command, min=min, max=max) def _finished(self, results): for result in results: log.debug("Finished with result %s" % str( result ) ) return results def doTask(self): log.debug("Scanning device %s [%s]", self.configId, self._manageIp) d = self._collectCallback() d.addBoth(self._finished) # returning a Deferred will keep the framework from assuming the task # is done until the Deferred actually completes return d def _collectCallback(self): jobs = NJobs(self._preferences.options.parallel, self._collectJMX, self._taskConfig.jmxDataSourceConfigs.values()) deferred = jobs.start() return deferred def cleanup(self): pass def stopJavaJmxClients(): # Currently only starting/stopping one. clientName = DEFAULT_JMX_JAVA_CLIENT_NAME client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) if client is not None: log.debug( 'Shutting down JMX Java client %s' % clientName ) client.stop() if __name__ == '__main__': myPreferences = ZenJMXPreferences() initialization = ZenJMXJavaClientInitialization() myTaskFactory = SimpleTaskFactory(ZenJMXTask) myTaskSplitter = SimpleTaskSplitter(myTaskFactory) daemon = CollectorDaemon(myPreferences, myTaskSplitter, initializationCallback=initialization.initialize, stoppingCallback=stopJavaJmxClients) daemon.run()
if result[0] is True: log.debug( 'Java jmx client started' ) self._jmxClient.restartEnabled = True deferred = defer.succeed( True ) # If the result[0] is 10, there was a port conflict elif result[0] == 10: log.debug( 'Java client didn\'t start; port %s occupied', self._rpcPort ) if self._rpcPort < ( self._startingPort + self._attemptedPortRange ): self._rpcPort += 1 deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) else: raise RuntimeError( "ZenJMXJavaClient could not be started, check ports") else: #unknown error raise RuntimeError('ZenJMXJavaClient could not be started, '+\ 'check JVM type and version: %s' % result[1])
conditional_block
zenjmx.py
#! /usr/bin/env python ############################################################################## # # Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # ############################################################################## __doc__ = """Monitor Java Management eXtension (JMX) mbeans Dispatches calls to a java server process to collect JMX values for a device. """ import logging import sys import os import socket import Globals import zope from twisted.internet.defer import Deferred from twisted.web import xmlrpc from twisted.internet.protocol import ProcessProtocol from twisted.internet import defer, reactor, error from Products.ZenCollector.daemon import CollectorDaemon from Products.ZenCollector.interfaces import ICollectorPreferences,\ IDataService,\ IEventService,\ IScheduledTask from Products.ZenCollector.tasks import SimpleTaskFactory,\ SimpleTaskSplitter,\ TaskStates from Products.ZenEvents import Event from Products.ZenHub.XmlRpcService import XmlRpcService from Products.ZenUtils.NJobs import NJobs from Products.ZenUtils.Utils import unused from Products.ZenUtils.observable import ObservableMixin import ZenPacks.zenoss.ZenJMX from ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService import JMXDataSourceConfig unused(JMXDataSourceConfig) log = logging.getLogger( "zen.zenjmx" ) DEFAULT_HEARTBEAT_TIME = 5 * 60 WARNING_EVENT = dict(eventClass='/Status/JMX', component='JMX', device=socket.getfqdn(), severity=Event.Warning) class ZenJMXPreferences(object): """ Configuration values for the zenjmx daemon. """ zope.interface.implements(ICollectorPreferences) def __init__(self): """ Construct a new ZenJMXPreferences instance and provide default values for needed attributes. """ self.collectorName = "zenjmx" self.defaultRRDCreateCommand = None self.cycleInterval = 5 * 60 # seconds self.configCycleInterval = 20 # minutes self.options = None # the configurationService attribute is the fully qualified class-name # of our configuration service that runs within ZenHub self.configurationService = 'ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService' def buildOptions(self, parser): parser.add_option('-j','--zenjmxjavaport', dest='zenjmxjavaport', default=9988, type='int', help='Port for zenjmxjava process; default 9988. '+\ 'Tries 5 consecutive ports if there is a conflict', ) parser.add_option('--concurrentJMXCalls', dest='concurrentJMXCalls', action='store_true', default=False, help='Enable concurrent calls to a JMX server' ) parser.add_option('--parallel', dest='parallel', default=200, type='int', help='Number of devices to collect from at one time' ) parser.add_option('--cycleInterval', dest='cycleInterval', default=300, type='int', help='Cycle time, in seconds, to run collection' ) parser.add_option('--portRange', dest='portRange', default=5, type='int', help='Number of ports to attempt when starting' + 'Java jmx client') parser.add_option('--javaheap', dest="maxHeap",type="int", default=512, help="Max heap, in MB, to use for java process") def postStartup(self): pass def getJavaClientArgs(self): args = None if self.options.configfile: args = ('--configfile', self.options.configfile) if self.options.logseverity: args = args + ('-v', str(self.options.logseverity)) if self.options.concurrentJMXCalls: args = args + ('-concurrentJMXCalls', ) return args def getStartingPort(self): return self.options.zenjmxjavaport def getAttemptedPortRange(self): return self.options.portRange class IZenJMXJavaClient(zope.interface.Interface): listenPort = zope.interface.Attribute("listenPort") class ZenJMXJavaClientImpl(ProcessProtocol): """ Protocol to control the zenjmxjava process """ zope.interface.implements(IZenJMXJavaClient) def __init__( self, args, cycle=True, zenjmxjavaport=9988, maxHeap=512 ): """ Initializer @param args: argument list for zenjmx @type args: list of strings @param cycle: whether to run once or repeat @type cycle: boolean @param zenjmxjavaport: port on which java process will listen for queries @type zenjmxjavaport: int """ self.deferred = Deferred() self.stopCalled = False self.process = None self.outReceived = sys.stdout.write self.errReceived = sys.stderr.write self.log = logging.getLogger('zen.ZenJMXJavaClient') self.args = args self.cycle = cycle self.listenPort = zenjmxjavaport self._maxHeap = maxHeap self.restartEnabled = False self._eventService = zope.component.queryUtility(IEventService) self._preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') def processEnded(self, reason): """ Twisted reactor function called when the process ends. @param reason: message from the process @type reason: string """ self.process = None if not self.stopCalled: procEndEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava ended unexpectedly: %s'\ % reason.getErrorMessage(), 'severity': Event.Warning, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procEndEvent) self.log.warn('processEnded():zenjmxjava process ended %s' % reason) if self.deferred: msg = reason.getErrorMessage() exitCode = reason.value.exitCode if exitCode == 10: msg = 'Could not start up Java web server, '+\ 'possible port conflict' self.deferred.callback((exitCode,msg)) self.deferred = None elif self.restartEnabled: self.log.info('processEnded():restarting zenjmxjava') reactor.callLater(1, self.run) def stop(self): """ Twisted reactor function called when we are shutting down. """ import signal self.log.info('stop():stopping zenjmxjava') self.stopCalled = True if not self.process: self.log.debug('stop():no zenjmxjava process to stop') return try: self.process.signalProcess(signal.SIGKILL) except error.ProcessExitedAlready: self.log.info('stop():zenjmxjava process already exited') pass try: self.process.loseConnection() except Exception: pass self.process = None def connectionMade(self): """ Called when the Twisted reactor starts up """ self.log.debug('connectionMade():zenjmxjava started') def doCallback(): """ doCallback """ msg = \ 'doCallback(): callback on deferred zenjmxjava proc is up' self.log.debug(msg) if self.deferred: self.deferred.callback((True,'zenjmx java started')) if self.process: procStartEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava started', 'severity': Event.Clear, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procStartEvent) self.deferred = None if self.deferred: self.log.debug('connectionMade():scheduling callback') # give the java service a chance to startup reactor.callLater(3, doCallback) self.log.debug('connectionMade(): done') def run(self):
DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient' class ZenJMXJavaClientInitialization(object): """ Wrapper that continues to start the Java jmx client until successful. """ def __init__(self, registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME): """ @param registeredName: the name with which this client will be registered as a utility """ self._jmxClient = None self._clientName = registeredName def initialize(self): """ Begin the first attempt to start the Java jmx client. Note that this method returns a Deferred that relies on the ZenJMXPreferences being present when it is finally executed. This is meant to be the Deferred that is given to the CollectorDaemon for initialization before the first JMX task is scheduled. @return the deferred that represents the loading of preferences and the initial attempt to start the Java jmx client @rtype defer.Deferred """ def loadPrefs(): log.debug( "Retrieving java client startup args") preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') self._args = preferences.getJavaClientArgs() self._cycle = preferences.options.cycle self._maxHeap = preferences.options.maxHeap self._startingPort = preferences.getStartingPort() self._rpcPort = self._startingPort self._attemptedPortRange = preferences.getAttemptedPortRange() def printProblem(result): log.error( str(result) ) sys.exit(1) d = defer.maybeDeferred( loadPrefs ) d.addCallback( self._startJavaProc ) d.addErrback( printProblem ) return d def _tryClientOnCurrentPort( self ): """ Returns the Deferred for executing an attempt to start the java jmx client on the current port. """ log.debug( 'Attempting java client startup on port %s', self._rpcPort ) self._jmxClient = ZenJMXJavaClientImpl( self._args, self._cycle, self._rpcPort, self._maxHeap ) zope.component.provideUtility( self._jmxClient, IZenJMXJavaClient, self._clientName ) return self._jmxClient.run() def _startJavaProc( self, result=None ): """ Checks whether startup of the java jmx client was successful. If it was unsuccessful due to port conflict, increments the port and tries to start the client again. """ # If the result is not None, that means this was called as a callback # after an attempt to start the client if result is not None: # If result[0] is True, the client process started if result[0] is True: log.debug( 'Java jmx client started' ) self._jmxClient.restartEnabled = True deferred = defer.succeed( True ) # If the result[0] is 10, there was a port conflict elif result[0] == 10: log.debug( 'Java client didn\'t start; port %s occupied', self._rpcPort ) if self._rpcPort < ( self._startingPort + self._attemptedPortRange ): self._rpcPort += 1 deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) else: raise RuntimeError( "ZenJMXJavaClient could not be started, check ports") else: #unknown error raise RuntimeError('ZenJMXJavaClient could not be started, '+\ 'check JVM type and version: %s' % result[1]) # If there was no result passed in, then this is the first attempt # to start the client else: deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) return deferred class ZenJMXTask(ObservableMixin): """ The scheduled task for all the jmx datasources on an individual device. """ zope.interface.implements(IScheduledTask) def __init__(self, deviceId, taskName, scheduleIntervalSeconds, taskConfig, clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ): super( ZenJMXTask, self ).__init__() self.name = taskName self.configId = deviceId self.state = TaskStates.STATE_IDLE self._taskConfig = taskConfig self._manageIp = self._taskConfig.manageIp self._dataService = zope.component.queryUtility( IDataService ) self._eventService = zope.component.queryUtility( IEventService ) self._preferences = zope.component.queryUtility( ICollectorPreferences, 'zenjmx' ) self._client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) # At this time, do not use the interval passed from the device # configuration. Use the value pulled from the daemon # configuration. unused( scheduleIntervalSeconds ) self.interval = self._preferences.options.cycleInterval def createEvent(self, errorMap, component=None): """ Given an event dictionary, copy it and return the event @param errorMap: errorMap @type errorMap: s dictionarytring @param component: component name @type component: string @return: updated event @rtype: dictionary """ event = errorMap.copy() if component: event['component'] = component if event.get('datasourceId') and not event.get('eventKey'): event['eventKey'] = event.get('datasourceId') return event def sendEvent(self, event, **kw): self._eventService.sendEvent(event, **kw) def _collectJMX(self, dsConfigList): """ Call Java JMX process to collect JMX values @param dsConfigList: DataSource configuration @type dsConfigList: list of JMXDataSourceConfig @return: Twisted deferred object @rtype: Twisted deferred object """ def toDict(config): """ Marshall the fields from the datasource into a dictionary and ignore everything that is not a primitive @param config: dictionary of results @type config: string @return: results from remote device @rtype: dictionary """ vals = {} for (key, val) in config.__dict__.items(): if key != 'rrdConfig' and type(val)\ in XmlRpcService.PRIMITIVES: vals[key] = val rrdConfigs = config.rrdConfig.values() rrdConfigs.sort(lambda x, y: cmp(x.dataPointId, y.dataPointId)) vals['dps'] = [] vals['dptypes'] = [] for rrdConfig in rrdConfigs: vals['dps'].append(rrdConfig.dataPointId) vals['dptypes'].append(rrdConfig.rrdType) vals['connectionKey'] = config.getConnectionPropsKey() return vals def rpcCall(): """ Communicate with our local JMX process to collect results. This is a generator function @param driver: generator @type driver: string """ port = self._client.listenPort xmlRpcProxy = xmlrpc.Proxy('http://localhost:%s/' % port) d = xmlRpcProxy.callRemote('zenjmx.collect', configMaps) d.addCallbacks( processResults , processRpcError) return d def processRpcError(error): log.debug("Could not make XML RPC call for device %s; content of call: %s", self._taskConfig, configMaps) self.sendEvent({}, severity=Event.Error, eventClass='/Status/JMX', summary='unexpected error: %s' % error.getErrorMessage(), eventKey='unexpected_xmlrpc_error', device=self.configId) return error def processResults(jmxResults): """ Given the results from JMX, store them or send events. @param jmxResults: jmxResults @type jmxResults: string """ #Send clear for RPC error self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='unexpected error cleared', eventKey='unexpected_xmlrpc_error', device=self.configId) result = {} hasConnectionError = False hasUnexpectedError = False for result in jmxResults: log.debug("JMX result -> %s", result) evtSummary = result.get('summary') deviceId = result.get('device') evt = self.createEvent(result) if not evtSummary: rrdPath = result.get('rrdPath') dsId = result.get('datasourceId') dpId = result.get('dpId') value = result.get('value') try: self.storeRRD(deviceId, rrdPath, dsId, dpId, value) except ValueError: pass self.sendEvent(evt,summary="Clear",severity=Event.Clear) else: # send event log.debug('processResults(): ' + 'jmx error, sending event for %s' % result) if evt.get("eventClass", "") == '/Status/JMX/Connection': hasConnectionError = True if evt.get("eventKey", "") == 'unexpected_error': hasUnexpectedError = True self.sendEvent(evt, severity=Event.Error) if not hasConnectionError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX/Connection', summary='Connection is up', eventKey=connectionComponentKey, device=self.configId) if not hasUnexpectedError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='Unexpected error cleared', eventKey='unexpected_error', device=self.configId) return jmxResults connectionComponentKey = '' configMaps = [] for config in dsConfigList: connectionComponentKey = config.getConnectionPropsKey() configMaps.append(toDict(config)) log.info('collectJMX(): for %s %s' % (config.device, connectionComponentKey)) return rpcCall() def storeRRD( self, deviceId, rrdPath, dataSourceId, dataPointId, dpValue, ): """ Store a value into an RRD file @param deviceId: name of the remote device @type deviceId: string @param dataSourceId: name of the data source @type dataSourceId: string @param dataPointId: name of the data point @type dataPointId: string @param dpValue: dpValue @type dpValue: number """ deviceConfig = self._taskConfig dsConfig = deviceConfig.findDataSource(dataSourceId) if not dsConfig: log.info( 'No data source config found for device %s datasource %s' \ % (deviceId, dataSourceId)) return rrdConf = dsConfig.rrdConfig.get(dataPointId) type = rrdConf.rrdType if(type in ('COUNTER', 'DERIVE')): try: # cast to float first because long('100.0') will fail with a # ValueError dpValue = long(float(dpValue)) except (TypeError, ValueError): log.warning("value %s not valid for derive or counter data points", dpValue) else: try: dpValue = float(dpValue) except (TypeError, ValueError): log.warning("value %s not valid for data point", dpValue) if not rrdConf: log.info( 'No RRD config found for device %s datasource %s datapoint %s' \ % (deviceId, dataSourceId, dataPointId)) return dpPath = '/'.join((rrdPath, rrdConf.dpName)) min = rrdConf.min max = rrdConf.max self._dataService.writeRRD(dpPath, dpValue, rrdConf.rrdType, rrdConf.command, min=min, max=max) def _finished(self, results): for result in results: log.debug("Finished with result %s" % str( result ) ) return results def doTask(self): log.debug("Scanning device %s [%s]", self.configId, self._manageIp) d = self._collectCallback() d.addBoth(self._finished) # returning a Deferred will keep the framework from assuming the task # is done until the Deferred actually completes return d def _collectCallback(self): jobs = NJobs(self._preferences.options.parallel, self._collectJMX, self._taskConfig.jmxDataSourceConfigs.values()) deferred = jobs.start() return deferred def cleanup(self): pass def stopJavaJmxClients(): # Currently only starting/stopping one. clientName = DEFAULT_JMX_JAVA_CLIENT_NAME client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) if client is not None: log.debug( 'Shutting down JMX Java client %s' % clientName ) client.stop() if __name__ == '__main__': myPreferences = ZenJMXPreferences() initialization = ZenJMXJavaClientInitialization() myTaskFactory = SimpleTaskFactory(ZenJMXTask) myTaskSplitter = SimpleTaskSplitter(myTaskFactory) daemon = CollectorDaemon(myPreferences, myTaskSplitter, initializationCallback=initialization.initialize, stoppingCallback=stopJavaJmxClients) daemon.run()
""" Twisted function called when started """ if self.stopCalled: return self.log.info('run():starting zenjmxjava') zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir, 'zenjmxjava') if self.cycle: args = ('runjmxenabled', ) else: # don't want to start up with jmx server to avoid port conflicts args = ('run', ) args = args + ('-zenjmxjavaport', str(self.listenPort)) if self.args: args = args + self.args cmd = (zenjmxjavacmd, ) + args self.log.debug('run():spawn process %s' % (cmd, )) self.deferred = Deferred() env = dict(os.environ) env['JVM_MAX_HEAP'] = '-Xmx%sm'%self._maxHeap self.process = reactor.spawnProcess(self, zenjmxjavacmd, cmd, env=env) return self.deferred
identifier_body
zenjmx.py
#! /usr/bin/env python ############################################################################## # # Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # ############################################################################## __doc__ = """Monitor Java Management eXtension (JMX) mbeans Dispatches calls to a java server process to collect JMX values for a device. """ import logging import sys import os import socket import Globals import zope from twisted.internet.defer import Deferred from twisted.web import xmlrpc from twisted.internet.protocol import ProcessProtocol from twisted.internet import defer, reactor, error from Products.ZenCollector.daemon import CollectorDaemon from Products.ZenCollector.interfaces import ICollectorPreferences,\ IDataService,\ IEventService,\ IScheduledTask from Products.ZenCollector.tasks import SimpleTaskFactory,\ SimpleTaskSplitter,\ TaskStates from Products.ZenEvents import Event from Products.ZenHub.XmlRpcService import XmlRpcService from Products.ZenUtils.NJobs import NJobs from Products.ZenUtils.Utils import unused from Products.ZenUtils.observable import ObservableMixin import ZenPacks.zenoss.ZenJMX from ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService import JMXDataSourceConfig unused(JMXDataSourceConfig) log = logging.getLogger( "zen.zenjmx" ) DEFAULT_HEARTBEAT_TIME = 5 * 60 WARNING_EVENT = dict(eventClass='/Status/JMX', component='JMX', device=socket.getfqdn(), severity=Event.Warning) class ZenJMXPreferences(object): """ Configuration values for the zenjmx daemon. """ zope.interface.implements(ICollectorPreferences) def __init__(self): """ Construct a new ZenJMXPreferences instance and provide default values for needed attributes. """ self.collectorName = "zenjmx" self.defaultRRDCreateCommand = None self.cycleInterval = 5 * 60 # seconds self.configCycleInterval = 20 # minutes self.options = None # the configurationService attribute is the fully qualified class-name # of our configuration service that runs within ZenHub self.configurationService = 'ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService' def buildOptions(self, parser): parser.add_option('-j','--zenjmxjavaport', dest='zenjmxjavaport', default=9988, type='int', help='Port for zenjmxjava process; default 9988. '+\ 'Tries 5 consecutive ports if there is a conflict', ) parser.add_option('--concurrentJMXCalls', dest='concurrentJMXCalls', action='store_true', default=False, help='Enable concurrent calls to a JMX server' ) parser.add_option('--parallel', dest='parallel', default=200, type='int', help='Number of devices to collect from at one time' ) parser.add_option('--cycleInterval', dest='cycleInterval', default=300, type='int', help='Cycle time, in seconds, to run collection' ) parser.add_option('--portRange', dest='portRange', default=5, type='int', help='Number of ports to attempt when starting' + 'Java jmx client') parser.add_option('--javaheap', dest="maxHeap",type="int", default=512, help="Max heap, in MB, to use for java process") def postStartup(self): pass def getJavaClientArgs(self): args = None if self.options.configfile: args = ('--configfile', self.options.configfile) if self.options.logseverity: args = args + ('-v', str(self.options.logseverity)) if self.options.concurrentJMXCalls: args = args + ('-concurrentJMXCalls', ) return args def getStartingPort(self): return self.options.zenjmxjavaport def getAttemptedPortRange(self): return self.options.portRange class IZenJMXJavaClient(zope.interface.Interface): listenPort = zope.interface.Attribute("listenPort") class ZenJMXJavaClientImpl(ProcessProtocol): """ Protocol to control the zenjmxjava process """ zope.interface.implements(IZenJMXJavaClient) def __init__( self, args, cycle=True, zenjmxjavaport=9988, maxHeap=512 ): """ Initializer @param args: argument list for zenjmx @type args: list of strings @param cycle: whether to run once or repeat @type cycle: boolean @param zenjmxjavaport: port on which java process will listen for queries @type zenjmxjavaport: int """ self.deferred = Deferred() self.stopCalled = False self.process = None self.outReceived = sys.stdout.write self.errReceived = sys.stderr.write self.log = logging.getLogger('zen.ZenJMXJavaClient') self.args = args self.cycle = cycle self.listenPort = zenjmxjavaport self._maxHeap = maxHeap self.restartEnabled = False self._eventService = zope.component.queryUtility(IEventService) self._preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') def processEnded(self, reason): """ Twisted reactor function called when the process ends. @param reason: message from the process @type reason: string """ self.process = None if not self.stopCalled: procEndEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava ended unexpectedly: %s'\ % reason.getErrorMessage(), 'severity': Event.Warning, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procEndEvent) self.log.warn('processEnded():zenjmxjava process ended %s' % reason) if self.deferred: msg = reason.getErrorMessage() exitCode = reason.value.exitCode if exitCode == 10: msg = 'Could not start up Java web server, '+\ 'possible port conflict' self.deferred.callback((exitCode,msg)) self.deferred = None elif self.restartEnabled: self.log.info('processEnded():restarting zenjmxjava') reactor.callLater(1, self.run) def stop(self): """ Twisted reactor function called when we are shutting down. """ import signal self.log.info('stop():stopping zenjmxjava') self.stopCalled = True if not self.process: self.log.debug('stop():no zenjmxjava process to stop') return try: self.process.signalProcess(signal.SIGKILL) except error.ProcessExitedAlready: self.log.info('stop():zenjmxjava process already exited') pass try: self.process.loseConnection() except Exception: pass self.process = None def connectionMade(self): """ Called when the Twisted reactor starts up """ self.log.debug('connectionMade():zenjmxjava started') def doCallback(): """ doCallback """ msg = \ 'doCallback(): callback on deferred zenjmxjava proc is up' self.log.debug(msg) if self.deferred: self.deferred.callback((True,'zenjmx java started')) if self.process: procStartEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava started', 'severity': Event.Clear, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procStartEvent) self.deferred = None if self.deferred: self.log.debug('connectionMade():scheduling callback') # give the java service a chance to startup reactor.callLater(3, doCallback) self.log.debug('connectionMade(): done') def run(self): """ Twisted function called when started """ if self.stopCalled: return self.log.info('run():starting zenjmxjava') zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir, 'zenjmxjava') if self.cycle: args = ('runjmxenabled', ) else: # don't want to start up with jmx server to avoid port conflicts args = ('run', ) args = args + ('-zenjmxjavaport', str(self.listenPort)) if self.args: args = args + self.args cmd = (zenjmxjavacmd, ) + args self.log.debug('run():spawn process %s' % (cmd, )) self.deferred = Deferred() env = dict(os.environ) env['JVM_MAX_HEAP'] = '-Xmx%sm'%self._maxHeap self.process = reactor.spawnProcess(self, zenjmxjavacmd, cmd, env=env) return self.deferred DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient' class ZenJMXJavaClientInitialization(object): """ Wrapper that continues to start the Java jmx client until successful. """ def __init__(self, registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME): """ @param registeredName: the name with which this client will be registered as a utility """ self._jmxClient = None self._clientName = registeredName def initialize(self): """ Begin the first attempt to start the Java jmx client. Note that this method returns a Deferred that relies on the ZenJMXPreferences being present when it is finally executed. This is meant to be the Deferred that is given to the CollectorDaemon for initialization before the first JMX task is scheduled. @return the deferred that represents the loading of preferences and the initial attempt to start the Java jmx client @rtype defer.Deferred """ def loadPrefs(): log.debug( "Retrieving java client startup args") preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') self._args = preferences.getJavaClientArgs() self._cycle = preferences.options.cycle self._maxHeap = preferences.options.maxHeap self._startingPort = preferences.getStartingPort() self._rpcPort = self._startingPort self._attemptedPortRange = preferences.getAttemptedPortRange() def printProblem(result): log.error( str(result) ) sys.exit(1) d = defer.maybeDeferred( loadPrefs ) d.addCallback( self._startJavaProc ) d.addErrback( printProblem ) return d def _tryClientOnCurrentPort( self ): """ Returns the Deferred for executing an attempt to start the java jmx client on the current port. """ log.debug( 'Attempting java client startup on port %s', self._rpcPort ) self._jmxClient = ZenJMXJavaClientImpl( self._args, self._cycle, self._rpcPort, self._maxHeap ) zope.component.provideUtility( self._jmxClient, IZenJMXJavaClient, self._clientName ) return self._jmxClient.run() def _startJavaProc( self, result=None ): """ Checks whether startup of the java jmx client was successful. If it was unsuccessful due to port conflict, increments the port and tries to start the client again. """ # If the result is not None, that means this was called as a callback # after an attempt to start the client if result is not None: # If result[0] is True, the client process started if result[0] is True: log.debug( 'Java jmx client started' ) self._jmxClient.restartEnabled = True deferred = defer.succeed( True ) # If the result[0] is 10, there was a port conflict elif result[0] == 10: log.debug( 'Java client didn\'t start; port %s occupied', self._rpcPort ) if self._rpcPort < ( self._startingPort + self._attemptedPortRange ): self._rpcPort += 1 deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) else: raise RuntimeError( "ZenJMXJavaClient could not be started, check ports") else: #unknown error raise RuntimeError('ZenJMXJavaClient could not be started, '+\ 'check JVM type and version: %s' % result[1]) # If there was no result passed in, then this is the first attempt # to start the client else: deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) return deferred class
(ObservableMixin): """ The scheduled task for all the jmx datasources on an individual device. """ zope.interface.implements(IScheduledTask) def __init__(self, deviceId, taskName, scheduleIntervalSeconds, taskConfig, clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ): super( ZenJMXTask, self ).__init__() self.name = taskName self.configId = deviceId self.state = TaskStates.STATE_IDLE self._taskConfig = taskConfig self._manageIp = self._taskConfig.manageIp self._dataService = zope.component.queryUtility( IDataService ) self._eventService = zope.component.queryUtility( IEventService ) self._preferences = zope.component.queryUtility( ICollectorPreferences, 'zenjmx' ) self._client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) # At this time, do not use the interval passed from the device # configuration. Use the value pulled from the daemon # configuration. unused( scheduleIntervalSeconds ) self.interval = self._preferences.options.cycleInterval def createEvent(self, errorMap, component=None): """ Given an event dictionary, copy it and return the event @param errorMap: errorMap @type errorMap: s dictionarytring @param component: component name @type component: string @return: updated event @rtype: dictionary """ event = errorMap.copy() if component: event['component'] = component if event.get('datasourceId') and not event.get('eventKey'): event['eventKey'] = event.get('datasourceId') return event def sendEvent(self, event, **kw): self._eventService.sendEvent(event, **kw) def _collectJMX(self, dsConfigList): """ Call Java JMX process to collect JMX values @param dsConfigList: DataSource configuration @type dsConfigList: list of JMXDataSourceConfig @return: Twisted deferred object @rtype: Twisted deferred object """ def toDict(config): """ Marshall the fields from the datasource into a dictionary and ignore everything that is not a primitive @param config: dictionary of results @type config: string @return: results from remote device @rtype: dictionary """ vals = {} for (key, val) in config.__dict__.items(): if key != 'rrdConfig' and type(val)\ in XmlRpcService.PRIMITIVES: vals[key] = val rrdConfigs = config.rrdConfig.values() rrdConfigs.sort(lambda x, y: cmp(x.dataPointId, y.dataPointId)) vals['dps'] = [] vals['dptypes'] = [] for rrdConfig in rrdConfigs: vals['dps'].append(rrdConfig.dataPointId) vals['dptypes'].append(rrdConfig.rrdType) vals['connectionKey'] = config.getConnectionPropsKey() return vals def rpcCall(): """ Communicate with our local JMX process to collect results. This is a generator function @param driver: generator @type driver: string """ port = self._client.listenPort xmlRpcProxy = xmlrpc.Proxy('http://localhost:%s/' % port) d = xmlRpcProxy.callRemote('zenjmx.collect', configMaps) d.addCallbacks( processResults , processRpcError) return d def processRpcError(error): log.debug("Could not make XML RPC call for device %s; content of call: %s", self._taskConfig, configMaps) self.sendEvent({}, severity=Event.Error, eventClass='/Status/JMX', summary='unexpected error: %s' % error.getErrorMessage(), eventKey='unexpected_xmlrpc_error', device=self.configId) return error def processResults(jmxResults): """ Given the results from JMX, store them or send events. @param jmxResults: jmxResults @type jmxResults: string """ #Send clear for RPC error self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='unexpected error cleared', eventKey='unexpected_xmlrpc_error', device=self.configId) result = {} hasConnectionError = False hasUnexpectedError = False for result in jmxResults: log.debug("JMX result -> %s", result) evtSummary = result.get('summary') deviceId = result.get('device') evt = self.createEvent(result) if not evtSummary: rrdPath = result.get('rrdPath') dsId = result.get('datasourceId') dpId = result.get('dpId') value = result.get('value') try: self.storeRRD(deviceId, rrdPath, dsId, dpId, value) except ValueError: pass self.sendEvent(evt,summary="Clear",severity=Event.Clear) else: # send event log.debug('processResults(): ' + 'jmx error, sending event for %s' % result) if evt.get("eventClass", "") == '/Status/JMX/Connection': hasConnectionError = True if evt.get("eventKey", "") == 'unexpected_error': hasUnexpectedError = True self.sendEvent(evt, severity=Event.Error) if not hasConnectionError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX/Connection', summary='Connection is up', eventKey=connectionComponentKey, device=self.configId) if not hasUnexpectedError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='Unexpected error cleared', eventKey='unexpected_error', device=self.configId) return jmxResults connectionComponentKey = '' configMaps = [] for config in dsConfigList: connectionComponentKey = config.getConnectionPropsKey() configMaps.append(toDict(config)) log.info('collectJMX(): for %s %s' % (config.device, connectionComponentKey)) return rpcCall() def storeRRD( self, deviceId, rrdPath, dataSourceId, dataPointId, dpValue, ): """ Store a value into an RRD file @param deviceId: name of the remote device @type deviceId: string @param dataSourceId: name of the data source @type dataSourceId: string @param dataPointId: name of the data point @type dataPointId: string @param dpValue: dpValue @type dpValue: number """ deviceConfig = self._taskConfig dsConfig = deviceConfig.findDataSource(dataSourceId) if not dsConfig: log.info( 'No data source config found for device %s datasource %s' \ % (deviceId, dataSourceId)) return rrdConf = dsConfig.rrdConfig.get(dataPointId) type = rrdConf.rrdType if(type in ('COUNTER', 'DERIVE')): try: # cast to float first because long('100.0') will fail with a # ValueError dpValue = long(float(dpValue)) except (TypeError, ValueError): log.warning("value %s not valid for derive or counter data points", dpValue) else: try: dpValue = float(dpValue) except (TypeError, ValueError): log.warning("value %s not valid for data point", dpValue) if not rrdConf: log.info( 'No RRD config found for device %s datasource %s datapoint %s' \ % (deviceId, dataSourceId, dataPointId)) return dpPath = '/'.join((rrdPath, rrdConf.dpName)) min = rrdConf.min max = rrdConf.max self._dataService.writeRRD(dpPath, dpValue, rrdConf.rrdType, rrdConf.command, min=min, max=max) def _finished(self, results): for result in results: log.debug("Finished with result %s" % str( result ) ) return results def doTask(self): log.debug("Scanning device %s [%s]", self.configId, self._manageIp) d = self._collectCallback() d.addBoth(self._finished) # returning a Deferred will keep the framework from assuming the task # is done until the Deferred actually completes return d def _collectCallback(self): jobs = NJobs(self._preferences.options.parallel, self._collectJMX, self._taskConfig.jmxDataSourceConfigs.values()) deferred = jobs.start() return deferred def cleanup(self): pass def stopJavaJmxClients(): # Currently only starting/stopping one. clientName = DEFAULT_JMX_JAVA_CLIENT_NAME client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) if client is not None: log.debug( 'Shutting down JMX Java client %s' % clientName ) client.stop() if __name__ == '__main__': myPreferences = ZenJMXPreferences() initialization = ZenJMXJavaClientInitialization() myTaskFactory = SimpleTaskFactory(ZenJMXTask) myTaskSplitter = SimpleTaskSplitter(myTaskFactory) daemon = CollectorDaemon(myPreferences, myTaskSplitter, initializationCallback=initialization.initialize, stoppingCallback=stopJavaJmxClients) daemon.run()
ZenJMXTask
identifier_name
zenjmx.py
#! /usr/bin/env python ############################################################################## # # Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # ############################################################################## __doc__ = """Monitor Java Management eXtension (JMX) mbeans Dispatches calls to a java server process to collect JMX values for a device. """ import logging import sys import os import socket import Globals import zope from twisted.internet.defer import Deferred from twisted.web import xmlrpc from twisted.internet.protocol import ProcessProtocol from twisted.internet import defer, reactor, error from Products.ZenCollector.daemon import CollectorDaemon from Products.ZenCollector.interfaces import ICollectorPreferences,\ IDataService,\ IEventService,\ IScheduledTask from Products.ZenCollector.tasks import SimpleTaskFactory,\ SimpleTaskSplitter,\ TaskStates from Products.ZenEvents import Event from Products.ZenHub.XmlRpcService import XmlRpcService from Products.ZenUtils.NJobs import NJobs from Products.ZenUtils.Utils import unused from Products.ZenUtils.observable import ObservableMixin import ZenPacks.zenoss.ZenJMX from ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService import JMXDataSourceConfig unused(JMXDataSourceConfig) log = logging.getLogger( "zen.zenjmx" ) DEFAULT_HEARTBEAT_TIME = 5 * 60 WARNING_EVENT = dict(eventClass='/Status/JMX', component='JMX', device=socket.getfqdn(), severity=Event.Warning) class ZenJMXPreferences(object): """ Configuration values for the zenjmx daemon. """ zope.interface.implements(ICollectorPreferences) def __init__(self): """ Construct a new ZenJMXPreferences instance and provide default values for needed attributes. """ self.collectorName = "zenjmx" self.defaultRRDCreateCommand = None self.cycleInterval = 5 * 60 # seconds self.configCycleInterval = 20 # minutes self.options = None # the configurationService attribute is the fully qualified class-name # of our configuration service that runs within ZenHub self.configurationService = 'ZenPacks.zenoss.ZenJMX.services.ZenJMXConfigService' def buildOptions(self, parser): parser.add_option('-j','--zenjmxjavaport', dest='zenjmxjavaport', default=9988, type='int', help='Port for zenjmxjava process; default 9988. '+\ 'Tries 5 consecutive ports if there is a conflict', ) parser.add_option('--concurrentJMXCalls', dest='concurrentJMXCalls', action='store_true', default=False, help='Enable concurrent calls to a JMX server' ) parser.add_option('--parallel', dest='parallel', default=200, type='int', help='Number of devices to collect from at one time' ) parser.add_option('--cycleInterval', dest='cycleInterval', default=300, type='int', help='Cycle time, in seconds, to run collection' ) parser.add_option('--portRange', dest='portRange', default=5, type='int', help='Number of ports to attempt when starting' + 'Java jmx client') parser.add_option('--javaheap', dest="maxHeap",type="int", default=512, help="Max heap, in MB, to use for java process") def postStartup(self): pass def getJavaClientArgs(self): args = None if self.options.configfile: args = ('--configfile', self.options.configfile) if self.options.logseverity: args = args + ('-v', str(self.options.logseverity)) if self.options.concurrentJMXCalls: args = args + ('-concurrentJMXCalls', ) return args def getStartingPort(self): return self.options.zenjmxjavaport def getAttemptedPortRange(self): return self.options.portRange class IZenJMXJavaClient(zope.interface.Interface): listenPort = zope.interface.Attribute("listenPort") class ZenJMXJavaClientImpl(ProcessProtocol): """ Protocol to control the zenjmxjava process """ zope.interface.implements(IZenJMXJavaClient) def __init__( self, args, cycle=True, zenjmxjavaport=9988, maxHeap=512 ): """ Initializer @param args: argument list for zenjmx @type args: list of strings @param cycle: whether to run once or repeat @type cycle: boolean @param zenjmxjavaport: port on which java process will listen for queries @type zenjmxjavaport: int """ self.deferred = Deferred() self.stopCalled = False self.process = None self.outReceived = sys.stdout.write self.errReceived = sys.stderr.write self.log = logging.getLogger('zen.ZenJMXJavaClient') self.args = args self.cycle = cycle self.listenPort = zenjmxjavaport self._maxHeap = maxHeap self.restartEnabled = False self._eventService = zope.component.queryUtility(IEventService) self._preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') def processEnded(self, reason): """ Twisted reactor function called when the process ends. @param reason: message from the process @type reason: string """ self.process = None if not self.stopCalled: procEndEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava ended unexpectedly: %s'\ % reason.getErrorMessage(), 'severity': Event.Warning,
self._eventService.sendEvent(procEndEvent) self.log.warn('processEnded():zenjmxjava process ended %s' % reason) if self.deferred: msg = reason.getErrorMessage() exitCode = reason.value.exitCode if exitCode == 10: msg = 'Could not start up Java web server, '+\ 'possible port conflict' self.deferred.callback((exitCode,msg)) self.deferred = None elif self.restartEnabled: self.log.info('processEnded():restarting zenjmxjava') reactor.callLater(1, self.run) def stop(self): """ Twisted reactor function called when we are shutting down. """ import signal self.log.info('stop():stopping zenjmxjava') self.stopCalled = True if not self.process: self.log.debug('stop():no zenjmxjava process to stop') return try: self.process.signalProcess(signal.SIGKILL) except error.ProcessExitedAlready: self.log.info('stop():zenjmxjava process already exited') pass try: self.process.loseConnection() except Exception: pass self.process = None def connectionMade(self): """ Called when the Twisted reactor starts up """ self.log.debug('connectionMade():zenjmxjava started') def doCallback(): """ doCallback """ msg = \ 'doCallback(): callback on deferred zenjmxjava proc is up' self.log.debug(msg) if self.deferred: self.deferred.callback((True,'zenjmx java started')) if self.process: procStartEvent = { 'eventClass': '/Status/JMX', 'summary': 'zenjmxjava started', 'severity': Event.Clear, 'component': 'zenjmx', 'device': self._preferences.options.monitor, } self._eventService.sendEvent(procStartEvent) self.deferred = None if self.deferred: self.log.debug('connectionMade():scheduling callback') # give the java service a chance to startup reactor.callLater(3, doCallback) self.log.debug('connectionMade(): done') def run(self): """ Twisted function called when started """ if self.stopCalled: return self.log.info('run():starting zenjmxjava') zenjmxjavacmd = os.path.join(ZenPacks.zenoss.ZenJMX.binDir, 'zenjmxjava') if self.cycle: args = ('runjmxenabled', ) else: # don't want to start up with jmx server to avoid port conflicts args = ('run', ) args = args + ('-zenjmxjavaport', str(self.listenPort)) if self.args: args = args + self.args cmd = (zenjmxjavacmd, ) + args self.log.debug('run():spawn process %s' % (cmd, )) self.deferred = Deferred() env = dict(os.environ) env['JVM_MAX_HEAP'] = '-Xmx%sm'%self._maxHeap self.process = reactor.spawnProcess(self, zenjmxjavacmd, cmd, env=env) return self.deferred DEFAULT_JMX_JAVA_CLIENT_NAME = 'zenjmxjavaclient' class ZenJMXJavaClientInitialization(object): """ Wrapper that continues to start the Java jmx client until successful. """ def __init__(self, registeredName=DEFAULT_JMX_JAVA_CLIENT_NAME): """ @param registeredName: the name with which this client will be registered as a utility """ self._jmxClient = None self._clientName = registeredName def initialize(self): """ Begin the first attempt to start the Java jmx client. Note that this method returns a Deferred that relies on the ZenJMXPreferences being present when it is finally executed. This is meant to be the Deferred that is given to the CollectorDaemon for initialization before the first JMX task is scheduled. @return the deferred that represents the loading of preferences and the initial attempt to start the Java jmx client @rtype defer.Deferred """ def loadPrefs(): log.debug( "Retrieving java client startup args") preferences = zope.component.queryUtility(ICollectorPreferences, 'zenjmx') self._args = preferences.getJavaClientArgs() self._cycle = preferences.options.cycle self._maxHeap = preferences.options.maxHeap self._startingPort = preferences.getStartingPort() self._rpcPort = self._startingPort self._attemptedPortRange = preferences.getAttemptedPortRange() def printProblem(result): log.error( str(result) ) sys.exit(1) d = defer.maybeDeferred( loadPrefs ) d.addCallback( self._startJavaProc ) d.addErrback( printProblem ) return d def _tryClientOnCurrentPort( self ): """ Returns the Deferred for executing an attempt to start the java jmx client on the current port. """ log.debug( 'Attempting java client startup on port %s', self._rpcPort ) self._jmxClient = ZenJMXJavaClientImpl( self._args, self._cycle, self._rpcPort, self._maxHeap ) zope.component.provideUtility( self._jmxClient, IZenJMXJavaClient, self._clientName ) return self._jmxClient.run() def _startJavaProc( self, result=None ): """ Checks whether startup of the java jmx client was successful. If it was unsuccessful due to port conflict, increments the port and tries to start the client again. """ # If the result is not None, that means this was called as a callback # after an attempt to start the client if result is not None: # If result[0] is True, the client process started if result[0] is True: log.debug( 'Java jmx client started' ) self._jmxClient.restartEnabled = True deferred = defer.succeed( True ) # If the result[0] is 10, there was a port conflict elif result[0] == 10: log.debug( 'Java client didn\'t start; port %s occupied', self._rpcPort ) if self._rpcPort < ( self._startingPort + self._attemptedPortRange ): self._rpcPort += 1 deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) else: raise RuntimeError( "ZenJMXJavaClient could not be started, check ports") else: #unknown error raise RuntimeError('ZenJMXJavaClient could not be started, '+\ 'check JVM type and version: %s' % result[1]) # If there was no result passed in, then this is the first attempt # to start the client else: deferred = self._tryClientOnCurrentPort() deferred.addCallback( self._startJavaProc ) return deferred class ZenJMXTask(ObservableMixin): """ The scheduled task for all the jmx datasources on an individual device. """ zope.interface.implements(IScheduledTask) def __init__(self, deviceId, taskName, scheduleIntervalSeconds, taskConfig, clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ): super( ZenJMXTask, self ).__init__() self.name = taskName self.configId = deviceId self.state = TaskStates.STATE_IDLE self._taskConfig = taskConfig self._manageIp = self._taskConfig.manageIp self._dataService = zope.component.queryUtility( IDataService ) self._eventService = zope.component.queryUtility( IEventService ) self._preferences = zope.component.queryUtility( ICollectorPreferences, 'zenjmx' ) self._client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) # At this time, do not use the interval passed from the device # configuration. Use the value pulled from the daemon # configuration. unused( scheduleIntervalSeconds ) self.interval = self._preferences.options.cycleInterval def createEvent(self, errorMap, component=None): """ Given an event dictionary, copy it and return the event @param errorMap: errorMap @type errorMap: s dictionarytring @param component: component name @type component: string @return: updated event @rtype: dictionary """ event = errorMap.copy() if component: event['component'] = component if event.get('datasourceId') and not event.get('eventKey'): event['eventKey'] = event.get('datasourceId') return event def sendEvent(self, event, **kw): self._eventService.sendEvent(event, **kw) def _collectJMX(self, dsConfigList): """ Call Java JMX process to collect JMX values @param dsConfigList: DataSource configuration @type dsConfigList: list of JMXDataSourceConfig @return: Twisted deferred object @rtype: Twisted deferred object """ def toDict(config): """ Marshall the fields from the datasource into a dictionary and ignore everything that is not a primitive @param config: dictionary of results @type config: string @return: results from remote device @rtype: dictionary """ vals = {} for (key, val) in config.__dict__.items(): if key != 'rrdConfig' and type(val)\ in XmlRpcService.PRIMITIVES: vals[key] = val rrdConfigs = config.rrdConfig.values() rrdConfigs.sort(lambda x, y: cmp(x.dataPointId, y.dataPointId)) vals['dps'] = [] vals['dptypes'] = [] for rrdConfig in rrdConfigs: vals['dps'].append(rrdConfig.dataPointId) vals['dptypes'].append(rrdConfig.rrdType) vals['connectionKey'] = config.getConnectionPropsKey() return vals def rpcCall(): """ Communicate with our local JMX process to collect results. This is a generator function @param driver: generator @type driver: string """ port = self._client.listenPort xmlRpcProxy = xmlrpc.Proxy('http://localhost:%s/' % port) d = xmlRpcProxy.callRemote('zenjmx.collect', configMaps) d.addCallbacks( processResults , processRpcError) return d def processRpcError(error): log.debug("Could not make XML RPC call for device %s; content of call: %s", self._taskConfig, configMaps) self.sendEvent({}, severity=Event.Error, eventClass='/Status/JMX', summary='unexpected error: %s' % error.getErrorMessage(), eventKey='unexpected_xmlrpc_error', device=self.configId) return error def processResults(jmxResults): """ Given the results from JMX, store them or send events. @param jmxResults: jmxResults @type jmxResults: string """ #Send clear for RPC error self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='unexpected error cleared', eventKey='unexpected_xmlrpc_error', device=self.configId) result = {} hasConnectionError = False hasUnexpectedError = False for result in jmxResults: log.debug("JMX result -> %s", result) evtSummary = result.get('summary') deviceId = result.get('device') evt = self.createEvent(result) if not evtSummary: rrdPath = result.get('rrdPath') dsId = result.get('datasourceId') dpId = result.get('dpId') value = result.get('value') try: self.storeRRD(deviceId, rrdPath, dsId, dpId, value) except ValueError: pass self.sendEvent(evt,summary="Clear",severity=Event.Clear) else: # send event log.debug('processResults(): ' + 'jmx error, sending event for %s' % result) if evt.get("eventClass", "") == '/Status/JMX/Connection': hasConnectionError = True if evt.get("eventKey", "") == 'unexpected_error': hasUnexpectedError = True self.sendEvent(evt, severity=Event.Error) if not hasConnectionError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX/Connection', summary='Connection is up', eventKey=connectionComponentKey, device=self.configId) if not hasUnexpectedError: self.sendEvent({}, severity=Event.Clear, eventClass='/Status/JMX', summary='Unexpected error cleared', eventKey='unexpected_error', device=self.configId) return jmxResults connectionComponentKey = '' configMaps = [] for config in dsConfigList: connectionComponentKey = config.getConnectionPropsKey() configMaps.append(toDict(config)) log.info('collectJMX(): for %s %s' % (config.device, connectionComponentKey)) return rpcCall() def storeRRD( self, deviceId, rrdPath, dataSourceId, dataPointId, dpValue, ): """ Store a value into an RRD file @param deviceId: name of the remote device @type deviceId: string @param dataSourceId: name of the data source @type dataSourceId: string @param dataPointId: name of the data point @type dataPointId: string @param dpValue: dpValue @type dpValue: number """ deviceConfig = self._taskConfig dsConfig = deviceConfig.findDataSource(dataSourceId) if not dsConfig: log.info( 'No data source config found for device %s datasource %s' \ % (deviceId, dataSourceId)) return rrdConf = dsConfig.rrdConfig.get(dataPointId) type = rrdConf.rrdType if(type in ('COUNTER', 'DERIVE')): try: # cast to float first because long('100.0') will fail with a # ValueError dpValue = long(float(dpValue)) except (TypeError, ValueError): log.warning("value %s not valid for derive or counter data points", dpValue) else: try: dpValue = float(dpValue) except (TypeError, ValueError): log.warning("value %s not valid for data point", dpValue) if not rrdConf: log.info( 'No RRD config found for device %s datasource %s datapoint %s' \ % (deviceId, dataSourceId, dataPointId)) return dpPath = '/'.join((rrdPath, rrdConf.dpName)) min = rrdConf.min max = rrdConf.max self._dataService.writeRRD(dpPath, dpValue, rrdConf.rrdType, rrdConf.command, min=min, max=max) def _finished(self, results): for result in results: log.debug("Finished with result %s" % str( result ) ) return results def doTask(self): log.debug("Scanning device %s [%s]", self.configId, self._manageIp) d = self._collectCallback() d.addBoth(self._finished) # returning a Deferred will keep the framework from assuming the task # is done until the Deferred actually completes return d def _collectCallback(self): jobs = NJobs(self._preferences.options.parallel, self._collectJMX, self._taskConfig.jmxDataSourceConfigs.values()) deferred = jobs.start() return deferred def cleanup(self): pass def stopJavaJmxClients(): # Currently only starting/stopping one. clientName = DEFAULT_JMX_JAVA_CLIENT_NAME client = zope.component.queryUtility( IZenJMXJavaClient, clientName ) if client is not None: log.debug( 'Shutting down JMX Java client %s' % clientName ) client.stop() if __name__ == '__main__': myPreferences = ZenJMXPreferences() initialization = ZenJMXJavaClientInitialization() myTaskFactory = SimpleTaskFactory(ZenJMXTask) myTaskSplitter = SimpleTaskSplitter(myTaskFactory) daemon = CollectorDaemon(myPreferences, myTaskSplitter, initializationCallback=initialization.initialize, stoppingCallback=stopJavaJmxClients) daemon.run()
'component': 'zenjmx', 'device': self._preferences.options.monitor, }
random_line_split
test.rs
text /* this is a /* nested block */ comment. And should stay a comment even with "strings" or 42 0x18 0b01011 // blah or u32 as i16 if impl */ text /** this is a /*! nested block */ doc comment */ text /// test /// *test* /// **test** /// ***test*** /// _test_ /// __test__ /// __***test***__ /// ___test___ /// # test /// ## test /// ### test /// #### test /// ##### test /// ###### test /// ####### test /// # test **test** /// # test _test_ /// [text]() /// [test](http://test.com) /// [test](#test) /// ![test](#test) /// [test] /// [test]: http://test.com /// `test code` /// ```rust /// test code block /// ``` /// test /// /// /// # Test /// /// ``` /// assert!(true); /// ``` /// fn test(&self) { asdf // test asdf } /** * Deprecated */ /*! * Deprecated */ text /**/ text text /***/ text text /****/ text text text // line comment text /// line doc comment text //! line doc comment text text #![main] text text #![allow(great_algorithms)] text text #![!resolve_unexported] text text #[deny(silly_comments)] text #[doc = "This attribute contains ] an attribute ending character"] text r"This is a raw string" text text r"This raw string ends in \" text text r#"This is also valid"# text text r##"This is ##"# also valid."## text text r#"This is #"## not valid."# text //" text b"This is a bytestring" text text br"And a raw byte string" text text rb"Invalid raw byte string" text text br##"This is ##"# also valid."## text text r##"Raw strings can span multiple lines"## text text "double-quote string" text text "string\nwith\x20escaped\"characters" text text "string with // comment /* inside" text text "strings can span multiple lines" text text 'c' text text 'cc' text text '\n' text text '\nf' text text '\n\n' text text '\x20' text text '\'' text text '\\' text text b'b' text text b'bb' text text b'\x20' text text 42i32 text text 42is text text 42int text text 42f32 text text 42e+18 text text 42.1415 text text 42.1415f32 text text 42.1415e18 text text 42.1415e+18 text text 42.1415e-18f64 text text 42 text text 0xf00b text text 0o755 text text 0b101010 text text bool text char text usize text isize text text u8 text u16 text u32 text u64 text text i8 text i16 text i32 text i64 text text Self text text str text &str text String text &String text text true text false text text break text continue text do text else text text if text in text for text loop text text match text return text while text text as text crate text extern text mod text text let text proc text ref text text extern crate foo; text use std::slice; text use std::{num, str}; text use self::foo::{bar, baz}; text use super::foo::{bar, baz}; text x = 1+1; y = 4-2; x *= 3; y++; y += 1; text pub enum MyEnum { One, Two } text pub struct MyStruct<'foo> { pub one: u32, two: Option<'a, MyEnum>, three: &'foo i32, } text pub struct MyTupleStruct(pub i32, u32); text text type MyType = u32; text text static MY_CONSTANT: &str = "hello"; text text pub trait MyTrait { text fn create_something (param: &str, mut other_param: u32) -> Option<Self>; text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>; text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool; text fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U; text } text text impl<'foo> MyTrait for MyStruct<'foo> { text fn create_something (param: &str, mut other_param: u32) -> Option<Self> { text return Some(cake); text } text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>
text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool { announce!("There's no cake"); if !test_subject.under_control() { text let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect(); text let boxed_list = box list; text self.announce_warning(); text if test_subject.ignored_warnings > 3 { text test_subject.incinerate(); text } text } text } text fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U { text let foo: Option<'a u32> = Some(18); text if self.one < 1 { text self.complain(&foo); text } } text } text text impl MyStruct<'foo> { text pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T { text f(123, "hello") text } text } text // Loop expression labels (#2) 'infinity: loop { do_serious_stuff(); use_a_letter('Z'); break 'infinity; } // isize/usize suffixes (#22) let x = 123usize; // Float literals without +- after E (#30) let x = 1.2345e6; // Nested generic (#33, #37) let x: Vec<Vec<u8>> = Vec::new(); // Correct detection of == (#40) struct Foo { x: i32 } if x == 1 { } // const function parameter (#52) fn foo(bar: *const i32) { let _ = 1234 as *const u32; } // Keywords and known types in wrapper structs (#56) pub struct Foobar(pub Option<bool>); pub struct Foobar(pub Test<W=bool>); pub struct Foobar(pub Test<W==bool>); pub struct Foobar(pub Test<W = bool>); struct Test(i32); struct Test(String); struct Test(Vec<i32>); struct Test(BTreeMap<String, i32>); // Lifetimes in associated type definitions trait Foo { type B: A + 'static; } // where clause impl Foo<A, B> where text { } text impl Foo<A, B> for C where text { } text impl Foo<A, B> for C { fn foo<A, B> -> C where text { } } text fn foo<A, B> -> C where text { } text struct Foo<A, B> where text { } text trait Foo<A, B> : C where { } text fn do_work<T: Any + Debug>(value: &T) {} impl Cookie {} impl<T> PrintInOption for T where Option<T>: Debug {} impl<K,V> HashMap<K, V> where K : Hash + Eq {} impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {} impl Debug for a where asdf {} impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {} // Unsafe in function arguments unsafe fn foo(); fn foo(f: unsafe fn()); // Format macros format!("text"); format!("text{}text", 1); format!("text{0}text", 1); format!("text{named}text", named=1); format!("text{:?}text", to_debug); format!("text{0:?}text", to_debug); format!("text{named:?}text", named=to_debug); format!("text{:<}text", 1); format!("text{:.>}text", 1); format!("text{:+}text", pos_or_neg); format!("text{:+0}text", pos_or_neg); format!("text{:+04}text", pos_or_neg); format!("text{:6}", "text"); format!("text{:1$}", "text", 6); format!("text{1:6$}", 6, "text"); format!("text{:w$}", "text", w=6); format!("text{:8b}text", byte); format!("text{:08b}text", byte); format!("text{:#010b}text", byte); format!("text{:2x}text", byte); format!("text{:#4x}text", byte); format!("text{:.2}text", 0.5); format!("text{:0.2}text", 0.5); format!("text{:06.2}text", 0.5); format!("text{named:.prec$}text", prec=0.5, named=2.0); format!("text{}text{2:.*}text", "text", 6, 0.5); format!("text{named:-^+#06.2e}text", named=0.5); format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2); format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}"); not_format!("text{}text"); format_args!("{}", "text"); write!("{}", "text"); writeln!("{}", "text"); print!("{}", "text"); println!("{}", "text"); log!("{}", "text"); error!("{}", "text"); warn!("{}", "text"); info!("{}", "text"); debug!("{}", "text"); trace!("{}", "text"); eprint!("{}", "text"); eprintln!("{}", "text"); // Unused reserved words abstract fn do_thing(); final let MAX = 10us; let i = 0; do { yield do_thing(i++); } while(i < MAX); impl Float for f32 { fn infinity() -> Self { f32::INFINITY } } #[derive(Default)] enum State { /// Currently open in a sane state Open, /// Waiting to send a GO_AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO_AWAY_ frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY* frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY__ frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY** frame GoAway(frame::GoAway) } Box<dyn MyTrait> &dyn Foo &mut dyn Foo
{ assert!(1 != 2); text self.with_something(param, |arg1, arg2| { text }, other_param); }
identifier_body
test.rs
text /* this is a /* nested block */ comment. And should stay a comment even with "strings" or 42 0x18 0b01011 // blah or u32 as i16 if impl */ text /** this is a /*! nested block */ doc comment */ text /// test /// *test* /// **test** /// ***test*** /// _test_ /// __test__ /// __***test***__ /// ___test___ /// # test /// ## test /// ### test /// #### test /// ##### test /// ###### test /// ####### test /// # test **test** /// # test _test_ /// [text]() /// [test](http://test.com) /// [test](#test) /// ![test](#test) /// [test] /// [test]: http://test.com /// `test code` /// ```rust /// test code block /// ``` /// test /// /// /// # Test /// /// ``` /// assert!(true); /// ``` /// fn test(&self) { asdf // test asdf } /** * Deprecated */ /*! * Deprecated */ text /**/ text text /***/ text text /****/ text text text // line comment text /// line doc comment text //! line doc comment text text #![main] text text #![allow(great_algorithms)] text text #![!resolve_unexported] text text #[deny(silly_comments)] text #[doc = "This attribute contains ] an attribute ending character"] text r"This is a raw string" text text r"This raw string ends in \" text text r#"This is also valid"# text text r##"This is ##"# also valid."## text text r#"This is #"## not valid."# text //" text b"This is a bytestring" text text br"And a raw byte string" text text rb"Invalid raw byte string" text text br##"This is ##"# also valid."## text text r##"Raw strings can span multiple lines"## text text "double-quote string" text text "string\nwith\x20escaped\"characters" text text "string with // comment /* inside" text text "strings can span multiple lines" text text 'c' text text 'cc' text text '\n' text text '\nf' text text '\n\n' text text '\x20' text text '\'' text text '\\' text text b'b' text text b'bb' text text b'\x20' text text 42i32 text text 42is text text 42int text text 42f32 text text 42e+18 text text 42.1415 text text 42.1415f32 text text 42.1415e18 text text 42.1415e+18 text text 42.1415e-18f64 text text 42 text text 0xf00b text text 0o755 text text 0b101010 text text bool text char text usize text isize text text u8 text u16 text u32 text u64 text text i8 text i16 text i32 text i64 text text Self text text str text &str text String text &String text text true text false text text break text continue text do text else text text if text in text for text loop text text match text return text while text text as text crate text extern text mod text text let text proc text ref text text extern crate foo; text use std::slice; text use std::{num, str}; text use self::foo::{bar, baz}; text use super::foo::{bar, baz}; text x = 1+1; y = 4-2; x *= 3; y++; y += 1; text pub enum MyEnum { One, Two } text pub struct MyStruct<'foo> { pub one: u32, two: Option<'a, MyEnum>, three: &'foo i32, } text pub struct MyTupleStruct(pub i32, u32); text text type MyType = u32; text text static MY_CONSTANT: &str = "hello"; text text pub trait MyTrait { text fn create_something (param: &str, mut other_param: u32) -> Option<Self>; text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>; text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool; text fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U; text } text text impl<'foo> MyTrait for MyStruct<'foo> { text fn create_something (param: &str, mut other_param: u32) -> Option<Self> { text return Some(cake); text } text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> { assert!(1 != 2); text self.with_something(param, |arg1, arg2| { text }, other_param); } text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool { announce!("There's no cake"); if !test_subject.under_control() { text let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect(); text let boxed_list = box list; text self.announce_warning(); text if test_subject.ignored_warnings > 3 { text test_subject.incinerate(); text } text } text } text fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U { text let foo: Option<'a u32> = Some(18); text if self.one < 1 { text self.complain(&foo); text } } text } text text impl MyStruct<'foo> { text pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T { text f(123, "hello") text } text } text // Loop expression labels (#2) 'infinity: loop { do_serious_stuff(); use_a_letter('Z'); break 'infinity; } // isize/usize suffixes (#22) let x = 123usize; // Float literals without +- after E (#30) let x = 1.2345e6; // Nested generic (#33, #37) let x: Vec<Vec<u8>> = Vec::new(); // Correct detection of == (#40) struct Foo { x: i32 } if x == 1
// const function parameter (#52) fn foo(bar: *const i32) { let _ = 1234 as *const u32; } // Keywords and known types in wrapper structs (#56) pub struct Foobar(pub Option<bool>); pub struct Foobar(pub Test<W=bool>); pub struct Foobar(pub Test<W==bool>); pub struct Foobar(pub Test<W = bool>); struct Test(i32); struct Test(String); struct Test(Vec<i32>); struct Test(BTreeMap<String, i32>); // Lifetimes in associated type definitions trait Foo { type B: A + 'static; } // where clause impl Foo<A, B> where text { } text impl Foo<A, B> for C where text { } text impl Foo<A, B> for C { fn foo<A, B> -> C where text { } } text fn foo<A, B> -> C where text { } text struct Foo<A, B> where text { } text trait Foo<A, B> : C where { } text fn do_work<T: Any + Debug>(value: &T) {} impl Cookie {} impl<T> PrintInOption for T where Option<T>: Debug {} impl<K,V> HashMap<K, V> where K : Hash + Eq {} impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {} impl Debug for a where asdf {} impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {} // Unsafe in function arguments unsafe fn foo(); fn foo(f: unsafe fn()); // Format macros format!("text"); format!("text{}text", 1); format!("text{0}text", 1); format!("text{named}text", named=1); format!("text{:?}text", to_debug); format!("text{0:?}text", to_debug); format!("text{named:?}text", named=to_debug); format!("text{:<}text", 1); format!("text{:.>}text", 1); format!("text{:+}text", pos_or_neg); format!("text{:+0}text", pos_or_neg); format!("text{:+04}text", pos_or_neg); format!("text{:6}", "text"); format!("text{:1$}", "text", 6); format!("text{1:6$}", 6, "text"); format!("text{:w$}", "text", w=6); format!("text{:8b}text", byte); format!("text{:08b}text", byte); format!("text{:#010b}text", byte); format!("text{:2x}text", byte); format!("text{:#4x}text", byte); format!("text{:.2}text", 0.5); format!("text{:0.2}text", 0.5); format!("text{:06.2}text", 0.5); format!("text{named:.prec$}text", prec=0.5, named=2.0); format!("text{}text{2:.*}text", "text", 6, 0.5); format!("text{named:-^+#06.2e}text", named=0.5); format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2); format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}"); not_format!("text{}text"); format_args!("{}", "text"); write!("{}", "text"); writeln!("{}", "text"); print!("{}", "text"); println!("{}", "text"); log!("{}", "text"); error!("{}", "text"); warn!("{}", "text"); info!("{}", "text"); debug!("{}", "text"); trace!("{}", "text"); eprint!("{}", "text"); eprintln!("{}", "text"); // Unused reserved words abstract fn do_thing(); final let MAX = 10us; let i = 0; do { yield do_thing(i++); } while(i < MAX); impl Float for f32 { fn infinity() -> Self { f32::INFINITY } } #[derive(Default)] enum State { /// Currently open in a sane state Open, /// Waiting to send a GO_AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO_AWAY_ frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY* frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY__ frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY** frame GoAway(frame::GoAway) } Box<dyn MyTrait> &dyn Foo &mut dyn Foo
{ }
conditional_block
test.rs
text /* this is a /* nested block */ comment. And should stay a comment even with "strings" or 42 0x18 0b01011 // blah or u32 as i16 if impl */ text /** this is a /*! nested block */ doc comment */ text /// test /// *test* /// **test** /// ***test*** /// _test_ /// __test__ /// __***test***__ /// ___test___ /// # test /// ## test /// ### test /// #### test /// ##### test /// ###### test /// ####### test /// # test **test** /// # test _test_ /// [text]() /// [test](http://test.com) /// [test](#test) /// ![test](#test) /// [test] /// [test]: http://test.com /// `test code` /// ```rust /// test code block /// ``` /// test /// /// /// # Test /// /// ``` /// assert!(true); /// ``` /// fn test(&self) { asdf // test asdf } /** * Deprecated */ /*! * Deprecated */ text /**/ text text /***/ text text /****/ text text text // line comment text /// line doc comment text //! line doc comment text text #![main] text text #![allow(great_algorithms)] text text #![!resolve_unexported] text text #[deny(silly_comments)] text #[doc = "This attribute contains ] an attribute ending character"] text r"This is a raw string" text text r"This raw string ends in \" text text r#"This is also valid"# text text r##"This is ##"# also valid."## text text r#"This is #"## not valid."# text //" text b"This is a bytestring" text text br"And a raw byte string" text text rb"Invalid raw byte string" text text br##"This is ##"# also valid."## text text r##"Raw strings can span multiple lines"## text text "double-quote string" text text "string\nwith\x20escaped\"characters" text text "string with // comment /* inside" text text "strings can span multiple lines" text text 'c' text text 'cc' text text '\n' text text '\nf' text text '\n\n' text text '\x20' text text '\'' text text '\\' text text b'b' text text b'bb' text text b'\x20' text text 42i32 text text 42is text text 42int text text 42f32 text text 42e+18 text text 42.1415 text text 42.1415f32 text text 42.1415e18 text text 42.1415e+18 text text 42.1415e-18f64 text text 42 text text 0xf00b text text 0o755 text text 0b101010 text text bool text char text usize text isize text text u8 text u16 text u32 text u64 text text i8 text i16 text i32 text i64 text text Self text text str text &str text String text &String text text true text false text text break text continue text do text else text text if text in text for text loop text text match text return text while text text as text crate text extern text mod text text let text proc text ref text text extern crate foo; text use std::slice; text use std::{num, str}; text use self::foo::{bar, baz}; text use super::foo::{bar, baz}; text x = 1+1; y = 4-2; x *= 3; y++; y += 1; text pub enum MyEnum { One, Two } text pub struct MyStruct<'foo> { pub one: u32, two: Option<'a, MyEnum>, three: &'foo i32, } text pub struct MyTupleStruct(pub i32, u32); text text type MyType = u32; text text static MY_CONSTANT: &str = "hello"; text text pub trait MyTrait { text fn create_something (param: &str, mut other_param: u32) -> Option<Self>; text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>; text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool; text fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U; text } text text impl<'foo> MyTrait for MyStruct<'foo> { text fn create_something (param: &str, mut other_param: u32) -> Option<Self> { text return Some(cake); text } text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> { assert!(1 != 2); text self.with_something(param, |arg1, arg2| { text }, other_param); } text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool { announce!("There's no cake"); if !test_subject.under_control() { text let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect(); text let boxed_list = box list; text self.announce_warning(); text if test_subject.ignored_warnings > 3 { text test_subject.incinerate(); text } text } text } text fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U { text let foo: Option<'a u32> = Some(18); text if self.one < 1 { text self.complain(&foo); text } } text } text text impl MyStruct<'foo> { text pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T { text f(123, "hello") text } text } text // Loop expression labels (#2) 'infinity: loop { do_serious_stuff(); use_a_letter('Z'); break 'infinity; } // isize/usize suffixes (#22) let x = 123usize; // Float literals without +- after E (#30) let x = 1.2345e6; // Nested generic (#33, #37) let x: Vec<Vec<u8>> = Vec::new(); // Correct detection of == (#40) struct Foo { x: i32 } if x == 1 { } // const function parameter (#52) fn foo(bar: *const i32) { let _ = 1234 as *const u32; } // Keywords and known types in wrapper structs (#56) pub struct Foobar(pub Option<bool>); pub struct
(pub Test<W=bool>); pub struct Foobar(pub Test<W==bool>); pub struct Foobar(pub Test<W = bool>); struct Test(i32); struct Test(String); struct Test(Vec<i32>); struct Test(BTreeMap<String, i32>); // Lifetimes in associated type definitions trait Foo { type B: A + 'static; } // where clause impl Foo<A, B> where text { } text impl Foo<A, B> for C where text { } text impl Foo<A, B> for C { fn foo<A, B> -> C where text { } } text fn foo<A, B> -> C where text { } text struct Foo<A, B> where text { } text trait Foo<A, B> : C where { } text fn do_work<T: Any + Debug>(value: &T) {} impl Cookie {} impl<T> PrintInOption for T where Option<T>: Debug {} impl<K,V> HashMap<K, V> where K : Hash + Eq {} impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {} impl Debug for a where asdf {} impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {} // Unsafe in function arguments unsafe fn foo(); fn foo(f: unsafe fn()); // Format macros format!("text"); format!("text{}text", 1); format!("text{0}text", 1); format!("text{named}text", named=1); format!("text{:?}text", to_debug); format!("text{0:?}text", to_debug); format!("text{named:?}text", named=to_debug); format!("text{:<}text", 1); format!("text{:.>}text", 1); format!("text{:+}text", pos_or_neg); format!("text{:+0}text", pos_or_neg); format!("text{:+04}text", pos_or_neg); format!("text{:6}", "text"); format!("text{:1$}", "text", 6); format!("text{1:6$}", 6, "text"); format!("text{:w$}", "text", w=6); format!("text{:8b}text", byte); format!("text{:08b}text", byte); format!("text{:#010b}text", byte); format!("text{:2x}text", byte); format!("text{:#4x}text", byte); format!("text{:.2}text", 0.5); format!("text{:0.2}text", 0.5); format!("text{:06.2}text", 0.5); format!("text{named:.prec$}text", prec=0.5, named=2.0); format!("text{}text{2:.*}text", "text", 6, 0.5); format!("text{named:-^+#06.2e}text", named=0.5); format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2); format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}"); not_format!("text{}text"); format_args!("{}", "text"); write!("{}", "text"); writeln!("{}", "text"); print!("{}", "text"); println!("{}", "text"); log!("{}", "text"); error!("{}", "text"); warn!("{}", "text"); info!("{}", "text"); debug!("{}", "text"); trace!("{}", "text"); eprint!("{}", "text"); eprintln!("{}", "text"); // Unused reserved words abstract fn do_thing(); final let MAX = 10us; let i = 0; do { yield do_thing(i++); } while(i < MAX); impl Float for f32 { fn infinity() -> Self { f32::INFINITY } } #[derive(Default)] enum State { /// Currently open in a sane state Open, /// Waiting to send a GO_AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO_AWAY_ frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY* frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY__ frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY** frame GoAway(frame::GoAway) } Box<dyn MyTrait> &dyn Foo &mut dyn Foo
Foobar
identifier_name
test.rs
text /* this is a /* nested block */ comment. And should stay a comment even with "strings" or 42 0x18 0b01011 // blah or u32 as i16 if impl */ text /** this is a /*! nested block */ doc comment */ text /// test /// *test* /// **test** /// ***test*** /// _test_ /// __test__ /// __***test***__ /// ___test___ /// # test /// ## test /// ### test /// #### test /// ##### test /// ###### test /// ####### test /// # test **test** /// # test _test_ /// [text]() /// [test](http://test.com) /// [test](#test) /// ![test](#test) /// [test] /// [test]: http://test.com /// `test code` /// ```rust /// test code block /// ``` /// test /// /// /// # Test /// /// ``` /// assert!(true); /// ``` /// fn test(&self) { asdf // test asdf } /** * Deprecated */ /*! * Deprecated */ text /**/ text text /***/ text text /****/ text text text // line comment text /// line doc comment text //! line doc comment text text #![main] text text #![allow(great_algorithms)] text text #![!resolve_unexported] text text #[deny(silly_comments)] text #[doc = "This attribute contains ] an attribute ending character"]
text r##"This is ##"# also valid."## text text r#"This is #"## not valid."# text //" text b"This is a bytestring" text text br"And a raw byte string" text text rb"Invalid raw byte string" text text br##"This is ##"# also valid."## text text r##"Raw strings can span multiple lines"## text text "double-quote string" text text "string\nwith\x20escaped\"characters" text text "string with // comment /* inside" text text "strings can span multiple lines" text text 'c' text text 'cc' text text '\n' text text '\nf' text text '\n\n' text text '\x20' text text '\'' text text '\\' text text b'b' text text b'bb' text text b'\x20' text text 42i32 text text 42is text text 42int text text 42f32 text text 42e+18 text text 42.1415 text text 42.1415f32 text text 42.1415e18 text text 42.1415e+18 text text 42.1415e-18f64 text text 42 text text 0xf00b text text 0o755 text text 0b101010 text text bool text char text usize text isize text text u8 text u16 text u32 text u64 text text i8 text i16 text i32 text i64 text text Self text text str text &str text String text &String text text true text false text text break text continue text do text else text text if text in text for text loop text text match text return text while text text as text crate text extern text mod text text let text proc text ref text text extern crate foo; text use std::slice; text use std::{num, str}; text use self::foo::{bar, baz}; text use super::foo::{bar, baz}; text x = 1+1; y = 4-2; x *= 3; y++; y += 1; text pub enum MyEnum { One, Two } text pub struct MyStruct<'foo> { pub one: u32, two: Option<'a, MyEnum>, three: &'foo i32, } text pub struct MyTupleStruct(pub i32, u32); text text type MyType = u32; text text static MY_CONSTANT: &str = "hello"; text text pub trait MyTrait { text fn create_something (param: &str, mut other_param: u32) -> Option<Self>; text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>; text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool; text fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U; text } text text impl<'foo> MyTrait for MyStruct<'foo> { text fn create_something (param: &str, mut other_param: u32) -> Option<Self> { text return Some(cake); text } text fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> { assert!(1 != 2); text self.with_something(param, |arg1, arg2| { text }, other_param); } text fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool { announce!("There's no cake"); if !test_subject.under_control() { text let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect(); text let boxed_list = box list; text self.announce_warning(); text if test_subject.ignored_warnings > 3 { text test_subject.incinerate(); text } text } text } text fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U { text let foo: Option<'a u32> = Some(18); text if self.one < 1 { text self.complain(&foo); text } } text } text text impl MyStruct<'foo> { text pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T { text f(123, "hello") text } text } text // Loop expression labels (#2) 'infinity: loop { do_serious_stuff(); use_a_letter('Z'); break 'infinity; } // isize/usize suffixes (#22) let x = 123usize; // Float literals without +- after E (#30) let x = 1.2345e6; // Nested generic (#33, #37) let x: Vec<Vec<u8>> = Vec::new(); // Correct detection of == (#40) struct Foo { x: i32 } if x == 1 { } // const function parameter (#52) fn foo(bar: *const i32) { let _ = 1234 as *const u32; } // Keywords and known types in wrapper structs (#56) pub struct Foobar(pub Option<bool>); pub struct Foobar(pub Test<W=bool>); pub struct Foobar(pub Test<W==bool>); pub struct Foobar(pub Test<W = bool>); struct Test(i32); struct Test(String); struct Test(Vec<i32>); struct Test(BTreeMap<String, i32>); // Lifetimes in associated type definitions trait Foo { type B: A + 'static; } // where clause impl Foo<A, B> where text { } text impl Foo<A, B> for C where text { } text impl Foo<A, B> for C { fn foo<A, B> -> C where text { } } text fn foo<A, B> -> C where text { } text struct Foo<A, B> where text { } text trait Foo<A, B> : C where { } text fn do_work<T: Any + Debug>(value: &T) {} impl Cookie {} impl<T> PrintInOption for T where Option<T>: Debug {} impl<K,V> HashMap<K, V> where K : Hash + Eq {} impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {} impl Debug for a where asdf {} impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {} // Unsafe in function arguments unsafe fn foo(); fn foo(f: unsafe fn()); // Format macros format!("text"); format!("text{}text", 1); format!("text{0}text", 1); format!("text{named}text", named=1); format!("text{:?}text", to_debug); format!("text{0:?}text", to_debug); format!("text{named:?}text", named=to_debug); format!("text{:<}text", 1); format!("text{:.>}text", 1); format!("text{:+}text", pos_or_neg); format!("text{:+0}text", pos_or_neg); format!("text{:+04}text", pos_or_neg); format!("text{:6}", "text"); format!("text{:1$}", "text", 6); format!("text{1:6$}", 6, "text"); format!("text{:w$}", "text", w=6); format!("text{:8b}text", byte); format!("text{:08b}text", byte); format!("text{:#010b}text", byte); format!("text{:2x}text", byte); format!("text{:#4x}text", byte); format!("text{:.2}text", 0.5); format!("text{:0.2}text", 0.5); format!("text{:06.2}text", 0.5); format!("text{named:.prec$}text", prec=0.5, named=2.0); format!("text{}text{2:.*}text", "text", 6, 0.5); format!("text{named:-^+#06.2e}text", named=0.5); format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2); format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}"); not_format!("text{}text"); format_args!("{}", "text"); write!("{}", "text"); writeln!("{}", "text"); print!("{}", "text"); println!("{}", "text"); log!("{}", "text"); error!("{}", "text"); warn!("{}", "text"); info!("{}", "text"); debug!("{}", "text"); trace!("{}", "text"); eprint!("{}", "text"); eprintln!("{}", "text"); // Unused reserved words abstract fn do_thing(); final let MAX = 10us; let i = 0; do { yield do_thing(i++); } while(i < MAX); impl Float for f32 { fn infinity() -> Self { f32::INFINITY } } #[derive(Default)] enum State { /// Currently open in a sane state Open, /// Waiting to send a GO_AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO_AWAY_ frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO*AWAY* frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO__AWAY__ frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY frame GoAway(frame::GoAway) /// Waiting to send a GO**AWAY** frame GoAway(frame::GoAway) } Box<dyn MyTrait> &dyn Foo &mut dyn Foo
text r"This is a raw string" text text r"This raw string ends in \" text text r#"This is also valid"# text
random_line_split
sync.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alexander Fomin <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. /* Last synced with: sync (GNU coreutils) 8.13 */ extern crate libc; use clap::{crate_version, App, AppSettings, Arg}; use std::path::Path; use uucore::display::Quotable; use uucore::error::{UResult, USimpleError}; use uucore::format_usage; static ABOUT: &str = "Synchronize cached writes to persistent storage"; const USAGE: &str = "{} [OPTION]... FILE..."; pub mod options { pub static FILE_SYSTEM: &str = "file-system"; pub static DATA: &str = "data"; } static ARG_FILES: &str = "files"; #[cfg(unix)] mod platform { use super::libc; #[cfg(target_os = "linux")] use std::fs::File; #[cfg(target_os = "linux")] use std::os::unix::io::AsRawFd; pub unsafe fn do_sync() -> isize { libc::sync(); 0 } #[cfg(target_os = "linux")] pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_syncfs, fd); } 0 } #[cfg(target_os = "linux")] pub unsafe fn do_fdatasync(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_fdatasync, fd); } 0 } } #[cfg(windows)] mod platform { extern crate winapi; use self::winapi::shared::minwindef; use self::winapi::shared::winerror; use self::winapi::um::handleapi; use self::winapi::um::winbase; use self::winapi::um::winnt; use std::fs::OpenOptions; use std::mem; use std::os::windows::prelude::*; use std::path::Path; use uucore::crash; use uucore::wide::{FromWide, ToWide}; unsafe fn flush_volume(name: &str) { let name_wide = name.to_wide_null(); if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED { let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash match OpenOptions::new().write(true).open(sliced_name) { Ok(file) => { if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to flush file buffer" ); } } Err(e) => crash!( e.raw_os_error().unwrap_or(1), "failed to create volume handle" ), } } } unsafe fn find_first_volume() -> (String, winnt::HANDLE) { #[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); let handle = winapi::um::fileapi::FindFirstVolumeW( name.as_mut_ptr(), name.len() as minwindef::DWORD, ); if handle == handleapi::INVALID_HANDLE_VALUE { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to find first volume" ); } (String::from_wide_null(&name), handle) }
#[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); if winapi::um::fileapi::FindNextVolumeW( next_volume_handle, name.as_mut_ptr(), name.len() as minwindef::DWORD, ) == 0 { match winapi::um::errhandlingapi::GetLastError() { winerror::ERROR_NO_MORE_FILES => { winapi::um::fileapi::FindVolumeClose(next_volume_handle); return volumes; } err => crash!(err as i32, "failed to find next volume"), } } else { volumes.push(String::from_wide_null(&name)); } } } pub unsafe fn do_sync() -> isize { let volumes = find_all_volumes(); for vol in &volumes { flush_volume(vol); } 0 } pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { flush_volume( Path::new(&path) .components() .next() .unwrap() .as_os_str() .to_str() .unwrap(), ); } 0 } } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<String> = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) .unwrap_or_default(); for f in &files { if !Path::new(&f).exists() { return Err(USimpleError::new( 1, format!("cannot stat {}: No such file or directory", f.quote()), )); } } #[allow(clippy::if_same_then_else)] if matches.is_present(options::FILE_SYSTEM) { #[cfg(any(target_os = "linux", target_os = "windows"))] syncfs(files); } else if matches.is_present(options::DATA) { #[cfg(target_os = "linux")] fdatasync(files); } else { sync(); } Ok(()) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILE_SYSTEM) .short('f') .long(options::FILE_SYSTEM) .conflicts_with(options::DATA) .help("sync the file systems that contain the files (Linux and Windows only)"), ) .arg( Arg::new(options::DATA) .short('d') .long(options::DATA) .conflicts_with(options::FILE_SYSTEM) .help("sync only file data, no unneeded metadata (Linux only)"), ) .arg( Arg::new(ARG_FILES) .multiple_occurrences(true) .takes_value(true), ) } fn sync() -> isize { unsafe { platform::do_sync() } } #[cfg(any(target_os = "linux", target_os = "windows"))] fn syncfs(files: Vec<String>) -> isize { unsafe { platform::do_syncfs(files) } } #[cfg(target_os = "linux")] fn fdatasync(files: Vec<String>) -> isize { unsafe { platform::do_fdatasync(files) } }
unsafe fn find_all_volumes() -> Vec<String> { let (first_volume, next_volume_handle) = find_first_volume(); let mut volumes = vec![first_volume]; loop {
random_line_split
sync.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alexander Fomin <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. /* Last synced with: sync (GNU coreutils) 8.13 */ extern crate libc; use clap::{crate_version, App, AppSettings, Arg}; use std::path::Path; use uucore::display::Quotable; use uucore::error::{UResult, USimpleError}; use uucore::format_usage; static ABOUT: &str = "Synchronize cached writes to persistent storage"; const USAGE: &str = "{} [OPTION]... FILE..."; pub mod options { pub static FILE_SYSTEM: &str = "file-system"; pub static DATA: &str = "data"; } static ARG_FILES: &str = "files"; #[cfg(unix)] mod platform { use super::libc; #[cfg(target_os = "linux")] use std::fs::File; #[cfg(target_os = "linux")] use std::os::unix::io::AsRawFd; pub unsafe fn do_sync() -> isize { libc::sync(); 0 } #[cfg(target_os = "linux")] pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_syncfs, fd); } 0 } #[cfg(target_os = "linux")] pub unsafe fn do_fdatasync(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_fdatasync, fd); } 0 } } #[cfg(windows)] mod platform { extern crate winapi; use self::winapi::shared::minwindef; use self::winapi::shared::winerror; use self::winapi::um::handleapi; use self::winapi::um::winbase; use self::winapi::um::winnt; use std::fs::OpenOptions; use std::mem; use std::os::windows::prelude::*; use std::path::Path; use uucore::crash; use uucore::wide::{FromWide, ToWide}; unsafe fn flush_volume(name: &str) { let name_wide = name.to_wide_null(); if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED { let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash match OpenOptions::new().write(true).open(sliced_name) { Ok(file) => { if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to flush file buffer" ); } } Err(e) => crash!( e.raw_os_error().unwrap_or(1), "failed to create volume handle" ), } } } unsafe fn find_first_volume() -> (String, winnt::HANDLE) { #[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); let handle = winapi::um::fileapi::FindFirstVolumeW( name.as_mut_ptr(), name.len() as minwindef::DWORD, ); if handle == handleapi::INVALID_HANDLE_VALUE { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to find first volume" ); } (String::from_wide_null(&name), handle) } unsafe fn find_all_volumes() -> Vec<String> { let (first_volume, next_volume_handle) = find_first_volume(); let mut volumes = vec![first_volume]; loop { #[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); if winapi::um::fileapi::FindNextVolumeW( next_volume_handle, name.as_mut_ptr(), name.len() as minwindef::DWORD, ) == 0 { match winapi::um::errhandlingapi::GetLastError() { winerror::ERROR_NO_MORE_FILES => { winapi::um::fileapi::FindVolumeClose(next_volume_handle); return volumes; } err => crash!(err as i32, "failed to find next volume"), } } else { volumes.push(String::from_wide_null(&name)); } } } pub unsafe fn do_sync() -> isize
pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { flush_volume( Path::new(&path) .components() .next() .unwrap() .as_os_str() .to_str() .unwrap(), ); } 0 } } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<String> = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) .unwrap_or_default(); for f in &files { if !Path::new(&f).exists() { return Err(USimpleError::new( 1, format!("cannot stat {}: No such file or directory", f.quote()), )); } } #[allow(clippy::if_same_then_else)] if matches.is_present(options::FILE_SYSTEM) { #[cfg(any(target_os = "linux", target_os = "windows"))] syncfs(files); } else if matches.is_present(options::DATA) { #[cfg(target_os = "linux")] fdatasync(files); } else { sync(); } Ok(()) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILE_SYSTEM) .short('f') .long(options::FILE_SYSTEM) .conflicts_with(options::DATA) .help("sync the file systems that contain the files (Linux and Windows only)"), ) .arg( Arg::new(options::DATA) .short('d') .long(options::DATA) .conflicts_with(options::FILE_SYSTEM) .help("sync only file data, no unneeded metadata (Linux only)"), ) .arg( Arg::new(ARG_FILES) .multiple_occurrences(true) .takes_value(true), ) } fn sync() -> isize { unsafe { platform::do_sync() } } #[cfg(any(target_os = "linux", target_os = "windows"))] fn syncfs(files: Vec<String>) -> isize { unsafe { platform::do_syncfs(files) } } #[cfg(target_os = "linux")] fn fdatasync(files: Vec<String>) -> isize { unsafe { platform::do_fdatasync(files) } }
{ let volumes = find_all_volumes(); for vol in &volumes { flush_volume(vol); } 0 }
identifier_body
sync.rs
// * This file is part of the uutils coreutils package. // * // * (c) Alexander Fomin <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. /* Last synced with: sync (GNU coreutils) 8.13 */ extern crate libc; use clap::{crate_version, App, AppSettings, Arg}; use std::path::Path; use uucore::display::Quotable; use uucore::error::{UResult, USimpleError}; use uucore::format_usage; static ABOUT: &str = "Synchronize cached writes to persistent storage"; const USAGE: &str = "{} [OPTION]... FILE..."; pub mod options { pub static FILE_SYSTEM: &str = "file-system"; pub static DATA: &str = "data"; } static ARG_FILES: &str = "files"; #[cfg(unix)] mod platform { use super::libc; #[cfg(target_os = "linux")] use std::fs::File; #[cfg(target_os = "linux")] use std::os::unix::io::AsRawFd; pub unsafe fn do_sync() -> isize { libc::sync(); 0 } #[cfg(target_os = "linux")] pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_syncfs, fd); } 0 } #[cfg(target_os = "linux")] pub unsafe fn do_fdatasync(files: Vec<String>) -> isize { for path in files { let f = File::open(&path).unwrap(); let fd = f.as_raw_fd(); libc::syscall(libc::SYS_fdatasync, fd); } 0 } } #[cfg(windows)] mod platform { extern crate winapi; use self::winapi::shared::minwindef; use self::winapi::shared::winerror; use self::winapi::um::handleapi; use self::winapi::um::winbase; use self::winapi::um::winnt; use std::fs::OpenOptions; use std::mem; use std::os::windows::prelude::*; use std::path::Path; use uucore::crash; use uucore::wide::{FromWide, ToWide}; unsafe fn
(name: &str) { let name_wide = name.to_wide_null(); if winapi::um::fileapi::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED { let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash match OpenOptions::new().write(true).open(sliced_name) { Ok(file) => { if winapi::um::fileapi::FlushFileBuffers(file.as_raw_handle()) == 0 { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to flush file buffer" ); } } Err(e) => crash!( e.raw_os_error().unwrap_or(1), "failed to create volume handle" ), } } } unsafe fn find_first_volume() -> (String, winnt::HANDLE) { #[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); let handle = winapi::um::fileapi::FindFirstVolumeW( name.as_mut_ptr(), name.len() as minwindef::DWORD, ); if handle == handleapi::INVALID_HANDLE_VALUE { crash!( winapi::um::errhandlingapi::GetLastError() as i32, "failed to find first volume" ); } (String::from_wide_null(&name), handle) } unsafe fn find_all_volumes() -> Vec<String> { let (first_volume, next_volume_handle) = find_first_volume(); let mut volumes = vec![first_volume]; loop { #[allow(deprecated)] let mut name: [winnt::WCHAR; minwindef::MAX_PATH] = mem::uninitialized(); if winapi::um::fileapi::FindNextVolumeW( next_volume_handle, name.as_mut_ptr(), name.len() as minwindef::DWORD, ) == 0 { match winapi::um::errhandlingapi::GetLastError() { winerror::ERROR_NO_MORE_FILES => { winapi::um::fileapi::FindVolumeClose(next_volume_handle); return volumes; } err => crash!(err as i32, "failed to find next volume"), } } else { volumes.push(String::from_wide_null(&name)); } } } pub unsafe fn do_sync() -> isize { let volumes = find_all_volumes(); for vol in &volumes { flush_volume(vol); } 0 } pub unsafe fn do_syncfs(files: Vec<String>) -> isize { for path in files { flush_volume( Path::new(&path) .components() .next() .unwrap() .as_os_str() .to_str() .unwrap(), ); } 0 } } #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let files: Vec<String> = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) .unwrap_or_default(); for f in &files { if !Path::new(&f).exists() { return Err(USimpleError::new( 1, format!("cannot stat {}: No such file or directory", f.quote()), )); } } #[allow(clippy::if_same_then_else)] if matches.is_present(options::FILE_SYSTEM) { #[cfg(any(target_os = "linux", target_os = "windows"))] syncfs(files); } else if matches.is_present(options::DATA) { #[cfg(target_os = "linux")] fdatasync(files); } else { sync(); } Ok(()) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(format_usage(USAGE)) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::FILE_SYSTEM) .short('f') .long(options::FILE_SYSTEM) .conflicts_with(options::DATA) .help("sync the file systems that contain the files (Linux and Windows only)"), ) .arg( Arg::new(options::DATA) .short('d') .long(options::DATA) .conflicts_with(options::FILE_SYSTEM) .help("sync only file data, no unneeded metadata (Linux only)"), ) .arg( Arg::new(ARG_FILES) .multiple_occurrences(true) .takes_value(true), ) } fn sync() -> isize { unsafe { platform::do_sync() } } #[cfg(any(target_os = "linux", target_os = "windows"))] fn syncfs(files: Vec<String>) -> isize { unsafe { platform::do_syncfs(files) } } #[cfg(target_os = "linux")] fn fdatasync(files: Vec<String>) -> isize { unsafe { platform::do_fdatasync(files) } }
flush_volume
identifier_name
assignment2.py
''' author Lama Hamadeh ''' import pandas as pd import matplotlib.pyplot as plt import matplotlib import assignment2_helper as helper # Look pretty... matplotlib.style.use('ggplot') # Do * NOT * alter this line, until instructed! scaleFeatures = True #Features scaling (if it's false no scaling appears and that affects the 2D plot and the variance values) # TODO: Load up the dataset and remove any and all # Rows that have a nan. You should be a pro at this # by now ;-) # # .. your code here .. df=pd.read_csv('/Users/ADB3HAMADL/Desktop/Anaconda_Packages/DAT210x-master/Module4/Datasets/kidney_disease.csv',index_col = 0) df = df.reset_index(drop=True) #remove the index column df=df.dropna(axis=0) #remove any and all Rows that have a nan #print(df) # Create some color coded labels; the actual label feature # will be removed prior to executing PCA, since it's unsupervised. # You're only labeling by color so you can see the effects of PCA labels = ['red' if i=='ckd' else 'green' for i in df.classification] # TODO: Use an indexer to select only the following columns: # ['bgr','wc','rc'] # # .. your code here .. df=df[['bgr', 'rc','wc']] #select only the following columns: bgr, rc, and wc # TODO: Print out and check your dataframe's dtypes. You'll probably # want to call 'exit()' after you print it out so you can stop the # program's execution. # # You can either take a look at the dataset webpage in the attribute info # section: https://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease # or you can actually peek through the dataframe by printing a few rows. # What kind of data type should these three columns be? If Pandas didn't # properly detect and convert them to that data type for you, then use # an appropriate command to coerce these features into the right type. # # .. your code here .. print(df.dtypes) # df.rc = pd.to_numeric(df.rc, errors='coerce') # df.wc = pd.to_numeric(df.wc, errors='coerce') # # TODO: PCA Operates based on variance. The variable with the greatest # variance will dominate. Go ahead and peek into your data using a # command that will check the variance of every feature in your dataset. # Print out the results. Also print out the results of running .describe # on your dataset. # # Hint: If you don't see all three variables: 'bgr','wc' and 'rc', then # you probably didn't complete the previous step properly. # # .. your code here .. print(df.var()) # print(df.describe()) # # TODO: This method assumes your dataframe is called df. If it isn't, # make the appropriate changes. Don't alter the code in scaleFeatures() # just yet though! # # .. your code adjustment here .. if scaleFeatures: df = helper.scaleFeatures(df) # TODO: Run PCA on your dataset and reduce it to 2 components # Ensure your PCA instance is saved in a variable called 'pca', # and that the results of your transformation are saved in 'T'. # # .. your code here ..
pca.fit(df) decomposition.PCA(copy=True, n_components=2, whiten=False) T= pca.transform(df) # Plot the transformed data as a scatter plot. Recall that transforming # the data will result in a NumPy NDArray. You can either use MatPlotLib # to graph it directly, or you can convert it to DataFrame and have pandas # do it for you. # # Since we've already demonstrated how to plot directly with MatPlotLib in # Module4/assignment1.py, this time we'll convert to a Pandas Dataframe. # # Since we transformed via PCA, we no longer have column names. We know we # are in P.C. space, so we'll just define the coordinates accordingly: ax = helper.drawVectors(T, pca.components_, df.columns.values, plt, scaleFeatures) T = pd.DataFrame(T) T.columns = ['component1', 'component2'] T.plot.scatter(x='component1', y='component2', marker='o', c=labels, alpha=0.75, ax=ax) plt.show()
from sklearn import decomposition pca = decomposition.PCA(n_components=2)
random_line_split
assignment2.py
''' author Lama Hamadeh ''' import pandas as pd import matplotlib.pyplot as plt import matplotlib import assignment2_helper as helper # Look pretty... matplotlib.style.use('ggplot') # Do * NOT * alter this line, until instructed! scaleFeatures = True #Features scaling (if it's false no scaling appears and that affects the 2D plot and the variance values) # TODO: Load up the dataset and remove any and all # Rows that have a nan. You should be a pro at this # by now ;-) # # .. your code here .. df=pd.read_csv('/Users/ADB3HAMADL/Desktop/Anaconda_Packages/DAT210x-master/Module4/Datasets/kidney_disease.csv',index_col = 0) df = df.reset_index(drop=True) #remove the index column df=df.dropna(axis=0) #remove any and all Rows that have a nan #print(df) # Create some color coded labels; the actual label feature # will be removed prior to executing PCA, since it's unsupervised. # You're only labeling by color so you can see the effects of PCA labels = ['red' if i=='ckd' else 'green' for i in df.classification] # TODO: Use an indexer to select only the following columns: # ['bgr','wc','rc'] # # .. your code here .. df=df[['bgr', 'rc','wc']] #select only the following columns: bgr, rc, and wc # TODO: Print out and check your dataframe's dtypes. You'll probably # want to call 'exit()' after you print it out so you can stop the # program's execution. # # You can either take a look at the dataset webpage in the attribute info # section: https://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease # or you can actually peek through the dataframe by printing a few rows. # What kind of data type should these three columns be? If Pandas didn't # properly detect and convert them to that data type for you, then use # an appropriate command to coerce these features into the right type. # # .. your code here .. print(df.dtypes) # df.rc = pd.to_numeric(df.rc, errors='coerce') # df.wc = pd.to_numeric(df.wc, errors='coerce') # # TODO: PCA Operates based on variance. The variable with the greatest # variance will dominate. Go ahead and peek into your data using a # command that will check the variance of every feature in your dataset. # Print out the results. Also print out the results of running .describe # on your dataset. # # Hint: If you don't see all three variables: 'bgr','wc' and 'rc', then # you probably didn't complete the previous step properly. # # .. your code here .. print(df.var()) # print(df.describe()) # # TODO: This method assumes your dataframe is called df. If it isn't, # make the appropriate changes. Don't alter the code in scaleFeatures() # just yet though! # # .. your code adjustment here .. if scaleFeatures:
# TODO: Run PCA on your dataset and reduce it to 2 components # Ensure your PCA instance is saved in a variable called 'pca', # and that the results of your transformation are saved in 'T'. # # .. your code here .. from sklearn import decomposition pca = decomposition.PCA(n_components=2) pca.fit(df) decomposition.PCA(copy=True, n_components=2, whiten=False) T= pca.transform(df) # Plot the transformed data as a scatter plot. Recall that transforming # the data will result in a NumPy NDArray. You can either use MatPlotLib # to graph it directly, or you can convert it to DataFrame and have pandas # do it for you. # # Since we've already demonstrated how to plot directly with MatPlotLib in # Module4/assignment1.py, this time we'll convert to a Pandas Dataframe. # # Since we transformed via PCA, we no longer have column names. We know we # are in P.C. space, so we'll just define the coordinates accordingly: ax = helper.drawVectors(T, pca.components_, df.columns.values, plt, scaleFeatures) T = pd.DataFrame(T) T.columns = ['component1', 'component2'] T.plot.scatter(x='component1', y='component2', marker='o', c=labels, alpha=0.75, ax=ax) plt.show()
df = helper.scaleFeatures(df)
conditional_block
docSearch.js
class DocSearchInterface extends ReactSingleAjax { constructor(props) { super(props); let urlP = getURLParams(); this.state = { termKind: urlP.termKind || "lemmas", query: urlP.query || "", operation: urlP.operation || "OR" }; this.init(); } componentDidMount() { if(this.state.query) { this.onFind(null); } } onFind(evt) { // one request at a time... if(this.waiting()) return; let request = {}; request.termKind = this.state.termKind; request.query = this.state.query; request.operation = this.state.operation; pushURLParams(request); this.send("/api/MatchDocuments", request); } render() { let results = ""; if(this.error()) { results = this.errorMessage(); } if(this.response()) { results = <pre key="json">{JSON.stringify(this.response())}</pre>; } return <div> <div>Document Search</div> <textarea value={this.state.query} onChange={(x) => this.setState({query: x.target.value}) } /> <SelectWidget opts={TermKindOpts} selected={this.state.termKind} onChange={(x) => this.setState({termKind: x})} /> <SelectWidget opts={OperationKinds} selected={this.state.operation} onChange={(x) => this.setState({operation: x})} /> <Button label="Find!" onClick={(evt) => this.onFind(evt)}/> <DocumentResults response={this.state.response} /> </div> } } class DocumentResults extends React.Component {
() { let resp = this.props.response; if(resp == null) { return <span />; } let results = _(resp.results).map(function(obj) { return <li key={obj.id}><DocumentLink id={obj.id} name={obj.name} /></li> }).value(); return <div> <label>Query Terms: <i>{strjoin(resp.queryTerms)}</i></label> <ul>{results}</ul> </div>; } }
render
identifier_name
docSearch.js
class DocSearchInterface extends ReactSingleAjax { constructor(props) { super(props); let urlP = getURLParams(); this.state = { termKind: urlP.termKind || "lemmas", query: urlP.query || "", operation: urlP.operation || "OR" }; this.init(); } componentDidMount() { if(this.state.query) { this.onFind(null); } } onFind(evt) { // one request at a time... if(this.waiting()) return; let request = {}; request.termKind = this.state.termKind; request.query = this.state.query; request.operation = this.state.operation; pushURLParams(request); this.send("/api/MatchDocuments", request); } render() { let results = ""; if(this.error())
if(this.response()) { results = <pre key="json">{JSON.stringify(this.response())}</pre>; } return <div> <div>Document Search</div> <textarea value={this.state.query} onChange={(x) => this.setState({query: x.target.value}) } /> <SelectWidget opts={TermKindOpts} selected={this.state.termKind} onChange={(x) => this.setState({termKind: x})} /> <SelectWidget opts={OperationKinds} selected={this.state.operation} onChange={(x) => this.setState({operation: x})} /> <Button label="Find!" onClick={(evt) => this.onFind(evt)}/> <DocumentResults response={this.state.response} /> </div> } } class DocumentResults extends React.Component { render() { let resp = this.props.response; if(resp == null) { return <span />; } let results = _(resp.results).map(function(obj) { return <li key={obj.id}><DocumentLink id={obj.id} name={obj.name} /></li> }).value(); return <div> <label>Query Terms: <i>{strjoin(resp.queryTerms)}</i></label> <ul>{results}</ul> </div>; } }
{ results = this.errorMessage(); }
conditional_block
docSearch.js
class DocSearchInterface extends ReactSingleAjax { constructor(props) { super(props); let urlP = getURLParams(); this.state = { termKind: urlP.termKind || "lemmas", query: urlP.query || "", operation: urlP.operation || "OR" }; this.init(); } componentDidMount() { if(this.state.query) { this.onFind(null); } }
let request = {}; request.termKind = this.state.termKind; request.query = this.state.query; request.operation = this.state.operation; pushURLParams(request); this.send("/api/MatchDocuments", request); } render() { let results = ""; if(this.error()) { results = this.errorMessage(); } if(this.response()) { results = <pre key="json">{JSON.stringify(this.response())}</pre>; } return <div> <div>Document Search</div> <textarea value={this.state.query} onChange={(x) => this.setState({query: x.target.value}) } /> <SelectWidget opts={TermKindOpts} selected={this.state.termKind} onChange={(x) => this.setState({termKind: x})} /> <SelectWidget opts={OperationKinds} selected={this.state.operation} onChange={(x) => this.setState({operation: x})} /> <Button label="Find!" onClick={(evt) => this.onFind(evt)}/> <DocumentResults response={this.state.response} /> </div> } } class DocumentResults extends React.Component { render() { let resp = this.props.response; if(resp == null) { return <span />; } let results = _(resp.results).map(function(obj) { return <li key={obj.id}><DocumentLink id={obj.id} name={obj.name} /></li> }).value(); return <div> <label>Query Terms: <i>{strjoin(resp.queryTerms)}</i></label> <ul>{results}</ul> </div>; } }
onFind(evt) { // one request at a time... if(this.waiting()) return;
random_line_split
custom_association_rules.py
import sys sys.path.append("..")
LE = "leite" PA = "pao" SU = "suco" OV = "ovos" CA = "cafe" BI = "biscoito" AR = "arroz" FE = "feijao" CE = "cerveja" MA = "manteiga" data = [[CA, PA, MA], [LE, CE, PA, MA], [CA, PA, MA], [LE, CA, PA, MA], [CE], [MA], [PA], [FE], [AR, FE], [AR]] compare(data, 0.0000000001, 5.0, 0)
from data_mining.association_rule.base import rules, lift, support from data_mining.association_rule.apriori import apriori from data_mining.association_rule.liftmin import apriorilift from pat_data_association_rules import compare
random_line_split
utils.py
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import base64 from datetime import datetime, timedelta import functools import json import os import time import yaml import jinja2 import jmespath from dateutil import parser from dateutil.tz import gettz, tzutc try: from botocore.exceptions import ClientError except ImportError: # pragma: no cover pass # Azure provider class Providers: AWS = 0 Azure = 1 def get_jinja_env(template_folders): env = jinja2.Environment(trim_blocks=True, autoescape=False) # nosec nosemgrep env.filters['yaml_safe'] = functools.partial(yaml.safe_dump, default_flow_style=False) env.filters['date_time_format'] = date_time_format env.filters['get_date_time_delta'] = get_date_time_delta env.filters['from_json'] = json.loads env.filters['get_date_age'] = get_date_age env.globals['format_resource'] = resource_format env.globals['format_struct'] = format_struct env.globals['resource_tag'] = get_resource_tag_value env.globals['get_resource_tag_value'] = get_resource_tag_value env.globals['search'] = jmespath.search env.loader = jinja2.FileSystemLoader(template_folders) return env def get_rendered_jinja( target, sqs_message, resources, logger, specified_template, default_template, template_folders): env = get_jinja_env(template_folders) mail_template = sqs_message['action'].get(specified_template, default_template) if not os.path.isabs(mail_template): mail_template = '%s.j2' % mail_template try: template = env.get_template(mail_template) except Exception as error_msg: logger.error("Invalid template reference %s\n%s" % (mail_template, error_msg)) return # recast seconds since epoch as utc iso datestring, template # authors can use date_time_format helper func to convert local # tz. if no execution start time was passed use current time. execution_start = datetime.utcfromtimestamp( sqs_message.get( 'execution_start', time.mktime( datetime.utcnow().timetuple()) )).isoformat() rendered_jinja = template.render( recipient=target, resources=resources, account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], execution_start=execution_start, region=sqs_message.get('region', '')) return rendered_jinja # eg, target_tag_keys could be resource-owners ['Owners', 'SupportTeam'] # and this function would go through the resource and look for any tag keys # that match Owners or SupportTeam, and return those values as targets def get_resource_tag_targets(resource, target_tag_keys): if 'Tags' not in resource: return [] if isinstance(resource['Tags'], dict): tags = resource['Tags'] else: tags = {tag['Key']: tag['Value'] for tag in resource['Tags']} targets = [] for target_tag_key in target_tag_keys: if target_tag_key in tags: targets.append(tags[target_tag_key]) return targets def get_message_subject(sqs_message): default_subject = 'Custodian notification - %s' % (sqs_message['policy']['name']) subject = sqs_message['action'].get('subject', default_subject) jinja_template = jinja2.Template(subject) subject = jinja_template.render( account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], region=sqs_message.get('region', '') ) return subject def setup_defaults(config): config.setdefault('region', 'us-east-1') config.setdefault('ses_region', config.get('region')) config.setdefault('memory', 1024) config.setdefault('runtime', 'python3.7') config.setdefault('timeout', 300) config.setdefault('subnets', None) config.setdefault('security_groups', None) config.setdefault('contact_tags', []) config.setdefault('ldap_uri', None) config.setdefault('ldap_bind_dn', None) config.setdefault('ldap_bind_user', None) config.setdefault('ldap_bind_password', None) config.setdefault('endpoint_url', None) config.setdefault('datadog_api_key', None) config.setdefault('slack_token', None) config.setdefault('slack_webhook', None) def date_time_format(utc_str, tz_str='US/Eastern', format='%Y %b %d %H:%M %Z'): return parser.parse(utc_str).astimezone(gettz(tz_str)).strftime(format) def get_date_time_delta(delta): return str(datetime.now().replace(tzinfo=gettz('UTC')) + timedelta(delta)) def get_date_age(date): return (datetime.now(tz=tzutc()) - parser.parse(date)).days def format_struct(evt): return json.dumps(evt, indent=2, ensure_ascii=False) def get_resource_tag_value(resource, k): for t in resource.get('Tags', []): if t['Key'] == k: return t['Value'] return '' def strip_prefix(value, prefix): if value.startswith(prefix): return value[len(prefix):] return value def resource_format(resource, resource_type): if resource_type.startswith('aws.'): resource_type = strip_prefix(resource_type, 'aws.') if resource_type == 'ec2': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s %s %s %s" % ( resource['InstanceId'], resource.get('VpcId', 'NO VPC!'), resource['InstanceType'], resource.get('LaunchTime'), tag_map.get('Name', ''), resource.get('PrivateIpAddress')) elif resource_type == 'ami': return "%s %s %s" % ( resource.get('Name'), resource['ImageId'], resource['CreationDate']) elif resource_type == 'sagemaker-notebook': return "%s" % (resource['NotebookInstanceName']) elif resource_type == 's3': return "%s" % (resource['Name']) elif resource_type == 'ebs': return "%s %s %s %s" % ( resource['VolumeId'], resource['Size'], resource['State'], resource['CreateTime']) elif resource_type == 'rds': return "%s %s %s %s" % ( resource['DBInstanceIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['DBInstanceClass'], resource['AllocatedStorage']) elif resource_type == 'rds-cluster': return "%s %s %s" % ( resource['DBClusterIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['AllocatedStorage']) elif resource_type == 'asg': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s" % ( resource['AutoScalingGroupName'], tag_map.get('Name', ''), "instances: %d" % (len(resource.get('Instances', [])))) elif resource_type == 'elb': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} if 'ProhibitedPolicies' in resource: return "%s %s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones']), "prohibited_policies: %s" % ','.join( resource['ProhibitedPolicies'])) return "%s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones'])) elif resource_type == 'redshift': return "%s %s %s" % ( resource['ClusterIdentifier'], 'nodes:%d' % len(resource['ClusterNodes']), 'encrypted:%s' % resource['Encrypted']) elif resource_type == 'emr': return "%s status:%s" % ( resource['Id'], resource['Status']['State']) elif resource_type == 'cfn': return "%s" % ( resource['StackName']) elif resource_type == 'launch-config': return "%s" % ( resource['LaunchConfigurationName']) elif resource_type == 'security-group': name = resource.get('GroupName', '') for t in resource.get('Tags', ()): if t['Key'] == 'Name': name = t['Value'] return "%s %s %s inrules: %d outrules: %d" % ( name, resource['GroupId'], resource.get('VpcId', 'na'), len(resource.get('IpPermissions', ())), len(resource.get('IpPermissionsEgress', ()))) elif resource_type == 'log-group': if 'lastWrite' in resource: return "name: %s last_write: %s" % ( resource['logGroupName'], resource['lastWrite']) return "name: %s" % (resource['logGroupName']) elif resource_type == 'cache-cluster': return "name: %s created: %s status: %s" % ( resource['CacheClusterId'], resource['CacheClusterCreateTime'], resource['CacheClusterStatus']) elif resource_type == 'cache-snapshot': cid = resource.get('CacheClusterId') if cid is None: cid = ', '.join([ ns['CacheClusterId'] for ns in resource['NodeSnapshots']]) return "name: %s cluster: %s source: %s" % ( resource['SnapshotName'], cid, resource['SnapshotSource']) elif resource_type == 'redshift-snapshot': return "name: %s db: %s" % ( resource['SnapshotIdentifier'], resource['DBName']) elif resource_type == 'ebs-snapshot': return "name: %s date: %s" % ( resource['SnapshotId'], resource['StartTime']) elif resource_type == 'subnet': return "%s %s %s %s %s %s" % ( resource['SubnetId'], resource['VpcId'], resource['AvailabilityZone'], resource['State'], resource['CidrBlock'], resource['AvailableIpAddressCount']) elif resource_type == 'account': return " %s %s" % ( resource['account_id'], resource['account_name']) elif resource_type == 'cloudtrail': return "%s" % ( resource['Name']) elif resource_type == 'vpc': return "%s " % ( resource['VpcId']) elif resource_type == 'iam-group': return " %s %s %s" % ( resource['GroupName'], resource['Arn'], resource['CreateDate']) elif resource_type == 'rds-snapshot': return " %s %s %s" % ( resource['DBSnapshotIdentifier'], resource['DBInstanceIdentifier'], resource['SnapshotCreateTime']) elif resource_type == 'iam-user':
elif resource_type == 'iam-role': return " %s %s " % ( resource['RoleName'], resource['CreateDate']) elif resource_type == 'iam-policy': return " %s " % ( resource['PolicyName']) elif resource_type == 'iam-profile': return " %s " % ( resource['InstanceProfileId']) elif resource_type == 'dynamodb-table': return "name: %s created: %s status: %s" % ( resource['TableName'], resource['CreationDateTime'], resource['TableStatus']) elif resource_type == "sqs": return "QueueURL: %s QueueArn: %s " % ( resource['QueueUrl'], resource['QueueArn']) elif resource_type == "efs": return "name: %s id: %s state: %s" % ( resource['Name'], resource['FileSystemId'], resource['LifeCycleState'] ) elif resource_type == "network-addr": return "ip: %s id: %s scope: %s" % ( resource['PublicIp'], resource['AllocationId'], resource['Domain'] ) elif resource_type == "route-table": return "id: %s vpc: %s" % ( resource['RouteTableId'], resource['VpcId'] ) elif resource_type == "app-elb": return "arn: %s zones: %s scheme: %s" % ( resource['LoadBalancerArn'], len(resource['AvailabilityZones']), resource['Scheme']) elif resource_type == "nat-gateway": return "id: %s state: %s vpc: %s" % ( resource['NatGatewayId'], resource['State'], resource['VpcId']) elif resource_type == "internet-gateway": return "id: %s attachments: %s" % ( resource['InternetGatewayId'], len(resource['Attachments'])) elif resource_type == 'lambda': return "Name: %s RunTime: %s \n" % ( resource['FunctionName'], resource['Runtime']) else: return "%s" % format_struct(resource) def get_provider(mailer_config): if mailer_config.get('queue_url', '').startswith('asq://'): return Providers.Azure return Providers.AWS def kms_decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): try: kms = session.client('kms') return kms.decrypt( CiphertextBlob=base64.b64decode(config[encrypted_field]))[ 'Plaintext'].decode('utf8') except (TypeError, base64.binascii.Error) as e: logger.warning( "Error: %s Unable to base64 decode %s, will assume plaintext." % (e, encrypted_field)) except ClientError as e: if e.response['Error']['Code'] != 'InvalidCiphertextException': raise logger.warning( "Error: %s Unable to decrypt %s with kms, will assume plaintext." % (e, encrypted_field)) return config[encrypted_field] else: logger.debug("No encrypted value to decrypt.") return None def decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): provider = get_provider(config) if provider == Providers.Azure: from c7n_mailer.azure_mailer.utils import azure_decrypt return azure_decrypt(config, logger, session, encrypted_field) elif provider == Providers.AWS: return kms_decrypt(config, logger, session, encrypted_field) else: raise Exception("Unknown provider") else: logger.debug("No encrypted value to decrypt.") return None # https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html def get_aws_username_from_event(logger, event): if event is None: return None identity = event.get('detail', {}).get('userIdentity', {}) if not identity: logger.warning("Could not get recipient from event \n %s" % ( format_struct(event))) return None if identity['type'] == 'AssumedRole': logger.debug( 'In some cases there is no ldap uid is associated with AssumedRole: %s', identity['arn']) logger.debug( 'We will try to assume that identity is in the AssumedRoleSessionName') user = identity['arn'].rsplit('/', 1)[-1] if user is None or user.startswith('i-') or user.startswith('awslambda'): return None if ':' in user: user = user.split(':', 1)[-1] return user if identity['type'] == 'IAMUser' or identity['type'] == 'WebIdentityUser': return identity['userName'] if identity['type'] == 'Root': return None # this conditional is left here as a last resort, it should # be better documented with an example UserIdentity json if ':' in identity['principalId']: user_id = identity['principalId'].split(':', 1)[-1] else: user_id = identity['principalId'] return user_id
return " %s " % ( resource['UserName'])
conditional_block
utils.py
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import base64 from datetime import datetime, timedelta import functools import json import os import time import yaml import jinja2 import jmespath from dateutil import parser from dateutil.tz import gettz, tzutc try: from botocore.exceptions import ClientError except ImportError: # pragma: no cover pass # Azure provider class Providers: AWS = 0 Azure = 1 def get_jinja_env(template_folders): env = jinja2.Environment(trim_blocks=True, autoescape=False) # nosec nosemgrep env.filters['yaml_safe'] = functools.partial(yaml.safe_dump, default_flow_style=False) env.filters['date_time_format'] = date_time_format env.filters['get_date_time_delta'] = get_date_time_delta env.filters['from_json'] = json.loads env.filters['get_date_age'] = get_date_age env.globals['format_resource'] = resource_format env.globals['format_struct'] = format_struct env.globals['resource_tag'] = get_resource_tag_value env.globals['get_resource_tag_value'] = get_resource_tag_value env.globals['search'] = jmespath.search env.loader = jinja2.FileSystemLoader(template_folders) return env def get_rendered_jinja( target, sqs_message, resources, logger, specified_template, default_template, template_folders): env = get_jinja_env(template_folders) mail_template = sqs_message['action'].get(specified_template, default_template) if not os.path.isabs(mail_template): mail_template = '%s.j2' % mail_template try: template = env.get_template(mail_template) except Exception as error_msg: logger.error("Invalid template reference %s\n%s" % (mail_template, error_msg)) return # recast seconds since epoch as utc iso datestring, template # authors can use date_time_format helper func to convert local # tz. if no execution start time was passed use current time. execution_start = datetime.utcfromtimestamp( sqs_message.get( 'execution_start', time.mktime( datetime.utcnow().timetuple()) )).isoformat() rendered_jinja = template.render( recipient=target, resources=resources, account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], execution_start=execution_start, region=sqs_message.get('region', '')) return rendered_jinja # eg, target_tag_keys could be resource-owners ['Owners', 'SupportTeam'] # and this function would go through the resource and look for any tag keys # that match Owners or SupportTeam, and return those values as targets def get_resource_tag_targets(resource, target_tag_keys): if 'Tags' not in resource: return [] if isinstance(resource['Tags'], dict): tags = resource['Tags'] else: tags = {tag['Key']: tag['Value'] for tag in resource['Tags']} targets = [] for target_tag_key in target_tag_keys: if target_tag_key in tags: targets.append(tags[target_tag_key]) return targets def
(sqs_message): default_subject = 'Custodian notification - %s' % (sqs_message['policy']['name']) subject = sqs_message['action'].get('subject', default_subject) jinja_template = jinja2.Template(subject) subject = jinja_template.render( account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], region=sqs_message.get('region', '') ) return subject def setup_defaults(config): config.setdefault('region', 'us-east-1') config.setdefault('ses_region', config.get('region')) config.setdefault('memory', 1024) config.setdefault('runtime', 'python3.7') config.setdefault('timeout', 300) config.setdefault('subnets', None) config.setdefault('security_groups', None) config.setdefault('contact_tags', []) config.setdefault('ldap_uri', None) config.setdefault('ldap_bind_dn', None) config.setdefault('ldap_bind_user', None) config.setdefault('ldap_bind_password', None) config.setdefault('endpoint_url', None) config.setdefault('datadog_api_key', None) config.setdefault('slack_token', None) config.setdefault('slack_webhook', None) def date_time_format(utc_str, tz_str='US/Eastern', format='%Y %b %d %H:%M %Z'): return parser.parse(utc_str).astimezone(gettz(tz_str)).strftime(format) def get_date_time_delta(delta): return str(datetime.now().replace(tzinfo=gettz('UTC')) + timedelta(delta)) def get_date_age(date): return (datetime.now(tz=tzutc()) - parser.parse(date)).days def format_struct(evt): return json.dumps(evt, indent=2, ensure_ascii=False) def get_resource_tag_value(resource, k): for t in resource.get('Tags', []): if t['Key'] == k: return t['Value'] return '' def strip_prefix(value, prefix): if value.startswith(prefix): return value[len(prefix):] return value def resource_format(resource, resource_type): if resource_type.startswith('aws.'): resource_type = strip_prefix(resource_type, 'aws.') if resource_type == 'ec2': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s %s %s %s" % ( resource['InstanceId'], resource.get('VpcId', 'NO VPC!'), resource['InstanceType'], resource.get('LaunchTime'), tag_map.get('Name', ''), resource.get('PrivateIpAddress')) elif resource_type == 'ami': return "%s %s %s" % ( resource.get('Name'), resource['ImageId'], resource['CreationDate']) elif resource_type == 'sagemaker-notebook': return "%s" % (resource['NotebookInstanceName']) elif resource_type == 's3': return "%s" % (resource['Name']) elif resource_type == 'ebs': return "%s %s %s %s" % ( resource['VolumeId'], resource['Size'], resource['State'], resource['CreateTime']) elif resource_type == 'rds': return "%s %s %s %s" % ( resource['DBInstanceIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['DBInstanceClass'], resource['AllocatedStorage']) elif resource_type == 'rds-cluster': return "%s %s %s" % ( resource['DBClusterIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['AllocatedStorage']) elif resource_type == 'asg': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s" % ( resource['AutoScalingGroupName'], tag_map.get('Name', ''), "instances: %d" % (len(resource.get('Instances', [])))) elif resource_type == 'elb': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} if 'ProhibitedPolicies' in resource: return "%s %s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones']), "prohibited_policies: %s" % ','.join( resource['ProhibitedPolicies'])) return "%s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones'])) elif resource_type == 'redshift': return "%s %s %s" % ( resource['ClusterIdentifier'], 'nodes:%d' % len(resource['ClusterNodes']), 'encrypted:%s' % resource['Encrypted']) elif resource_type == 'emr': return "%s status:%s" % ( resource['Id'], resource['Status']['State']) elif resource_type == 'cfn': return "%s" % ( resource['StackName']) elif resource_type == 'launch-config': return "%s" % ( resource['LaunchConfigurationName']) elif resource_type == 'security-group': name = resource.get('GroupName', '') for t in resource.get('Tags', ()): if t['Key'] == 'Name': name = t['Value'] return "%s %s %s inrules: %d outrules: %d" % ( name, resource['GroupId'], resource.get('VpcId', 'na'), len(resource.get('IpPermissions', ())), len(resource.get('IpPermissionsEgress', ()))) elif resource_type == 'log-group': if 'lastWrite' in resource: return "name: %s last_write: %s" % ( resource['logGroupName'], resource['lastWrite']) return "name: %s" % (resource['logGroupName']) elif resource_type == 'cache-cluster': return "name: %s created: %s status: %s" % ( resource['CacheClusterId'], resource['CacheClusterCreateTime'], resource['CacheClusterStatus']) elif resource_type == 'cache-snapshot': cid = resource.get('CacheClusterId') if cid is None: cid = ', '.join([ ns['CacheClusterId'] for ns in resource['NodeSnapshots']]) return "name: %s cluster: %s source: %s" % ( resource['SnapshotName'], cid, resource['SnapshotSource']) elif resource_type == 'redshift-snapshot': return "name: %s db: %s" % ( resource['SnapshotIdentifier'], resource['DBName']) elif resource_type == 'ebs-snapshot': return "name: %s date: %s" % ( resource['SnapshotId'], resource['StartTime']) elif resource_type == 'subnet': return "%s %s %s %s %s %s" % ( resource['SubnetId'], resource['VpcId'], resource['AvailabilityZone'], resource['State'], resource['CidrBlock'], resource['AvailableIpAddressCount']) elif resource_type == 'account': return " %s %s" % ( resource['account_id'], resource['account_name']) elif resource_type == 'cloudtrail': return "%s" % ( resource['Name']) elif resource_type == 'vpc': return "%s " % ( resource['VpcId']) elif resource_type == 'iam-group': return " %s %s %s" % ( resource['GroupName'], resource['Arn'], resource['CreateDate']) elif resource_type == 'rds-snapshot': return " %s %s %s" % ( resource['DBSnapshotIdentifier'], resource['DBInstanceIdentifier'], resource['SnapshotCreateTime']) elif resource_type == 'iam-user': return " %s " % ( resource['UserName']) elif resource_type == 'iam-role': return " %s %s " % ( resource['RoleName'], resource['CreateDate']) elif resource_type == 'iam-policy': return " %s " % ( resource['PolicyName']) elif resource_type == 'iam-profile': return " %s " % ( resource['InstanceProfileId']) elif resource_type == 'dynamodb-table': return "name: %s created: %s status: %s" % ( resource['TableName'], resource['CreationDateTime'], resource['TableStatus']) elif resource_type == "sqs": return "QueueURL: %s QueueArn: %s " % ( resource['QueueUrl'], resource['QueueArn']) elif resource_type == "efs": return "name: %s id: %s state: %s" % ( resource['Name'], resource['FileSystemId'], resource['LifeCycleState'] ) elif resource_type == "network-addr": return "ip: %s id: %s scope: %s" % ( resource['PublicIp'], resource['AllocationId'], resource['Domain'] ) elif resource_type == "route-table": return "id: %s vpc: %s" % ( resource['RouteTableId'], resource['VpcId'] ) elif resource_type == "app-elb": return "arn: %s zones: %s scheme: %s" % ( resource['LoadBalancerArn'], len(resource['AvailabilityZones']), resource['Scheme']) elif resource_type == "nat-gateway": return "id: %s state: %s vpc: %s" % ( resource['NatGatewayId'], resource['State'], resource['VpcId']) elif resource_type == "internet-gateway": return "id: %s attachments: %s" % ( resource['InternetGatewayId'], len(resource['Attachments'])) elif resource_type == 'lambda': return "Name: %s RunTime: %s \n" % ( resource['FunctionName'], resource['Runtime']) else: return "%s" % format_struct(resource) def get_provider(mailer_config): if mailer_config.get('queue_url', '').startswith('asq://'): return Providers.Azure return Providers.AWS def kms_decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): try: kms = session.client('kms') return kms.decrypt( CiphertextBlob=base64.b64decode(config[encrypted_field]))[ 'Plaintext'].decode('utf8') except (TypeError, base64.binascii.Error) as e: logger.warning( "Error: %s Unable to base64 decode %s, will assume plaintext." % (e, encrypted_field)) except ClientError as e: if e.response['Error']['Code'] != 'InvalidCiphertextException': raise logger.warning( "Error: %s Unable to decrypt %s with kms, will assume plaintext." % (e, encrypted_field)) return config[encrypted_field] else: logger.debug("No encrypted value to decrypt.") return None def decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): provider = get_provider(config) if provider == Providers.Azure: from c7n_mailer.azure_mailer.utils import azure_decrypt return azure_decrypt(config, logger, session, encrypted_field) elif provider == Providers.AWS: return kms_decrypt(config, logger, session, encrypted_field) else: raise Exception("Unknown provider") else: logger.debug("No encrypted value to decrypt.") return None # https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html def get_aws_username_from_event(logger, event): if event is None: return None identity = event.get('detail', {}).get('userIdentity', {}) if not identity: logger.warning("Could not get recipient from event \n %s" % ( format_struct(event))) return None if identity['type'] == 'AssumedRole': logger.debug( 'In some cases there is no ldap uid is associated with AssumedRole: %s', identity['arn']) logger.debug( 'We will try to assume that identity is in the AssumedRoleSessionName') user = identity['arn'].rsplit('/', 1)[-1] if user is None or user.startswith('i-') or user.startswith('awslambda'): return None if ':' in user: user = user.split(':', 1)[-1] return user if identity['type'] == 'IAMUser' or identity['type'] == 'WebIdentityUser': return identity['userName'] if identity['type'] == 'Root': return None # this conditional is left here as a last resort, it should # be better documented with an example UserIdentity json if ':' in identity['principalId']: user_id = identity['principalId'].split(':', 1)[-1] else: user_id = identity['principalId'] return user_id
get_message_subject
identifier_name
utils.py
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import base64 from datetime import datetime, timedelta import functools import json import os import time import yaml import jinja2 import jmespath from dateutil import parser from dateutil.tz import gettz, tzutc try: from botocore.exceptions import ClientError except ImportError: # pragma: no cover pass # Azure provider class Providers: AWS = 0 Azure = 1 def get_jinja_env(template_folders): env = jinja2.Environment(trim_blocks=True, autoescape=False) # nosec nosemgrep env.filters['yaml_safe'] = functools.partial(yaml.safe_dump, default_flow_style=False) env.filters['date_time_format'] = date_time_format env.filters['get_date_time_delta'] = get_date_time_delta env.filters['from_json'] = json.loads env.filters['get_date_age'] = get_date_age env.globals['format_resource'] = resource_format env.globals['format_struct'] = format_struct env.globals['resource_tag'] = get_resource_tag_value env.globals['get_resource_tag_value'] = get_resource_tag_value env.globals['search'] = jmespath.search env.loader = jinja2.FileSystemLoader(template_folders) return env def get_rendered_jinja( target, sqs_message, resources, logger, specified_template, default_template, template_folders): env = get_jinja_env(template_folders) mail_template = sqs_message['action'].get(specified_template, default_template) if not os.path.isabs(mail_template): mail_template = '%s.j2' % mail_template try: template = env.get_template(mail_template) except Exception as error_msg: logger.error("Invalid template reference %s\n%s" % (mail_template, error_msg)) return # recast seconds since epoch as utc iso datestring, template # authors can use date_time_format helper func to convert local # tz. if no execution start time was passed use current time. execution_start = datetime.utcfromtimestamp( sqs_message.get( 'execution_start', time.mktime( datetime.utcnow().timetuple()) )).isoformat() rendered_jinja = template.render( recipient=target, resources=resources, account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], execution_start=execution_start, region=sqs_message.get('region', '')) return rendered_jinja # eg, target_tag_keys could be resource-owners ['Owners', 'SupportTeam'] # and this function would go through the resource and look for any tag keys # that match Owners or SupportTeam, and return those values as targets def get_resource_tag_targets(resource, target_tag_keys): if 'Tags' not in resource: return [] if isinstance(resource['Tags'], dict): tags = resource['Tags'] else: tags = {tag['Key']: tag['Value'] for tag in resource['Tags']} targets = [] for target_tag_key in target_tag_keys: if target_tag_key in tags: targets.append(tags[target_tag_key]) return targets def get_message_subject(sqs_message): default_subject = 'Custodian notification - %s' % (sqs_message['policy']['name']) subject = sqs_message['action'].get('subject', default_subject) jinja_template = jinja2.Template(subject) subject = jinja_template.render( account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], region=sqs_message.get('region', '') ) return subject def setup_defaults(config): config.setdefault('region', 'us-east-1') config.setdefault('ses_region', config.get('region')) config.setdefault('memory', 1024) config.setdefault('runtime', 'python3.7') config.setdefault('timeout', 300) config.setdefault('subnets', None) config.setdefault('security_groups', None) config.setdefault('contact_tags', []) config.setdefault('ldap_uri', None) config.setdefault('ldap_bind_dn', None) config.setdefault('ldap_bind_user', None) config.setdefault('ldap_bind_password', None) config.setdefault('endpoint_url', None) config.setdefault('datadog_api_key', None) config.setdefault('slack_token', None) config.setdefault('slack_webhook', None) def date_time_format(utc_str, tz_str='US/Eastern', format='%Y %b %d %H:%M %Z'): return parser.parse(utc_str).astimezone(gettz(tz_str)).strftime(format) def get_date_time_delta(delta): return str(datetime.now().replace(tzinfo=gettz('UTC')) + timedelta(delta)) def get_date_age(date): return (datetime.now(tz=tzutc()) - parser.parse(date)).days def format_struct(evt): return json.dumps(evt, indent=2, ensure_ascii=False) def get_resource_tag_value(resource, k): for t in resource.get('Tags', []): if t['Key'] == k: return t['Value'] return '' def strip_prefix(value, prefix): if value.startswith(prefix): return value[len(prefix):] return value def resource_format(resource, resource_type): if resource_type.startswith('aws.'): resource_type = strip_prefix(resource_type, 'aws.') if resource_type == 'ec2': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s %s %s %s" % ( resource['InstanceId'], resource.get('VpcId', 'NO VPC!'), resource['InstanceType'], resource.get('LaunchTime'), tag_map.get('Name', ''), resource.get('PrivateIpAddress')) elif resource_type == 'ami': return "%s %s %s" % ( resource.get('Name'), resource['ImageId'], resource['CreationDate']) elif resource_type == 'sagemaker-notebook': return "%s" % (resource['NotebookInstanceName']) elif resource_type == 's3': return "%s" % (resource['Name']) elif resource_type == 'ebs': return "%s %s %s %s" % ( resource['VolumeId'], resource['Size'], resource['State'], resource['CreateTime']) elif resource_type == 'rds': return "%s %s %s %s" % ( resource['DBInstanceIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['DBInstanceClass'], resource['AllocatedStorage']) elif resource_type == 'rds-cluster': return "%s %s %s" % ( resource['DBClusterIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['AllocatedStorage']) elif resource_type == 'asg': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s" % ( resource['AutoScalingGroupName'], tag_map.get('Name', ''), "instances: %d" % (len(resource.get('Instances', [])))) elif resource_type == 'elb': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} if 'ProhibitedPolicies' in resource: return "%s %s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones']), "prohibited_policies: %s" % ','.join( resource['ProhibitedPolicies'])) return "%s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones'])) elif resource_type == 'redshift': return "%s %s %s" % ( resource['ClusterIdentifier'], 'nodes:%d' % len(resource['ClusterNodes']), 'encrypted:%s' % resource['Encrypted']) elif resource_type == 'emr': return "%s status:%s" % ( resource['Id'], resource['Status']['State']) elif resource_type == 'cfn': return "%s" % ( resource['StackName']) elif resource_type == 'launch-config': return "%s" % ( resource['LaunchConfigurationName']) elif resource_type == 'security-group': name = resource.get('GroupName', '') for t in resource.get('Tags', ()): if t['Key'] == 'Name': name = t['Value'] return "%s %s %s inrules: %d outrules: %d" % ( name, resource['GroupId'], resource.get('VpcId', 'na'), len(resource.get('IpPermissions', ())), len(resource.get('IpPermissionsEgress', ()))) elif resource_type == 'log-group': if 'lastWrite' in resource: return "name: %s last_write: %s" % ( resource['logGroupName'], resource['lastWrite']) return "name: %s" % (resource['logGroupName']) elif resource_type == 'cache-cluster': return "name: %s created: %s status: %s" % ( resource['CacheClusterId'], resource['CacheClusterCreateTime'], resource['CacheClusterStatus']) elif resource_type == 'cache-snapshot': cid = resource.get('CacheClusterId') if cid is None: cid = ', '.join([ ns['CacheClusterId'] for ns in resource['NodeSnapshots']]) return "name: %s cluster: %s source: %s" % ( resource['SnapshotName'], cid, resource['SnapshotSource']) elif resource_type == 'redshift-snapshot': return "name: %s db: %s" % ( resource['SnapshotIdentifier'], resource['DBName']) elif resource_type == 'ebs-snapshot': return "name: %s date: %s" % ( resource['SnapshotId'], resource['StartTime']) elif resource_type == 'subnet': return "%s %s %s %s %s %s" % ( resource['SubnetId'], resource['VpcId'], resource['AvailabilityZone'], resource['State'], resource['CidrBlock'], resource['AvailableIpAddressCount']) elif resource_type == 'account': return " %s %s" % ( resource['account_id'], resource['account_name']) elif resource_type == 'cloudtrail': return "%s" % ( resource['Name']) elif resource_type == 'vpc': return "%s " % ( resource['VpcId']) elif resource_type == 'iam-group': return " %s %s %s" % ( resource['GroupName'], resource['Arn'], resource['CreateDate']) elif resource_type == 'rds-snapshot': return " %s %s %s" % ( resource['DBSnapshotIdentifier'], resource['DBInstanceIdentifier'], resource['SnapshotCreateTime']) elif resource_type == 'iam-user': return " %s " % ( resource['UserName']) elif resource_type == 'iam-role': return " %s %s " % ( resource['RoleName'], resource['CreateDate']) elif resource_type == 'iam-policy': return " %s " % ( resource['PolicyName']) elif resource_type == 'iam-profile': return " %s " % ( resource['InstanceProfileId']) elif resource_type == 'dynamodb-table': return "name: %s created: %s status: %s" % ( resource['TableName'], resource['CreationDateTime'], resource['TableStatus']) elif resource_type == "sqs": return "QueueURL: %s QueueArn: %s " % ( resource['QueueUrl'], resource['QueueArn']) elif resource_type == "efs": return "name: %s id: %s state: %s" % ( resource['Name'], resource['FileSystemId'], resource['LifeCycleState'] ) elif resource_type == "network-addr": return "ip: %s id: %s scope: %s" % ( resource['PublicIp'], resource['AllocationId'], resource['Domain'] ) elif resource_type == "route-table": return "id: %s vpc: %s" % (
) elif resource_type == "app-elb": return "arn: %s zones: %s scheme: %s" % ( resource['LoadBalancerArn'], len(resource['AvailabilityZones']), resource['Scheme']) elif resource_type == "nat-gateway": return "id: %s state: %s vpc: %s" % ( resource['NatGatewayId'], resource['State'], resource['VpcId']) elif resource_type == "internet-gateway": return "id: %s attachments: %s" % ( resource['InternetGatewayId'], len(resource['Attachments'])) elif resource_type == 'lambda': return "Name: %s RunTime: %s \n" % ( resource['FunctionName'], resource['Runtime']) else: return "%s" % format_struct(resource) def get_provider(mailer_config): if mailer_config.get('queue_url', '').startswith('asq://'): return Providers.Azure return Providers.AWS def kms_decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): try: kms = session.client('kms') return kms.decrypt( CiphertextBlob=base64.b64decode(config[encrypted_field]))[ 'Plaintext'].decode('utf8') except (TypeError, base64.binascii.Error) as e: logger.warning( "Error: %s Unable to base64 decode %s, will assume plaintext." % (e, encrypted_field)) except ClientError as e: if e.response['Error']['Code'] != 'InvalidCiphertextException': raise logger.warning( "Error: %s Unable to decrypt %s with kms, will assume plaintext." % (e, encrypted_field)) return config[encrypted_field] else: logger.debug("No encrypted value to decrypt.") return None def decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): provider = get_provider(config) if provider == Providers.Azure: from c7n_mailer.azure_mailer.utils import azure_decrypt return azure_decrypt(config, logger, session, encrypted_field) elif provider == Providers.AWS: return kms_decrypt(config, logger, session, encrypted_field) else: raise Exception("Unknown provider") else: logger.debug("No encrypted value to decrypt.") return None # https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html def get_aws_username_from_event(logger, event): if event is None: return None identity = event.get('detail', {}).get('userIdentity', {}) if not identity: logger.warning("Could not get recipient from event \n %s" % ( format_struct(event))) return None if identity['type'] == 'AssumedRole': logger.debug( 'In some cases there is no ldap uid is associated with AssumedRole: %s', identity['arn']) logger.debug( 'We will try to assume that identity is in the AssumedRoleSessionName') user = identity['arn'].rsplit('/', 1)[-1] if user is None or user.startswith('i-') or user.startswith('awslambda'): return None if ':' in user: user = user.split(':', 1)[-1] return user if identity['type'] == 'IAMUser' or identity['type'] == 'WebIdentityUser': return identity['userName'] if identity['type'] == 'Root': return None # this conditional is left here as a last resort, it should # be better documented with an example UserIdentity json if ':' in identity['principalId']: user_id = identity['principalId'].split(':', 1)[-1] else: user_id = identity['principalId'] return user_id
resource['RouteTableId'], resource['VpcId']
random_line_split
utils.py
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import base64 from datetime import datetime, timedelta import functools import json import os import time import yaml import jinja2 import jmespath from dateutil import parser from dateutil.tz import gettz, tzutc try: from botocore.exceptions import ClientError except ImportError: # pragma: no cover pass # Azure provider class Providers: AWS = 0 Azure = 1 def get_jinja_env(template_folders): env = jinja2.Environment(trim_blocks=True, autoescape=False) # nosec nosemgrep env.filters['yaml_safe'] = functools.partial(yaml.safe_dump, default_flow_style=False) env.filters['date_time_format'] = date_time_format env.filters['get_date_time_delta'] = get_date_time_delta env.filters['from_json'] = json.loads env.filters['get_date_age'] = get_date_age env.globals['format_resource'] = resource_format env.globals['format_struct'] = format_struct env.globals['resource_tag'] = get_resource_tag_value env.globals['get_resource_tag_value'] = get_resource_tag_value env.globals['search'] = jmespath.search env.loader = jinja2.FileSystemLoader(template_folders) return env def get_rendered_jinja( target, sqs_message, resources, logger, specified_template, default_template, template_folders): env = get_jinja_env(template_folders) mail_template = sqs_message['action'].get(specified_template, default_template) if not os.path.isabs(mail_template): mail_template = '%s.j2' % mail_template try: template = env.get_template(mail_template) except Exception as error_msg: logger.error("Invalid template reference %s\n%s" % (mail_template, error_msg)) return # recast seconds since epoch as utc iso datestring, template # authors can use date_time_format helper func to convert local # tz. if no execution start time was passed use current time. execution_start = datetime.utcfromtimestamp( sqs_message.get( 'execution_start', time.mktime( datetime.utcnow().timetuple()) )).isoformat() rendered_jinja = template.render( recipient=target, resources=resources, account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], execution_start=execution_start, region=sqs_message.get('region', '')) return rendered_jinja # eg, target_tag_keys could be resource-owners ['Owners', 'SupportTeam'] # and this function would go through the resource and look for any tag keys # that match Owners or SupportTeam, and return those values as targets def get_resource_tag_targets(resource, target_tag_keys): if 'Tags' not in resource: return [] if isinstance(resource['Tags'], dict): tags = resource['Tags'] else: tags = {tag['Key']: tag['Value'] for tag in resource['Tags']} targets = [] for target_tag_key in target_tag_keys: if target_tag_key in tags: targets.append(tags[target_tag_key]) return targets def get_message_subject(sqs_message): default_subject = 'Custodian notification - %s' % (sqs_message['policy']['name']) subject = sqs_message['action'].get('subject', default_subject) jinja_template = jinja2.Template(subject) subject = jinja_template.render( account=sqs_message.get('account', ''), account_id=sqs_message.get('account_id', ''), partition=sqs_message.get('partition', ''), event=sqs_message.get('event', None), action=sqs_message['action'], policy=sqs_message['policy'], region=sqs_message.get('region', '') ) return subject def setup_defaults(config): config.setdefault('region', 'us-east-1') config.setdefault('ses_region', config.get('region')) config.setdefault('memory', 1024) config.setdefault('runtime', 'python3.7') config.setdefault('timeout', 300) config.setdefault('subnets', None) config.setdefault('security_groups', None) config.setdefault('contact_tags', []) config.setdefault('ldap_uri', None) config.setdefault('ldap_bind_dn', None) config.setdefault('ldap_bind_user', None) config.setdefault('ldap_bind_password', None) config.setdefault('endpoint_url', None) config.setdefault('datadog_api_key', None) config.setdefault('slack_token', None) config.setdefault('slack_webhook', None) def date_time_format(utc_str, tz_str='US/Eastern', format='%Y %b %d %H:%M %Z'): return parser.parse(utc_str).astimezone(gettz(tz_str)).strftime(format) def get_date_time_delta(delta): return str(datetime.now().replace(tzinfo=gettz('UTC')) + timedelta(delta)) def get_date_age(date): return (datetime.now(tz=tzutc()) - parser.parse(date)).days def format_struct(evt): return json.dumps(evt, indent=2, ensure_ascii=False) def get_resource_tag_value(resource, k): for t in resource.get('Tags', []): if t['Key'] == k: return t['Value'] return '' def strip_prefix(value, prefix): if value.startswith(prefix): return value[len(prefix):] return value def resource_format(resource, resource_type):
def get_provider(mailer_config): if mailer_config.get('queue_url', '').startswith('asq://'): return Providers.Azure return Providers.AWS def kms_decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): try: kms = session.client('kms') return kms.decrypt( CiphertextBlob=base64.b64decode(config[encrypted_field]))[ 'Plaintext'].decode('utf8') except (TypeError, base64.binascii.Error) as e: logger.warning( "Error: %s Unable to base64 decode %s, will assume plaintext." % (e, encrypted_field)) except ClientError as e: if e.response['Error']['Code'] != 'InvalidCiphertextException': raise logger.warning( "Error: %s Unable to decrypt %s with kms, will assume plaintext." % (e, encrypted_field)) return config[encrypted_field] else: logger.debug("No encrypted value to decrypt.") return None def decrypt(config, logger, session, encrypted_field): if config.get(encrypted_field): provider = get_provider(config) if provider == Providers.Azure: from c7n_mailer.azure_mailer.utils import azure_decrypt return azure_decrypt(config, logger, session, encrypted_field) elif provider == Providers.AWS: return kms_decrypt(config, logger, session, encrypted_field) else: raise Exception("Unknown provider") else: logger.debug("No encrypted value to decrypt.") return None # https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html def get_aws_username_from_event(logger, event): if event is None: return None identity = event.get('detail', {}).get('userIdentity', {}) if not identity: logger.warning("Could not get recipient from event \n %s" % ( format_struct(event))) return None if identity['type'] == 'AssumedRole': logger.debug( 'In some cases there is no ldap uid is associated with AssumedRole: %s', identity['arn']) logger.debug( 'We will try to assume that identity is in the AssumedRoleSessionName') user = identity['arn'].rsplit('/', 1)[-1] if user is None or user.startswith('i-') or user.startswith('awslambda'): return None if ':' in user: user = user.split(':', 1)[-1] return user if identity['type'] == 'IAMUser' or identity['type'] == 'WebIdentityUser': return identity['userName'] if identity['type'] == 'Root': return None # this conditional is left here as a last resort, it should # be better documented with an example UserIdentity json if ':' in identity['principalId']: user_id = identity['principalId'].split(':', 1)[-1] else: user_id = identity['principalId'] return user_id
if resource_type.startswith('aws.'): resource_type = strip_prefix(resource_type, 'aws.') if resource_type == 'ec2': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s %s %s %s" % ( resource['InstanceId'], resource.get('VpcId', 'NO VPC!'), resource['InstanceType'], resource.get('LaunchTime'), tag_map.get('Name', ''), resource.get('PrivateIpAddress')) elif resource_type == 'ami': return "%s %s %s" % ( resource.get('Name'), resource['ImageId'], resource['CreationDate']) elif resource_type == 'sagemaker-notebook': return "%s" % (resource['NotebookInstanceName']) elif resource_type == 's3': return "%s" % (resource['Name']) elif resource_type == 'ebs': return "%s %s %s %s" % ( resource['VolumeId'], resource['Size'], resource['State'], resource['CreateTime']) elif resource_type == 'rds': return "%s %s %s %s" % ( resource['DBInstanceIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['DBInstanceClass'], resource['AllocatedStorage']) elif resource_type == 'rds-cluster': return "%s %s %s" % ( resource['DBClusterIdentifier'], "%s-%s" % ( resource['Engine'], resource['EngineVersion']), resource['AllocatedStorage']) elif resource_type == 'asg': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} return "%s %s %s" % ( resource['AutoScalingGroupName'], tag_map.get('Name', ''), "instances: %d" % (len(resource.get('Instances', [])))) elif resource_type == 'elb': tag_map = {t['Key']: t['Value'] for t in resource.get('Tags', ())} if 'ProhibitedPolicies' in resource: return "%s %s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones']), "prohibited_policies: %s" % ','.join( resource['ProhibitedPolicies'])) return "%s %s %s" % ( resource['LoadBalancerName'], "instances: %d" % len(resource['Instances']), "zones: %d" % len(resource['AvailabilityZones'])) elif resource_type == 'redshift': return "%s %s %s" % ( resource['ClusterIdentifier'], 'nodes:%d' % len(resource['ClusterNodes']), 'encrypted:%s' % resource['Encrypted']) elif resource_type == 'emr': return "%s status:%s" % ( resource['Id'], resource['Status']['State']) elif resource_type == 'cfn': return "%s" % ( resource['StackName']) elif resource_type == 'launch-config': return "%s" % ( resource['LaunchConfigurationName']) elif resource_type == 'security-group': name = resource.get('GroupName', '') for t in resource.get('Tags', ()): if t['Key'] == 'Name': name = t['Value'] return "%s %s %s inrules: %d outrules: %d" % ( name, resource['GroupId'], resource.get('VpcId', 'na'), len(resource.get('IpPermissions', ())), len(resource.get('IpPermissionsEgress', ()))) elif resource_type == 'log-group': if 'lastWrite' in resource: return "name: %s last_write: %s" % ( resource['logGroupName'], resource['lastWrite']) return "name: %s" % (resource['logGroupName']) elif resource_type == 'cache-cluster': return "name: %s created: %s status: %s" % ( resource['CacheClusterId'], resource['CacheClusterCreateTime'], resource['CacheClusterStatus']) elif resource_type == 'cache-snapshot': cid = resource.get('CacheClusterId') if cid is None: cid = ', '.join([ ns['CacheClusterId'] for ns in resource['NodeSnapshots']]) return "name: %s cluster: %s source: %s" % ( resource['SnapshotName'], cid, resource['SnapshotSource']) elif resource_type == 'redshift-snapshot': return "name: %s db: %s" % ( resource['SnapshotIdentifier'], resource['DBName']) elif resource_type == 'ebs-snapshot': return "name: %s date: %s" % ( resource['SnapshotId'], resource['StartTime']) elif resource_type == 'subnet': return "%s %s %s %s %s %s" % ( resource['SubnetId'], resource['VpcId'], resource['AvailabilityZone'], resource['State'], resource['CidrBlock'], resource['AvailableIpAddressCount']) elif resource_type == 'account': return " %s %s" % ( resource['account_id'], resource['account_name']) elif resource_type == 'cloudtrail': return "%s" % ( resource['Name']) elif resource_type == 'vpc': return "%s " % ( resource['VpcId']) elif resource_type == 'iam-group': return " %s %s %s" % ( resource['GroupName'], resource['Arn'], resource['CreateDate']) elif resource_type == 'rds-snapshot': return " %s %s %s" % ( resource['DBSnapshotIdentifier'], resource['DBInstanceIdentifier'], resource['SnapshotCreateTime']) elif resource_type == 'iam-user': return " %s " % ( resource['UserName']) elif resource_type == 'iam-role': return " %s %s " % ( resource['RoleName'], resource['CreateDate']) elif resource_type == 'iam-policy': return " %s " % ( resource['PolicyName']) elif resource_type == 'iam-profile': return " %s " % ( resource['InstanceProfileId']) elif resource_type == 'dynamodb-table': return "name: %s created: %s status: %s" % ( resource['TableName'], resource['CreationDateTime'], resource['TableStatus']) elif resource_type == "sqs": return "QueueURL: %s QueueArn: %s " % ( resource['QueueUrl'], resource['QueueArn']) elif resource_type == "efs": return "name: %s id: %s state: %s" % ( resource['Name'], resource['FileSystemId'], resource['LifeCycleState'] ) elif resource_type == "network-addr": return "ip: %s id: %s scope: %s" % ( resource['PublicIp'], resource['AllocationId'], resource['Domain'] ) elif resource_type == "route-table": return "id: %s vpc: %s" % ( resource['RouteTableId'], resource['VpcId'] ) elif resource_type == "app-elb": return "arn: %s zones: %s scheme: %s" % ( resource['LoadBalancerArn'], len(resource['AvailabilityZones']), resource['Scheme']) elif resource_type == "nat-gateway": return "id: %s state: %s vpc: %s" % ( resource['NatGatewayId'], resource['State'], resource['VpcId']) elif resource_type == "internet-gateway": return "id: %s attachments: %s" % ( resource['InternetGatewayId'], len(resource['Attachments'])) elif resource_type == 'lambda': return "Name: %s RunTime: %s \n" % ( resource['FunctionName'], resource['Runtime']) else: return "%s" % format_struct(resource)
identifier_body
QuickOpen.ts
// Copyright 2016 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. import * as i18n from '../../../../core/i18n/i18n.js'; import type * as UI from '../../legacy.js'; import type {Provider} from './FilteredListWidget.js'; import {FilteredListWidget, getRegisteredProviders} from './FilteredListWidget.js'; const UIStrings = { /** * @description Text of the hint shows under Quick Open input box */ typeToSeeAvailableCommands: 'Type \'?\' to see available commands', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/quick_open/QuickOpen.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export const history: string[] = []; export class QuickOpenImpl { private prefix: string|null; private readonly prefixes: string[]; private providers: Map<string, { provider: () => Promise<Provider>, titlePrefix: (() => string), titleSuggestion?: (() => string), }>; private filteredListWidget: FilteredListWidget|null; constructor() { this.prefix = null; this.prefixes = []; this.providers = new Map(); this.filteredListWidget = null; getRegisteredProviders().forEach(this.addProvider.bind(this)); this.prefixes.sort((a, b) => b.length - a.length); } static show(query: string): void { const quickOpen = new this(); const filteredListWidget = new FilteredListWidget(null, history, quickOpen.queryChanged.bind(quickOpen)); quickOpen.filteredListWidget = filteredListWidget; filteredListWidget.setHintElement(i18nString(UIStrings.typeToSeeAvailableCommands)); filteredListWidget.showAsDialog(); filteredListWidget.setQuery(query); } private addProvider(extension: { prefix: string, provider: () => Promise<Provider>, titlePrefix: () => string, titleSuggestion?: (() => string), }): void { const prefix = extension.prefix; if (prefix === null) { return; } this.prefixes.push(prefix); this.providers.set(prefix, { provider: extension.provider, titlePrefix: extension.titlePrefix, titleSuggestion: extension.titleSuggestion, }); } private async queryChanged(query: string): Promise<void> { const prefix = this.prefixes.find(prefix => query.startsWith(prefix)); if (typeof prefix !== 'string') { return; } if (!this.filteredListWidget) { return; } this.filteredListWidget.setPrefix(prefix); const titlePrefixFunction = this.providers.get(prefix)?.titlePrefix; this.filteredListWidget.setCommandPrefix(titlePrefixFunction ? titlePrefixFunction() : ''); const titleSuggestionFunction = (query === prefix) && this.providers.get(prefix)?.titleSuggestion; this.filteredListWidget.setCommandSuggestion(titleSuggestionFunction ? titleSuggestionFunction() : ''); if (this.prefix === prefix) { return; } this.prefix = prefix; this.filteredListWidget.setProvider(null); const providerFunction = this.providers.get(prefix)?.provider; if (!providerFunction) { return; } const provider = await providerFunction(); if (this.prefix !== prefix || !this.filteredListWidget) { return; } this.filteredListWidget.setProvider(provider); this.providerLoadedForTest(provider); } private
(_provider: Provider): void { } } let showActionDelegateInstance: ShowActionDelegate; export class ShowActionDelegate implements UI.ActionRegistration.ActionDelegate { static instance(opts: { forceNew: boolean|null, } = {forceNew: null}): ShowActionDelegate { const {forceNew} = opts; if (!showActionDelegateInstance || forceNew) { showActionDelegateInstance = new ShowActionDelegate(); } return showActionDelegateInstance; } handleAction(context: UI.Context.Context, actionId: string): boolean { switch (actionId) { case 'quickOpen.show': QuickOpenImpl.show(''); return true; } return false; } }
providerLoadedForTest
identifier_name
QuickOpen.ts
// Copyright 2016 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. import * as i18n from '../../../../core/i18n/i18n.js'; import type * as UI from '../../legacy.js'; import type {Provider} from './FilteredListWidget.js'; import {FilteredListWidget, getRegisteredProviders} from './FilteredListWidget.js'; const UIStrings = { /** * @description Text of the hint shows under Quick Open input box */ typeToSeeAvailableCommands: 'Type \'?\' to see available commands', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/quick_open/QuickOpen.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export const history: string[] = []; export class QuickOpenImpl { private prefix: string|null; private readonly prefixes: string[]; private providers: Map<string, { provider: () => Promise<Provider>, titlePrefix: (() => string), titleSuggestion?: (() => string), }>; private filteredListWidget: FilteredListWidget|null; constructor() { this.prefix = null; this.prefixes = []; this.providers = new Map(); this.filteredListWidget = null; getRegisteredProviders().forEach(this.addProvider.bind(this)); this.prefixes.sort((a, b) => b.length - a.length); } static show(query: string): void { const quickOpen = new this(); const filteredListWidget = new FilteredListWidget(null, history, quickOpen.queryChanged.bind(quickOpen)); quickOpen.filteredListWidget = filteredListWidget; filteredListWidget.setHintElement(i18nString(UIStrings.typeToSeeAvailableCommands)); filteredListWidget.showAsDialog(); filteredListWidget.setQuery(query); } private addProvider(extension: { prefix: string, provider: () => Promise<Provider>, titlePrefix: () => string, titleSuggestion?: (() => string), }): void { const prefix = extension.prefix; if (prefix === null) { return; } this.prefixes.push(prefix); this.providers.set(prefix, { provider: extension.provider, titlePrefix: extension.titlePrefix, titleSuggestion: extension.titleSuggestion, }); } private async queryChanged(query: string): Promise<void> { const prefix = this.prefixes.find(prefix => query.startsWith(prefix)); if (typeof prefix !== 'string') { return; }
this.filteredListWidget.setCommandPrefix(titlePrefixFunction ? titlePrefixFunction() : ''); const titleSuggestionFunction = (query === prefix) && this.providers.get(prefix)?.titleSuggestion; this.filteredListWidget.setCommandSuggestion(titleSuggestionFunction ? titleSuggestionFunction() : ''); if (this.prefix === prefix) { return; } this.prefix = prefix; this.filteredListWidget.setProvider(null); const providerFunction = this.providers.get(prefix)?.provider; if (!providerFunction) { return; } const provider = await providerFunction(); if (this.prefix !== prefix || !this.filteredListWidget) { return; } this.filteredListWidget.setProvider(provider); this.providerLoadedForTest(provider); } private providerLoadedForTest(_provider: Provider): void { } } let showActionDelegateInstance: ShowActionDelegate; export class ShowActionDelegate implements UI.ActionRegistration.ActionDelegate { static instance(opts: { forceNew: boolean|null, } = {forceNew: null}): ShowActionDelegate { const {forceNew} = opts; if (!showActionDelegateInstance || forceNew) { showActionDelegateInstance = new ShowActionDelegate(); } return showActionDelegateInstance; } handleAction(context: UI.Context.Context, actionId: string): boolean { switch (actionId) { case 'quickOpen.show': QuickOpenImpl.show(''); return true; } return false; } }
if (!this.filteredListWidget) { return; } this.filteredListWidget.setPrefix(prefix); const titlePrefixFunction = this.providers.get(prefix)?.titlePrefix;
random_line_split
QuickOpen.ts
// Copyright 2016 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. import * as i18n from '../../../../core/i18n/i18n.js'; import type * as UI from '../../legacy.js'; import type {Provider} from './FilteredListWidget.js'; import {FilteredListWidget, getRegisteredProviders} from './FilteredListWidget.js'; const UIStrings = { /** * @description Text of the hint shows under Quick Open input box */ typeToSeeAvailableCommands: 'Type \'?\' to see available commands', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/quick_open/QuickOpen.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export const history: string[] = []; export class QuickOpenImpl { private prefix: string|null; private readonly prefixes: string[]; private providers: Map<string, { provider: () => Promise<Provider>, titlePrefix: (() => string), titleSuggestion?: (() => string), }>; private filteredListWidget: FilteredListWidget|null; constructor() { this.prefix = null; this.prefixes = []; this.providers = new Map(); this.filteredListWidget = null; getRegisteredProviders().forEach(this.addProvider.bind(this)); this.prefixes.sort((a, b) => b.length - a.length); } static show(query: string): void { const quickOpen = new this(); const filteredListWidget = new FilteredListWidget(null, history, quickOpen.queryChanged.bind(quickOpen)); quickOpen.filteredListWidget = filteredListWidget; filteredListWidget.setHintElement(i18nString(UIStrings.typeToSeeAvailableCommands)); filteredListWidget.showAsDialog(); filteredListWidget.setQuery(query); } private addProvider(extension: { prefix: string, provider: () => Promise<Provider>, titlePrefix: () => string, titleSuggestion?: (() => string), }): void { const prefix = extension.prefix; if (prefix === null) { return; } this.prefixes.push(prefix); this.providers.set(prefix, { provider: extension.provider, titlePrefix: extension.titlePrefix, titleSuggestion: extension.titleSuggestion, }); } private async queryChanged(query: string): Promise<void> { const prefix = this.prefixes.find(prefix => query.startsWith(prefix)); if (typeof prefix !== 'string') { return; } if (!this.filteredListWidget) { return; } this.filteredListWidget.setPrefix(prefix); const titlePrefixFunction = this.providers.get(prefix)?.titlePrefix; this.filteredListWidget.setCommandPrefix(titlePrefixFunction ? titlePrefixFunction() : ''); const titleSuggestionFunction = (query === prefix) && this.providers.get(prefix)?.titleSuggestion; this.filteredListWidget.setCommandSuggestion(titleSuggestionFunction ? titleSuggestionFunction() : ''); if (this.prefix === prefix) { return; } this.prefix = prefix; this.filteredListWidget.setProvider(null); const providerFunction = this.providers.get(prefix)?.provider; if (!providerFunction) { return; } const provider = await providerFunction(); if (this.prefix !== prefix || !this.filteredListWidget) { return; } this.filteredListWidget.setProvider(provider); this.providerLoadedForTest(provider); } private providerLoadedForTest(_provider: Provider): void { } } let showActionDelegateInstance: ShowActionDelegate; export class ShowActionDelegate implements UI.ActionRegistration.ActionDelegate { static instance(opts: { forceNew: boolean|null, } = {forceNew: null}): ShowActionDelegate { const {forceNew} = opts; if (!showActionDelegateInstance || forceNew)
return showActionDelegateInstance; } handleAction(context: UI.Context.Context, actionId: string): boolean { switch (actionId) { case 'quickOpen.show': QuickOpenImpl.show(''); return true; } return false; } }
{ showActionDelegateInstance = new ShowActionDelegate(); }
conditional_block
HelloWorld.py
"""Example macro.""" revision = "$Rev$" url = "$URL$" # # The following shows the code for macro, old-style. # # The `execute` function serves no purpose other than to illustrate # the example, it will not be used anymore. # # ---- (ignore in your own macro) ---- # -- from trac.util import escape def execute(hdf, txt, env): # Currently hdf is set only when the macro is called # From a wiki page if hdf: hdf['wiki.macro.greeting'] = 'Hello World' # args will be `None` if the macro is called without parenthesis. args = txt or 'No arguments' # then, as `txt` comes from the user, it's important to guard against # the possibility to inject malicious HTML/Javascript, by using `escape()`: return 'Hello World, args = ' + escape(args) # -- # ---- (ignore in your own macro) ---- # # The following is the converted new-style macro # # ---- (reuse for your own macro) ---- # -- from trac.wiki.macros import WikiMacroBase class HelloWorldMacro(WikiMacroBase): _description = cleandoc_( """Simple HelloWorld macro. Note that the name of the class is meaningful: - it must end with "Macro" - what comes before "Macro" ends up being the macro name The documentation of the class (i.e. what you're reading) will become the documentation of the macro, as shown by the !MacroList macro (usually used in the TracWikiMacros page). """) def expand_macro(self, formatter, name, args): """Return some output that will be displayed in the Wiki content. `name` is the actual name of the macro (no surprise, here it'll be `'HelloWorld'`),
""" return 'Hello World, args = ' + unicode(args) # Note that there's no need to HTML escape the returned data, # as the template engine (Genshi) will do it for us. # -- # ---- (reuse for your own macro) ----
`args` is the text enclosed in parenthesis at the call of the macro. Note that if there are ''no'' parenthesis (like in, e.g. [[HelloWorld]]), then `args` is `None`.
random_line_split
HelloWorld.py
"""Example macro.""" revision = "$Rev$" url = "$URL$" # # The following shows the code for macro, old-style. # # The `execute` function serves no purpose other than to illustrate # the example, it will not be used anymore. # # ---- (ignore in your own macro) ---- # -- from trac.util import escape def execute(hdf, txt, env): # Currently hdf is set only when the macro is called # From a wiki page if hdf: hdf['wiki.macro.greeting'] = 'Hello World' # args will be `None` if the macro is called without parenthesis. args = txt or 'No arguments' # then, as `txt` comes from the user, it's important to guard against # the possibility to inject malicious HTML/Javascript, by using `escape()`: return 'Hello World, args = ' + escape(args) # -- # ---- (ignore in your own macro) ---- # # The following is the converted new-style macro # # ---- (reuse for your own macro) ---- # -- from trac.wiki.macros import WikiMacroBase class HelloWorldMacro(WikiMacroBase): _description = cleandoc_( """Simple HelloWorld macro. Note that the name of the class is meaningful: - it must end with "Macro" - what comes before "Macro" ends up being the macro name The documentation of the class (i.e. what you're reading) will become the documentation of the macro, as shown by the !MacroList macro (usually used in the TracWikiMacros page). """) def expand_macro(self, formatter, name, args):
# Note that there's no need to HTML escape the returned data, # as the template engine (Genshi) will do it for us. # -- # ---- (reuse for your own macro) ----
"""Return some output that will be displayed in the Wiki content. `name` is the actual name of the macro (no surprise, here it'll be `'HelloWorld'`), `args` is the text enclosed in parenthesis at the call of the macro. Note that if there are ''no'' parenthesis (like in, e.g. [[HelloWorld]]), then `args` is `None`. """ return 'Hello World, args = ' + unicode(args)
identifier_body
HelloWorld.py
"""Example macro.""" revision = "$Rev$" url = "$URL$" # # The following shows the code for macro, old-style. # # The `execute` function serves no purpose other than to illustrate # the example, it will not be used anymore. # # ---- (ignore in your own macro) ---- # -- from trac.util import escape def execute(hdf, txt, env): # Currently hdf is set only when the macro is called # From a wiki page if hdf:
# args will be `None` if the macro is called without parenthesis. args = txt or 'No arguments' # then, as `txt` comes from the user, it's important to guard against # the possibility to inject malicious HTML/Javascript, by using `escape()`: return 'Hello World, args = ' + escape(args) # -- # ---- (ignore in your own macro) ---- # # The following is the converted new-style macro # # ---- (reuse for your own macro) ---- # -- from trac.wiki.macros import WikiMacroBase class HelloWorldMacro(WikiMacroBase): _description = cleandoc_( """Simple HelloWorld macro. Note that the name of the class is meaningful: - it must end with "Macro" - what comes before "Macro" ends up being the macro name The documentation of the class (i.e. what you're reading) will become the documentation of the macro, as shown by the !MacroList macro (usually used in the TracWikiMacros page). """) def expand_macro(self, formatter, name, args): """Return some output that will be displayed in the Wiki content. `name` is the actual name of the macro (no surprise, here it'll be `'HelloWorld'`), `args` is the text enclosed in parenthesis at the call of the macro. Note that if there are ''no'' parenthesis (like in, e.g. [[HelloWorld]]), then `args` is `None`. """ return 'Hello World, args = ' + unicode(args) # Note that there's no need to HTML escape the returned data, # as the template engine (Genshi) will do it for us. # -- # ---- (reuse for your own macro) ----
hdf['wiki.macro.greeting'] = 'Hello World'
conditional_block
HelloWorld.py
"""Example macro.""" revision = "$Rev$" url = "$URL$" # # The following shows the code for macro, old-style. # # The `execute` function serves no purpose other than to illustrate # the example, it will not be used anymore. # # ---- (ignore in your own macro) ---- # -- from trac.util import escape def
(hdf, txt, env): # Currently hdf is set only when the macro is called # From a wiki page if hdf: hdf['wiki.macro.greeting'] = 'Hello World' # args will be `None` if the macro is called without parenthesis. args = txt or 'No arguments' # then, as `txt` comes from the user, it's important to guard against # the possibility to inject malicious HTML/Javascript, by using `escape()`: return 'Hello World, args = ' + escape(args) # -- # ---- (ignore in your own macro) ---- # # The following is the converted new-style macro # # ---- (reuse for your own macro) ---- # -- from trac.wiki.macros import WikiMacroBase class HelloWorldMacro(WikiMacroBase): _description = cleandoc_( """Simple HelloWorld macro. Note that the name of the class is meaningful: - it must end with "Macro" - what comes before "Macro" ends up being the macro name The documentation of the class (i.e. what you're reading) will become the documentation of the macro, as shown by the !MacroList macro (usually used in the TracWikiMacros page). """) def expand_macro(self, formatter, name, args): """Return some output that will be displayed in the Wiki content. `name` is the actual name of the macro (no surprise, here it'll be `'HelloWorld'`), `args` is the text enclosed in parenthesis at the call of the macro. Note that if there are ''no'' parenthesis (like in, e.g. [[HelloWorld]]), then `args` is `None`. """ return 'Hello World, args = ' + unicode(args) # Note that there's no need to HTML escape the returned data, # as the template engine (Genshi) will do it for us. # -- # ---- (reuse for your own macro) ----
execute
identifier_name
errorHandler.js
/** * error handling middleware loosely based off of the connect/errorHandler code. This handler chooses * to render errors using Jade / Express instead of the manual templating used by the connect middleware * sample. This may or may not be a good idea :-) * @param options {object} array of options **/ exports = module.exports = function errorHandler(options) { options = options || {}; // defaults var showStack = options.showStack || options.stack , showMessage = options.showMessage || options.message , dumpExceptions = options.dumpExceptions || options.dump , formatUrl = options.formatUrl; return function errorHandler(err, req, res, next) { res.statusCode = 500; if(dumpExceptions) console.error(err.stack); var app = res.app; if(err instanceof exports.NotFound) { res.render('errors/404', { locals: { title: '404 - Not Found' }, status: 404 }); } else { res.render('errors/500', { locals: { title: 'The Server Encountered an Error' , error: showStack ? err : undefined }, status: 500 }); }
exports.NotFound = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }
}; };
random_line_split
errorHandler.js
/** * error handling middleware loosely based off of the connect/errorHandler code. This handler chooses * to render errors using Jade / Express instead of the manual templating used by the connect middleware * sample. This may or may not be a good idea :-) * @param options {object} array of options **/ exports = module.exports = function errorHandler(options) { options = options || {}; // defaults var showStack = options.showStack || options.stack , showMessage = options.showMessage || options.message , dumpExceptions = options.dumpExceptions || options.dump , formatUrl = options.formatUrl; return function errorHandler(err, req, res, next) { res.statusCode = 500; if(dumpExceptions) console.error(err.stack); var app = res.app; if(err instanceof exports.NotFound) { res.render('errors/404', { locals: { title: '404 - Not Found' }, status: 404 }); } else
}; }; exports.NotFound = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }
{ res.render('errors/500', { locals: { title: 'The Server Encountered an Error' , error: showStack ? err : undefined }, status: 500 }); }
conditional_block
base_scraper.py
import logging import sys import time import traceback from weakref import WeakValueDictionary import bs4 from selenium import webdriver from app.services import slack from app.utils import db class BaseScraper(object): """ Abstract class for implementing a datasource. """ _instances = WeakValueDictionary() def __init__(self): self._instances[id(self)] = self self.logger = logging.getLogger() self.__browser = webdriver.PhantomJS(service_args=['--load-images=no', '--disk-cache=true']) # self.__browser = webdriver.Chrome() # self.__browser.set_window_size(1280, 1024) # self.__browser.implicitly_wait(10) # self.__browser.set_page_load_timeout(60) def __del__(self): self.__browser.quit() # region scraping methods def _get_search_url(self): """ The search url of the datasource :return string """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _get_offers(self, root): """ Builds a list of offers :return list(Offer) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def __get_offers(self, root): """ Builds a list of offers :return list(BaseOffer) """ offers = [] r_offers = self._get_offers(root) for r_offer in r_offers: o = self._get_offer_object(r_offer) if o is None: continue if self._is_valid_offer(o, r_offer): payload = self._prepare_offer_filling(o, r_offer) o.fill_object(self, r_offer, payload) self._clean_offer_filling(o, r_offer, payload) offers.append(o) else: self.logger.warning("Invalid offer detected. Skipping...") return offers def _get_offer_object(self, r_offer):
def _is_valid_offer(self, offer, r_offer): """ Let the datasource object checks if the offer to be parsed is a valid one. If the validity check allows to prefill some fields, the offer model object can be used. :return True if the offer is valid, False otherwise """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _prepare_offer_filling(self, offer, r_offer): """ Let the datasource object preloads required state to fill the offer object. The offer object can already be filled with some properties to avoid duplicate lookups in r_offers. :return a payload of any data useful for the offer filling """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _clean_offer_filling(self, offer, r_offer, payload): """ Let the datasource object clean up its state. At the time of calling, the offer object must not be modified. """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _has_next_page(self, root): """ Check if there is a next page and returns it parameters. :returns has_next_page(bool),url(string),params(dict) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _load_web_page(self, url): """ Retrieves results and returns a ready to use return object :return BeautifulSoup instance. """ self.__browser.get(url) # This does not throw an exception if it got a 404 html = self.__browser.page_source self.logger.info("GET request: {}".format(url)) result = None try: result = bs4.BeautifulSoup(html, 'html5lib') except Exception as e: self.logger.error("Failed to load webpage {}: {}".format(url, str(e))) finally: return result def _next_page(self): """ Retrieve the next page of results. This method must yield each page. :return list[Offer]: A list of Offer objects. """ has_next = True url = self._get_search_url() while has_next: root = self._load_web_page(url) if root is not None: has_next, url = self._has_next_page(root) yield self.__get_offers(root) @classmethod def get_or_none(cls, obj, key): val = obj.find(key) if val is not None: val = val.text return val # endregion # region datasource identification and scrape methods def get_datasource_name(self): """ Returns the datasource's name. """ return self.__class__.__name__ def scrape(self): """ Runs the datasource. """ self.logger.info("{}: Retrieving offers from {}...".format(time.ctime(), self.get_datasource_name())) try: total_count = 0 for offers in self._next_page(): for o in offers: if db.Offer.is_new_offer(o, self.get_datasource_name()): db.Offer.persist_offer(o, self.get_datasource_name()) # if db.Offer.is_new_offer(o, self.get_datasource_name()) and filter.Filter.apply(o) is False: # db.Offer.persist_offer(o, self.get_datasource_name()) slack.Slack.post_message(o) total_count += 1 except Exception as exc: self.logger.error("Error with the scraping:", sys.exc_info()[0]) traceback.print_exc() else: self.logger.info("{}: Got {} results from {}".format(time.ctime(), total_count, self.get_datasource_name())) # endregion # region field extraction methods # endregion
""" Returns a valid offer object for the offer to parse. :return A BaseOffer object subclass instance """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__))
identifier_body
base_scraper.py
import logging import sys import time import traceback from weakref import WeakValueDictionary import bs4 from selenium import webdriver from app.services import slack from app.utils import db class BaseScraper(object): """ Abstract class for implementing a datasource. """ _instances = WeakValueDictionary() def __init__(self): self._instances[id(self)] = self self.logger = logging.getLogger() self.__browser = webdriver.PhantomJS(service_args=['--load-images=no', '--disk-cache=true']) # self.__browser = webdriver.Chrome() # self.__browser.set_window_size(1280, 1024) # self.__browser.implicitly_wait(10) # self.__browser.set_page_load_timeout(60) def __del__(self): self.__browser.quit() # region scraping methods def _get_search_url(self): """ The search url of the datasource :return string """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _get_offers(self, root): """ Builds a list of offers :return list(Offer) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def __get_offers(self, root): """ Builds a list of offers :return list(BaseOffer) """ offers = [] r_offers = self._get_offers(root) for r_offer in r_offers: o = self._get_offer_object(r_offer) if o is None: continue if self._is_valid_offer(o, r_offer): payload = self._prepare_offer_filling(o, r_offer) o.fill_object(self, r_offer, payload) self._clean_offer_filling(o, r_offer, payload) offers.append(o) else:
return offers def _get_offer_object(self, r_offer): """ Returns a valid offer object for the offer to parse. :return A BaseOffer object subclass instance """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _is_valid_offer(self, offer, r_offer): """ Let the datasource object checks if the offer to be parsed is a valid one. If the validity check allows to prefill some fields, the offer model object can be used. :return True if the offer is valid, False otherwise """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _prepare_offer_filling(self, offer, r_offer): """ Let the datasource object preloads required state to fill the offer object. The offer object can already be filled with some properties to avoid duplicate lookups in r_offers. :return a payload of any data useful for the offer filling """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _clean_offer_filling(self, offer, r_offer, payload): """ Let the datasource object clean up its state. At the time of calling, the offer object must not be modified. """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _has_next_page(self, root): """ Check if there is a next page and returns it parameters. :returns has_next_page(bool),url(string),params(dict) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _load_web_page(self, url): """ Retrieves results and returns a ready to use return object :return BeautifulSoup instance. """ self.__browser.get(url) # This does not throw an exception if it got a 404 html = self.__browser.page_source self.logger.info("GET request: {}".format(url)) result = None try: result = bs4.BeautifulSoup(html, 'html5lib') except Exception as e: self.logger.error("Failed to load webpage {}: {}".format(url, str(e))) finally: return result def _next_page(self): """ Retrieve the next page of results. This method must yield each page. :return list[Offer]: A list of Offer objects. """ has_next = True url = self._get_search_url() while has_next: root = self._load_web_page(url) if root is not None: has_next, url = self._has_next_page(root) yield self.__get_offers(root) @classmethod def get_or_none(cls, obj, key): val = obj.find(key) if val is not None: val = val.text return val # endregion # region datasource identification and scrape methods def get_datasource_name(self): """ Returns the datasource's name. """ return self.__class__.__name__ def scrape(self): """ Runs the datasource. """ self.logger.info("{}: Retrieving offers from {}...".format(time.ctime(), self.get_datasource_name())) try: total_count = 0 for offers in self._next_page(): for o in offers: if db.Offer.is_new_offer(o, self.get_datasource_name()): db.Offer.persist_offer(o, self.get_datasource_name()) # if db.Offer.is_new_offer(o, self.get_datasource_name()) and filter.Filter.apply(o) is False: # db.Offer.persist_offer(o, self.get_datasource_name()) slack.Slack.post_message(o) total_count += 1 except Exception as exc: self.logger.error("Error with the scraping:", sys.exc_info()[0]) traceback.print_exc() else: self.logger.info("{}: Got {} results from {}".format(time.ctime(), total_count, self.get_datasource_name())) # endregion # region field extraction methods # endregion
self.logger.warning("Invalid offer detected. Skipping...")
conditional_block
base_scraper.py
import logging import sys import time import traceback from weakref import WeakValueDictionary import bs4 from selenium import webdriver from app.services import slack from app.utils import db class BaseScraper(object): """ Abstract class for implementing a datasource. """ _instances = WeakValueDictionary() def __init__(self): self._instances[id(self)] = self self.logger = logging.getLogger() self.__browser = webdriver.PhantomJS(service_args=['--load-images=no', '--disk-cache=true']) # self.__browser = webdriver.Chrome() # self.__browser.set_window_size(1280, 1024) # self.__browser.implicitly_wait(10) # self.__browser.set_page_load_timeout(60) def __del__(self): self.__browser.quit() # region scraping methods def _get_search_url(self): """ The search url of the datasource :return string """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _get_offers(self, root): """ Builds a list of offers :return list(Offer) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def __get_offers(self, root): """ Builds a list of offers :return list(BaseOffer) """ offers = [] r_offers = self._get_offers(root) for r_offer in r_offers: o = self._get_offer_object(r_offer) if o is None: continue if self._is_valid_offer(o, r_offer): payload = self._prepare_offer_filling(o, r_offer) o.fill_object(self, r_offer, payload) self._clean_offer_filling(o, r_offer, payload) offers.append(o) else: self.logger.warning("Invalid offer detected. Skipping...") return offers def _get_offer_object(self, r_offer): """ Returns a valid offer object for the offer to parse. :return A BaseOffer object subclass instance """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def
(self, offer, r_offer): """ Let the datasource object checks if the offer to be parsed is a valid one. If the validity check allows to prefill some fields, the offer model object can be used. :return True if the offer is valid, False otherwise """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _prepare_offer_filling(self, offer, r_offer): """ Let the datasource object preloads required state to fill the offer object. The offer object can already be filled with some properties to avoid duplicate lookups in r_offers. :return a payload of any data useful for the offer filling """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _clean_offer_filling(self, offer, r_offer, payload): """ Let the datasource object clean up its state. At the time of calling, the offer object must not be modified. """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _has_next_page(self, root): """ Check if there is a next page and returns it parameters. :returns has_next_page(bool),url(string),params(dict) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _load_web_page(self, url): """ Retrieves results and returns a ready to use return object :return BeautifulSoup instance. """ self.__browser.get(url) # This does not throw an exception if it got a 404 html = self.__browser.page_source self.logger.info("GET request: {}".format(url)) result = None try: result = bs4.BeautifulSoup(html, 'html5lib') except Exception as e: self.logger.error("Failed to load webpage {}: {}".format(url, str(e))) finally: return result def _next_page(self): """ Retrieve the next page of results. This method must yield each page. :return list[Offer]: A list of Offer objects. """ has_next = True url = self._get_search_url() while has_next: root = self._load_web_page(url) if root is not None: has_next, url = self._has_next_page(root) yield self.__get_offers(root) @classmethod def get_or_none(cls, obj, key): val = obj.find(key) if val is not None: val = val.text return val # endregion # region datasource identification and scrape methods def get_datasource_name(self): """ Returns the datasource's name. """ return self.__class__.__name__ def scrape(self): """ Runs the datasource. """ self.logger.info("{}: Retrieving offers from {}...".format(time.ctime(), self.get_datasource_name())) try: total_count = 0 for offers in self._next_page(): for o in offers: if db.Offer.is_new_offer(o, self.get_datasource_name()): db.Offer.persist_offer(o, self.get_datasource_name()) # if db.Offer.is_new_offer(o, self.get_datasource_name()) and filter.Filter.apply(o) is False: # db.Offer.persist_offer(o, self.get_datasource_name()) slack.Slack.post_message(o) total_count += 1 except Exception as exc: self.logger.error("Error with the scraping:", sys.exc_info()[0]) traceback.print_exc() else: self.logger.info("{}: Got {} results from {}".format(time.ctime(), total_count, self.get_datasource_name())) # endregion # region field extraction methods # endregion
_is_valid_offer
identifier_name
base_scraper.py
import logging import sys import time import traceback from weakref import WeakValueDictionary import bs4 from selenium import webdriver from app.services import slack from app.utils import db class BaseScraper(object): """ Abstract class for implementing a datasource. """ _instances = WeakValueDictionary() def __init__(self): self._instances[id(self)] = self self.logger = logging.getLogger() self.__browser = webdriver.PhantomJS(service_args=['--load-images=no', '--disk-cache=true']) # self.__browser = webdriver.Chrome() # self.__browser.set_window_size(1280, 1024) # self.__browser.implicitly_wait(10) # self.__browser.set_page_load_timeout(60) def __del__(self): self.__browser.quit() # region scraping methods def _get_search_url(self): """ The search url of the datasource :return string """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _get_offers(self, root): """ Builds a list of offers :return list(Offer) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def __get_offers(self, root): """ Builds a list of offers :return list(BaseOffer) """ offers = [] r_offers = self._get_offers(root) for r_offer in r_offers: o = self._get_offer_object(r_offer) if o is None: continue if self._is_valid_offer(o, r_offer): payload = self._prepare_offer_filling(o, r_offer) o.fill_object(self, r_offer, payload) self._clean_offer_filling(o, r_offer, payload) offers.append(o) else: self.logger.warning("Invalid offer detected. Skipping...") return offers def _get_offer_object(self, r_offer): """ Returns a valid offer object for the offer to parse. :return A BaseOffer object subclass instance """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _is_valid_offer(self, offer, r_offer): """
If the validity check allows to prefill some fields, the offer model object can be used. :return True if the offer is valid, False otherwise """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _prepare_offer_filling(self, offer, r_offer): """ Let the datasource object preloads required state to fill the offer object. The offer object can already be filled with some properties to avoid duplicate lookups in r_offers. :return a payload of any data useful for the offer filling """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _clean_offer_filling(self, offer, r_offer, payload): """ Let the datasource object clean up its state. At the time of calling, the offer object must not be modified. """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _has_next_page(self, root): """ Check if there is a next page and returns it parameters. :returns has_next_page(bool),url(string),params(dict) """ NotImplementedError("Class {} doesn't implement aMethod()".format(self.__class__.__name__)) def _load_web_page(self, url): """ Retrieves results and returns a ready to use return object :return BeautifulSoup instance. """ self.__browser.get(url) # This does not throw an exception if it got a 404 html = self.__browser.page_source self.logger.info("GET request: {}".format(url)) result = None try: result = bs4.BeautifulSoup(html, 'html5lib') except Exception as e: self.logger.error("Failed to load webpage {}: {}".format(url, str(e))) finally: return result def _next_page(self): """ Retrieve the next page of results. This method must yield each page. :return list[Offer]: A list of Offer objects. """ has_next = True url = self._get_search_url() while has_next: root = self._load_web_page(url) if root is not None: has_next, url = self._has_next_page(root) yield self.__get_offers(root) @classmethod def get_or_none(cls, obj, key): val = obj.find(key) if val is not None: val = val.text return val # endregion # region datasource identification and scrape methods def get_datasource_name(self): """ Returns the datasource's name. """ return self.__class__.__name__ def scrape(self): """ Runs the datasource. """ self.logger.info("{}: Retrieving offers from {}...".format(time.ctime(), self.get_datasource_name())) try: total_count = 0 for offers in self._next_page(): for o in offers: if db.Offer.is_new_offer(o, self.get_datasource_name()): db.Offer.persist_offer(o, self.get_datasource_name()) # if db.Offer.is_new_offer(o, self.get_datasource_name()) and filter.Filter.apply(o) is False: # db.Offer.persist_offer(o, self.get_datasource_name()) slack.Slack.post_message(o) total_count += 1 except Exception as exc: self.logger.error("Error with the scraping:", sys.exc_info()[0]) traceback.print_exc() else: self.logger.info("{}: Got {} results from {}".format(time.ctime(), total_count, self.get_datasource_name())) # endregion # region field extraction methods # endregion
Let the datasource object checks if the offer to be parsed is a valid one.
random_line_split
LayerFactory.js
import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer'; import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer'; import ImageLayer from 'esri/layers/ArcGISImageServiceLayer'; import ImageParameters from 'esri/layers/ImageParameters'; import WebTiledLayer from 'esri/layers/WebTiledLayer'; import GraphicsLayer from 'esri/layers/GraphicsLayer'; import FeatureLayer from 'esri/layers/FeatureLayer'; import SimpleRenderer from 'esri/renderers/SimpleRenderer'; import Symbols from 'helpers/Symbols'; import KEYS from 'js/constants'; import {errors} from 'js/config'; /** * Map Function that gets called for each entry in the provided layers config and returns an array of ArcGIS Layers * @param {object} layer - Layer Config object, see the layersConfig object in js/map/config.js for example * @return {Layer} esriLayer - Some sort of esri layer, current types are: * - ArcGISDynamicMapServiceLayer * - ArcGISTiledMapServiceLayer * - ArcGISImageServiceLayer * - FeatureLayer */ export default (layer) => { if ((!layer.url && layer.type !== 'graphic') || !layer.type) { throw new Error(errors.missingLayerConfig); } let esriLayer, options = {}, imageParameters; switch (layer.type) { case 'tiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new TiledLayer(layer.url, options); break; case 'webtiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new WebTiledLayer(layer.url, options); break; case 'image': options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1; esriLayer = new ImageLayer(layer.url, options); break; case 'dynamic': // Create some image parameters imageParameters = new ImageParameters(); imageParameters.layerOption = ImageParameters.LAYER_OPTION_SHOW; imageParameters.layerIds = layer.layerIds; imageParameters.format = 'png32'; // Populate the options and then add the layer options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1.0; options.imageParameters = imageParameters; if (layer.defaultDefinitionExpression) { var layerDefs = []; layer.layerIds.forEach(val => { // ['ACQ_DATE', 1] // "ACQ_DATE > date'" + new window.Kalendae.moment().subtract(1, 'd').format('YYYY-MM-DD') + "'", const date = new Date(); date.setDate(date.getDate() - layer.defaultDefinitionExpression[1]); const dateString = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); layerDefs[val] = layer.defaultDefinitionExpression[0] + ' > date \'' + dateString + '\''; // layerDefs[val] = layer.defaultDefinitionExpression; }); imageParameters.layerDefinitions = layerDefs; } esriLayer = new DynamicLayer(layer.url, options); break; case 'feature': options.id = layer.id; options.visible = layer.visible || false; options.outFields = layer.outFields || ['*']; esriLayer = new FeatureLayer(layer.url, options); if (layer.id === KEYS.smallGrants)
break; case 'graphic': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new GraphicsLayer(options); break; default: throw new Error(errors.incorrectLayerConfig(layer.type)); } return esriLayer; };
{ const pointSymbol = Symbols.getGrantsPointSymbol(); const renderer = new SimpleRenderer(pointSymbol); esriLayer.renderer = renderer; }
conditional_block
LayerFactory.js
import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer'; import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer'; import ImageLayer from 'esri/layers/ArcGISImageServiceLayer'; import ImageParameters from 'esri/layers/ImageParameters'; import WebTiledLayer from 'esri/layers/WebTiledLayer'; import GraphicsLayer from 'esri/layers/GraphicsLayer'; import FeatureLayer from 'esri/layers/FeatureLayer'; import SimpleRenderer from 'esri/renderers/SimpleRenderer'; import Symbols from 'helpers/Symbols'; import KEYS from 'js/constants'; import {errors} from 'js/config'; /** * Map Function that gets called for each entry in the provided layers config and returns an array of ArcGIS Layers * @param {object} layer - Layer Config object, see the layersConfig object in js/map/config.js for example * @return {Layer} esriLayer - Some sort of esri layer, current types are: * - ArcGISDynamicMapServiceLayer * - ArcGISTiledMapServiceLayer * - ArcGISImageServiceLayer * - FeatureLayer */ export default (layer) => { if ((!layer.url && layer.type !== 'graphic') || !layer.type) { throw new Error(errors.missingLayerConfig); } let esriLayer, options = {}, imageParameters; switch (layer.type) { case 'tiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new TiledLayer(layer.url, options); break; case 'webtiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new WebTiledLayer(layer.url, options); break; case 'image': options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1; esriLayer = new ImageLayer(layer.url, options); break; case 'dynamic': // Create some image parameters imageParameters = new ImageParameters(); imageParameters.layerOption = ImageParameters.LAYER_OPTION_SHOW; imageParameters.layerIds = layer.layerIds; imageParameters.format = 'png32'; // Populate the options and then add the layer options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1.0; options.imageParameters = imageParameters; if (layer.defaultDefinitionExpression) { var layerDefs = []; layer.layerIds.forEach(val => { // ['ACQ_DATE', 1] // "ACQ_DATE > date'" + new window.Kalendae.moment().subtract(1, 'd').format('YYYY-MM-DD') + "'", const date = new Date(); date.setDate(date.getDate() - layer.defaultDefinitionExpression[1]); const dateString = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); layerDefs[val] = layer.defaultDefinitionExpression[0] + ' > date \'' + dateString + '\''; // layerDefs[val] = layer.defaultDefinitionExpression; }); imageParameters.layerDefinitions = layerDefs; } esriLayer = new DynamicLayer(layer.url, options);
options.outFields = layer.outFields || ['*']; esriLayer = new FeatureLayer(layer.url, options); if (layer.id === KEYS.smallGrants) { const pointSymbol = Symbols.getGrantsPointSymbol(); const renderer = new SimpleRenderer(pointSymbol); esriLayer.renderer = renderer; } break; case 'graphic': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new GraphicsLayer(options); break; default: throw new Error(errors.incorrectLayerConfig(layer.type)); } return esriLayer; };
break; case 'feature': options.id = layer.id; options.visible = layer.visible || false;
random_line_split
types.rs
extern crate serde_json; extern crate rmp_serde; use std::cmp::Eq; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use super::zmq; use errors::common::CommonError; use services::ledger::merkletree::merkletree::MerkleTree; use utils::json::{JsonDecodable, JsonEncodable}; #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct NodeData { pub alias: String, pub client_ip: String, pub client_port: u32, pub node_ip: String, pub node_port: u32, pub services: Vec<String>, } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct GenTransaction { pub data: NodeData, pub dest: String, pub identifier: String, #[serde(rename = "txnId")] pub txn_id: Option<String>, #[serde(rename = "type")] pub txn_type: String, } impl JsonEncodable for GenTransaction {} impl<'a> JsonDecodable<'a> for GenTransaction {} impl GenTransaction { pub fn to_msg_pack(&self) -> Result<Vec<u8>, rmp_serde::encode::Error> { rmp_serde::to_vec_named(self) } } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug)] pub struct LedgerStatus { pub txnSeqNo: usize, pub merkleRoot: String, pub ledgerId: u8, pub ppSeqNo: Option<String>, pub viewNo: Option<String>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug)] pub struct ConsistencyProof { //TODO almost all fields Option<> or find better approach pub seqNoEnd: usize, pub seqNoStart: usize, pub ledgerId: usize, pub hashes: Vec<String>, pub oldMerkleRoot: String, pub newMerkleRoot: String, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] pub struct CatchupReq { pub ledgerId: usize, pub seqNoStart: usize, pub seqNoEnd: usize, pub catchupTill: usize, } impl<'a> JsonDecodable<'a> for CatchupReq {} #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct CatchupRep { pub ledgerId: usize, pub consProof: Vec<String>, pub txns: HashMap<String, serde_json::Value>, } impl CatchupRep { pub fn min_tx(&self) -> Result<usize, CommonError> { let mut min = None; for (k, _) in self.txns.iter() { let val = k.parse::<usize>() .map_err(|err| CommonError::InvalidStructure(format!("{:?}", err)))?; match min { None => min = Some(val), Some(m) => if val < m { min = Some(val) } } } min.ok_or(CommonError::InvalidStructure(format!("Empty Map"))) } }
#[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Response { pub req_id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct PoolLedgerTxns { pub txn: Response, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct SimpleRequest { pub req_id: u64, } impl JsonEncodable for SimpleRequest {} impl<'a> JsonDecodable<'a> for SimpleRequest {} #[serde(tag = "op")] #[derive(Serialize, Deserialize, Debug)] pub enum Message { #[serde(rename = "CONSISTENCY_PROOF")] ConsistencyProof(ConsistencyProof), #[serde(rename = "LEDGER_STATUS")] LedgerStatus(LedgerStatus), #[serde(rename = "CATCHUP_REQ")] CatchupReq(CatchupReq), #[serde(rename = "CATCHUP_REP")] CatchupRep(CatchupRep), #[serde(rename = "REQACK")] ReqACK(Response), #[serde(rename = "REQNACK")] ReqNACK(Response), #[serde(rename = "REPLY")] Reply(Reply), #[serde(rename = "REJECT")] Reject(Response), #[serde(rename = "POOL_LEDGER_TXNS")] PoolLedgerTxns(PoolLedgerTxns), Ping, Pong, } impl Message { pub fn from_raw_str(str: &str) -> Result<Message, serde_json::Error> { match str { "po" => Ok(Message::Pong), "pi" => Ok(Message::Ping), _ => Message::from_json(str), } } } impl JsonEncodable for Message {} impl<'a> JsonDecodable<'a> for Message {} #[derive(Serialize, Deserialize)] pub struct PoolConfig { pub genesis_txn: String } impl JsonEncodable for PoolConfig {} impl<'a> JsonDecodable<'a> for PoolConfig {} impl PoolConfig { pub fn default_for_name(name: &str) -> PoolConfig { let mut txn = name.to_string(); txn += ".txn"; PoolConfig { genesis_txn: txn } } } pub struct RemoteNode { pub name: String, pub public_key: Vec<u8>, pub zaddr: String, pub zsock: Option<zmq::Socket>, pub is_blacklisted: bool, } pub struct CatchUpProcess { pub merkle_tree: MerkleTree, pub pending_reps: Vec<(CatchupRep, usize)>, } pub trait MinValue { fn get_min_index(&self) -> Result<usize, CommonError>; } impl MinValue for Vec<(CatchupRep, usize)> { fn get_min_index(&self) -> Result<usize, CommonError> { let mut res = None; for (index, &(ref catchup_rep, _)) in self.iter().enumerate() { match res { None => { res = Some((catchup_rep, index)); } Some((min_rep, i)) => if catchup_rep.min_tx()? < min_rep.min_tx()? { res = Some((catchup_rep, index)); } } } Ok(res.ok_or(CommonError::InvalidStructure("Element not Found".to_string()))?.1) } } #[derive(Debug)] pub struct HashableValue { pub inner: serde_json::Value } impl Eq for HashableValue {} impl Hash for HashableValue { fn hash<H: Hasher>(&self, state: &mut H) { serde_json::to_string(&self.inner).unwrap().hash(state); //TODO } } impl PartialEq for HashableValue { fn eq(&self, other: &HashableValue) -> bool { self.inner.eq(&other.inner) } } #[derive(Debug, PartialEq, Eq)] pub struct CommandProcess { pub nack_cnt: usize, pub replies: HashMap<HashableValue, usize>, pub cmd_ids: Vec<i32>, } #[derive(Debug, PartialEq, Eq)] pub enum ZMQLoopAction { RequestToSend(RequestToSend), MessageToProcess(MessageToProcess), Terminate(i32), Refresh(i32), } #[derive(Debug, PartialEq, Eq)] pub struct RequestToSend { pub request: String, pub id: i32, } #[derive(Debug, PartialEq, Eq)] pub struct MessageToProcess { pub message: String, pub node_idx: usize, }
#[derive(Serialize, Deserialize, Debug)] pub struct Reply { pub result: Response, }
random_line_split
types.rs
extern crate serde_json; extern crate rmp_serde; use std::cmp::Eq; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use super::zmq; use errors::common::CommonError; use services::ledger::merkletree::merkletree::MerkleTree; use utils::json::{JsonDecodable, JsonEncodable}; #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct NodeData { pub alias: String, pub client_ip: String, pub client_port: u32, pub node_ip: String, pub node_port: u32, pub services: Vec<String>, } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] pub struct GenTransaction { pub data: NodeData, pub dest: String, pub identifier: String, #[serde(rename = "txnId")] pub txn_id: Option<String>, #[serde(rename = "type")] pub txn_type: String, } impl JsonEncodable for GenTransaction {} impl<'a> JsonDecodable<'a> for GenTransaction {} impl GenTransaction { pub fn to_msg_pack(&self) -> Result<Vec<u8>, rmp_serde::encode::Error> { rmp_serde::to_vec_named(self) } } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug)] pub struct LedgerStatus { pub txnSeqNo: usize, pub merkleRoot: String, pub ledgerId: u8, pub ppSeqNo: Option<String>, pub viewNo: Option<String>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug)] pub struct ConsistencyProof { //TODO almost all fields Option<> or find better approach pub seqNoEnd: usize, pub seqNoStart: usize, pub ledgerId: usize, pub hashes: Vec<String>, pub oldMerkleRoot: String, pub newMerkleRoot: String, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] pub struct CatchupReq { pub ledgerId: usize, pub seqNoStart: usize, pub seqNoEnd: usize, pub catchupTill: usize, } impl<'a> JsonDecodable<'a> for CatchupReq {} #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct CatchupRep { pub ledgerId: usize, pub consProof: Vec<String>, pub txns: HashMap<String, serde_json::Value>, } impl CatchupRep { pub fn min_tx(&self) -> Result<usize, CommonError> { let mut min = None; for (k, _) in self.txns.iter() { let val = k.parse::<usize>() .map_err(|err| CommonError::InvalidStructure(format!("{:?}", err)))?; match min { None => min = Some(val), Some(m) => if val < m { min = Some(val) } } } min.ok_or(CommonError::InvalidStructure(format!("Empty Map"))) } } #[derive(Serialize, Deserialize, Debug)] pub struct Reply { pub result: Response, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Response { pub req_id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct PoolLedgerTxns { pub txn: Response, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct SimpleRequest { pub req_id: u64, } impl JsonEncodable for SimpleRequest {} impl<'a> JsonDecodable<'a> for SimpleRequest {} #[serde(tag = "op")] #[derive(Serialize, Deserialize, Debug)] pub enum Message { #[serde(rename = "CONSISTENCY_PROOF")] ConsistencyProof(ConsistencyProof), #[serde(rename = "LEDGER_STATUS")] LedgerStatus(LedgerStatus), #[serde(rename = "CATCHUP_REQ")] CatchupReq(CatchupReq), #[serde(rename = "CATCHUP_REP")] CatchupRep(CatchupRep), #[serde(rename = "REQACK")] ReqACK(Response), #[serde(rename = "REQNACK")] ReqNACK(Response), #[serde(rename = "REPLY")] Reply(Reply), #[serde(rename = "REJECT")] Reject(Response), #[serde(rename = "POOL_LEDGER_TXNS")] PoolLedgerTxns(PoolLedgerTxns), Ping, Pong, } impl Message { pub fn
(str: &str) -> Result<Message, serde_json::Error> { match str { "po" => Ok(Message::Pong), "pi" => Ok(Message::Ping), _ => Message::from_json(str), } } } impl JsonEncodable for Message {} impl<'a> JsonDecodable<'a> for Message {} #[derive(Serialize, Deserialize)] pub struct PoolConfig { pub genesis_txn: String } impl JsonEncodable for PoolConfig {} impl<'a> JsonDecodable<'a> for PoolConfig {} impl PoolConfig { pub fn default_for_name(name: &str) -> PoolConfig { let mut txn = name.to_string(); txn += ".txn"; PoolConfig { genesis_txn: txn } } } pub struct RemoteNode { pub name: String, pub public_key: Vec<u8>, pub zaddr: String, pub zsock: Option<zmq::Socket>, pub is_blacklisted: bool, } pub struct CatchUpProcess { pub merkle_tree: MerkleTree, pub pending_reps: Vec<(CatchupRep, usize)>, } pub trait MinValue { fn get_min_index(&self) -> Result<usize, CommonError>; } impl MinValue for Vec<(CatchupRep, usize)> { fn get_min_index(&self) -> Result<usize, CommonError> { let mut res = None; for (index, &(ref catchup_rep, _)) in self.iter().enumerate() { match res { None => { res = Some((catchup_rep, index)); } Some((min_rep, i)) => if catchup_rep.min_tx()? < min_rep.min_tx()? { res = Some((catchup_rep, index)); } } } Ok(res.ok_or(CommonError::InvalidStructure("Element not Found".to_string()))?.1) } } #[derive(Debug)] pub struct HashableValue { pub inner: serde_json::Value } impl Eq for HashableValue {} impl Hash for HashableValue { fn hash<H: Hasher>(&self, state: &mut H) { serde_json::to_string(&self.inner).unwrap().hash(state); //TODO } } impl PartialEq for HashableValue { fn eq(&self, other: &HashableValue) -> bool { self.inner.eq(&other.inner) } } #[derive(Debug, PartialEq, Eq)] pub struct CommandProcess { pub nack_cnt: usize, pub replies: HashMap<HashableValue, usize>, pub cmd_ids: Vec<i32>, } #[derive(Debug, PartialEq, Eq)] pub enum ZMQLoopAction { RequestToSend(RequestToSend), MessageToProcess(MessageToProcess), Terminate(i32), Refresh(i32), } #[derive(Debug, PartialEq, Eq)] pub struct RequestToSend { pub request: String, pub id: i32, } #[derive(Debug, PartialEq, Eq)] pub struct MessageToProcess { pub message: String, pub node_idx: usize, }
from_raw_str
identifier_name
test_parsers.py
import json from io import BytesIO import pytest from rest_framework.exceptions import ParseError from rest_framework_json_api.parsers import JSONParser from rest_framework_json_api.utils import format_value from tests.views import BasicModelViewSet class TestJSONParser: @pytest.fixture def parser(self):
@pytest.fixture def parse(self, parser): def parse_wrapper(data, parser_context): stream = BytesIO(json.dumps(data).encode("utf-8")) return parser.parse(stream, None, parser_context) return parse_wrapper @pytest.fixture def parser_context(self, rf): return {"request": rf.post("/"), "kwargs": {}, "view": BasicModelViewSet()} @pytest.mark.parametrize( "format_field_names", [ False, "dasherize", "camelize", "capitalize", "underscore", ], ) def test_parse_formats_field_names( self, settings, format_field_names, parse, parser_context, ): settings.JSON_API_FORMAT_FIELD_NAMES = format_field_names data = { "data": { "id": "123", "type": "BasicModel", "attributes": { format_value("test_attribute", format_field_names): "test-value" }, "relationships": { format_value("test_relationship", format_field_names): { "data": {"type": "TestRelationship", "id": "123"} } }, } } result = parse(data, parser_context) assert result == { "id": "123", "type": "BasicModel", "test_attribute": "test-value", "test_relationship": {"id": "123", "type": "TestRelationship"}, } def test_parse_extracts_meta(self, parse, parser_context): data = { "data": { "type": "BasicModel", }, "meta": {"random_key": "random_value"}, } result = parse(data, parser_context) assert result["_meta"] == data["meta"] def test_parse_with_default_arguments(self, parse): data = { "data": { "type": "BasicModel", }, } result = parse(data, None) assert result == {"type": "BasicModel"} def test_parse_preserves_json_value_field_names( self, settings, parse, parser_context ): settings.JSON_API_FORMAT_FIELD_NAMES = "dasherize" data = { "data": { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, }, } result = parse(data, parser_context) assert result["json_value"] == {"JsonKey": "JsonValue"} def test_parse_raises_error_on_empty_data(self, parse, parser_context): data = [] with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "Received document does not contain primary data" == str(excinfo.value) def test_parse_fails_on_list_of_objects(self, parse, parser_context): data = { "data": [ { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, } ], } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert ( "Received data is not a valid JSON:API Resource Identifier Object" == str(excinfo.value) ) def test_parse_fails_when_id_is_missing_on_patch(self, rf, parse, parser_context): parser_context["request"] = rf.patch("/") data = { "data": { "type": "BasicModel", }, } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "The resource identifier object must contain an 'id' member" == str( excinfo.value )
return JSONParser()
identifier_body
test_parsers.py
import json from io import BytesIO import pytest from rest_framework.exceptions import ParseError from rest_framework_json_api.parsers import JSONParser from rest_framework_json_api.utils import format_value from tests.views import BasicModelViewSet class TestJSONParser: @pytest.fixture def parser(self): return JSONParser() @pytest.fixture def parse(self, parser): def parse_wrapper(data, parser_context): stream = BytesIO(json.dumps(data).encode("utf-8")) return parser.parse(stream, None, parser_context) return parse_wrapper @pytest.fixture def parser_context(self, rf): return {"request": rf.post("/"), "kwargs": {}, "view": BasicModelViewSet()} @pytest.mark.parametrize( "format_field_names", [ False, "dasherize", "camelize", "capitalize", "underscore", ], ) def test_parse_formats_field_names( self, settings, format_field_names, parse, parser_context, ): settings.JSON_API_FORMAT_FIELD_NAMES = format_field_names data = { "data": { "id": "123", "type": "BasicModel", "attributes": { format_value("test_attribute", format_field_names): "test-value" }, "relationships": { format_value("test_relationship", format_field_names): { "data": {"type": "TestRelationship", "id": "123"} } }, } } result = parse(data, parser_context)
"test_attribute": "test-value", "test_relationship": {"id": "123", "type": "TestRelationship"}, } def test_parse_extracts_meta(self, parse, parser_context): data = { "data": { "type": "BasicModel", }, "meta": {"random_key": "random_value"}, } result = parse(data, parser_context) assert result["_meta"] == data["meta"] def test_parse_with_default_arguments(self, parse): data = { "data": { "type": "BasicModel", }, } result = parse(data, None) assert result == {"type": "BasicModel"} def test_parse_preserves_json_value_field_names( self, settings, parse, parser_context ): settings.JSON_API_FORMAT_FIELD_NAMES = "dasherize" data = { "data": { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, }, } result = parse(data, parser_context) assert result["json_value"] == {"JsonKey": "JsonValue"} def test_parse_raises_error_on_empty_data(self, parse, parser_context): data = [] with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "Received document does not contain primary data" == str(excinfo.value) def test_parse_fails_on_list_of_objects(self, parse, parser_context): data = { "data": [ { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, } ], } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert ( "Received data is not a valid JSON:API Resource Identifier Object" == str(excinfo.value) ) def test_parse_fails_when_id_is_missing_on_patch(self, rf, parse, parser_context): parser_context["request"] = rf.patch("/") data = { "data": { "type": "BasicModel", }, } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "The resource identifier object must contain an 'id' member" == str( excinfo.value )
assert result == { "id": "123", "type": "BasicModel",
random_line_split
test_parsers.py
import json from io import BytesIO import pytest from rest_framework.exceptions import ParseError from rest_framework_json_api.parsers import JSONParser from rest_framework_json_api.utils import format_value from tests.views import BasicModelViewSet class TestJSONParser: @pytest.fixture def parser(self): return JSONParser() @pytest.fixture def
(self, parser): def parse_wrapper(data, parser_context): stream = BytesIO(json.dumps(data).encode("utf-8")) return parser.parse(stream, None, parser_context) return parse_wrapper @pytest.fixture def parser_context(self, rf): return {"request": rf.post("/"), "kwargs": {}, "view": BasicModelViewSet()} @pytest.mark.parametrize( "format_field_names", [ False, "dasherize", "camelize", "capitalize", "underscore", ], ) def test_parse_formats_field_names( self, settings, format_field_names, parse, parser_context, ): settings.JSON_API_FORMAT_FIELD_NAMES = format_field_names data = { "data": { "id": "123", "type": "BasicModel", "attributes": { format_value("test_attribute", format_field_names): "test-value" }, "relationships": { format_value("test_relationship", format_field_names): { "data": {"type": "TestRelationship", "id": "123"} } }, } } result = parse(data, parser_context) assert result == { "id": "123", "type": "BasicModel", "test_attribute": "test-value", "test_relationship": {"id": "123", "type": "TestRelationship"}, } def test_parse_extracts_meta(self, parse, parser_context): data = { "data": { "type": "BasicModel", }, "meta": {"random_key": "random_value"}, } result = parse(data, parser_context) assert result["_meta"] == data["meta"] def test_parse_with_default_arguments(self, parse): data = { "data": { "type": "BasicModel", }, } result = parse(data, None) assert result == {"type": "BasicModel"} def test_parse_preserves_json_value_field_names( self, settings, parse, parser_context ): settings.JSON_API_FORMAT_FIELD_NAMES = "dasherize" data = { "data": { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, }, } result = parse(data, parser_context) assert result["json_value"] == {"JsonKey": "JsonValue"} def test_parse_raises_error_on_empty_data(self, parse, parser_context): data = [] with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "Received document does not contain primary data" == str(excinfo.value) def test_parse_fails_on_list_of_objects(self, parse, parser_context): data = { "data": [ { "type": "BasicModel", "attributes": {"json-value": {"JsonKey": "JsonValue"}}, } ], } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert ( "Received data is not a valid JSON:API Resource Identifier Object" == str(excinfo.value) ) def test_parse_fails_when_id_is_missing_on_patch(self, rf, parse, parser_context): parser_context["request"] = rf.patch("/") data = { "data": { "type": "BasicModel", }, } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "The resource identifier object must contain an 'id' member" == str( excinfo.value )
parse
identifier_name
addon.js
'use strict'; var fs = require('fs'); var path = require('path'); var deprecate = require('../utilities/deprecate'); var assign = require('lodash-node/modern/objects/assign'); function Addon(project)
Addon.__proto__ = require('./core-object'); Addon.prototype.constructor = Addon; function unwatchedTree(dir) { return { read: function() { return dir; }, cleanup: function() { } }; } Addon.prototype.treePaths = { app: 'app', styles: 'app/styles', templates: 'app/templates', vendor: 'vendor' }; Addon.prototype.treeFor = function treeFor(name) { var treePath = path.join(this._root, this.treePaths[name]); if (fs.existsSync(treePath)) { return unwatchedTree(treePath); } }; Addon.resolvePath = function(addon) { var addonMain; deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']); addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js'; // Resolve will fail unless it has an extension if(!path.extname(addonMain)) { addonMain += '.js'; } return path.resolve(addon.path, addonMain); }; Addon.lookup = function(addon) { var Constructor, addonModule, modulePath, moduleDir; modulePath = Addon.resolvePath(addon); moduleDir = path.dirname(modulePath); if (fs.existsSync(modulePath)) { addonModule = require(modulePath); if (typeof addonModule === 'function') { Constructor = addonModule; Constructor.prototype._root = moduleDir; } else { Constructor = Addon.extend(assign(addonModule, { _root: moduleDir })); } } else { Constructor = Addon.extend({ name: '(generated ' + addon.pkg.name + ' addon)', _root: moduleDir }); } return Constructor; }; module.exports = Addon;
{ this.project = project; }
identifier_body
addon.js
'use strict'; var fs = require('fs'); var path = require('path'); var deprecate = require('../utilities/deprecate'); var assign = require('lodash-node/modern/objects/assign'); function Addon(project) { this.project = project; } Addon.__proto__ = require('./core-object'); Addon.prototype.constructor = Addon; function
(dir) { return { read: function() { return dir; }, cleanup: function() { } }; } Addon.prototype.treePaths = { app: 'app', styles: 'app/styles', templates: 'app/templates', vendor: 'vendor' }; Addon.prototype.treeFor = function treeFor(name) { var treePath = path.join(this._root, this.treePaths[name]); if (fs.existsSync(treePath)) { return unwatchedTree(treePath); } }; Addon.resolvePath = function(addon) { var addonMain; deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']); addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js'; // Resolve will fail unless it has an extension if(!path.extname(addonMain)) { addonMain += '.js'; } return path.resolve(addon.path, addonMain); }; Addon.lookup = function(addon) { var Constructor, addonModule, modulePath, moduleDir; modulePath = Addon.resolvePath(addon); moduleDir = path.dirname(modulePath); if (fs.existsSync(modulePath)) { addonModule = require(modulePath); if (typeof addonModule === 'function') { Constructor = addonModule; Constructor.prototype._root = moduleDir; } else { Constructor = Addon.extend(assign(addonModule, { _root: moduleDir })); } } else { Constructor = Addon.extend({ name: '(generated ' + addon.pkg.name + ' addon)', _root: moduleDir }); } return Constructor; }; module.exports = Addon;
unwatchedTree
identifier_name
addon.js
'use strict'; var fs = require('fs'); var path = require('path'); var deprecate = require('../utilities/deprecate'); var assign = require('lodash-node/modern/objects/assign'); function Addon(project) { this.project = project; } Addon.__proto__ = require('./core-object'); Addon.prototype.constructor = Addon; function unwatchedTree(dir) { return { read: function() { return dir; }, cleanup: function() { } }; } Addon.prototype.treePaths = { app: 'app', styles: 'app/styles', templates: 'app/templates', vendor: 'vendor' }; Addon.prototype.treeFor = function treeFor(name) { var treePath = path.join(this._root, this.treePaths[name]); if (fs.existsSync(treePath)) { return unwatchedTree(treePath); } }; Addon.resolvePath = function(addon) { var addonMain; deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']); addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js'; // Resolve will fail unless it has an extension if(!path.extname(addonMain)) { addonMain += '.js'; } return path.resolve(addon.path, addonMain); }; Addon.lookup = function(addon) { var Constructor, addonModule, modulePath, moduleDir; modulePath = Addon.resolvePath(addon); moduleDir = path.dirname(modulePath); if (fs.existsSync(modulePath)) { addonModule = require(modulePath); if (typeof addonModule === 'function') { Constructor = addonModule; Constructor.prototype._root = moduleDir; } else { Constructor = Addon.extend(assign(addonModule, { _root: moduleDir })); } } else { Constructor = Addon.extend({ name: '(generated ' + addon.pkg.name + ' addon)',
}; module.exports = Addon;
_root: moduleDir }); } return Constructor;
random_line_split
addon.js
'use strict'; var fs = require('fs'); var path = require('path'); var deprecate = require('../utilities/deprecate'); var assign = require('lodash-node/modern/objects/assign'); function Addon(project) { this.project = project; } Addon.__proto__ = require('./core-object'); Addon.prototype.constructor = Addon; function unwatchedTree(dir) { return { read: function() { return dir; }, cleanup: function() { } }; } Addon.prototype.treePaths = { app: 'app', styles: 'app/styles', templates: 'app/templates', vendor: 'vendor' }; Addon.prototype.treeFor = function treeFor(name) { var treePath = path.join(this._root, this.treePaths[name]); if (fs.existsSync(treePath)) { return unwatchedTree(treePath); } }; Addon.resolvePath = function(addon) { var addonMain; deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']); addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js'; // Resolve will fail unless it has an extension if(!path.extname(addonMain))
return path.resolve(addon.path, addonMain); }; Addon.lookup = function(addon) { var Constructor, addonModule, modulePath, moduleDir; modulePath = Addon.resolvePath(addon); moduleDir = path.dirname(modulePath); if (fs.existsSync(modulePath)) { addonModule = require(modulePath); if (typeof addonModule === 'function') { Constructor = addonModule; Constructor.prototype._root = moduleDir; } else { Constructor = Addon.extend(assign(addonModule, { _root: moduleDir })); } } else { Constructor = Addon.extend({ name: '(generated ' + addon.pkg.name + ' addon)', _root: moduleDir }); } return Constructor; }; module.exports = Addon;
{ addonMain += '.js'; }
conditional_block